From 4f065ccbbf72f683047b1559dedaaa03dc480a5c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:52:50 -0800 Subject: [PATCH 01/78] Part of #978: Show Opacity in the Color Wheel panel sets the opacity of the fill or stroke The Color Wheel panel menu gets Show Opacity, kept with the preferences (`ui.colorWheel {opacity}`). It adds a row under the wheel or the box with a slider and a percent field. The row sets the opacity of the fill or stroke item, the selected gradient stop or the selected freeform point (the first stop or point when none is selected, as for a color pick), and a drag is one undo step. The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing. - paint.setFill and paint.setStroke take `opacity` (a percentage, 0 to 100), with or without a new paint. An opacity that no target takes is an error and leaves the paint undone too. paint.proxies answers `fillOpacity` and `strokeOpacity` from the first row the command would edit. A graph series keeps the opacity on regeneration. - The opacity slider and the swatch chips draw the same checkerboard. - New error and menu strings have rows in the catalogs. Docs: docs/mcp.md, docs/control-protocol.md, docs/target-app-parity.md. --- crates/engine/src/cmd/graph/tests.rs | 19 ++ crates/engine/src/cmd/paint.rs | 297 +++++++++++----- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/paintopacity.rs | 293 ++++++++++++++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 7 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 7 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 7 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 7 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 7 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 7 + crates/ui-egui/src/i18n/nl.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 7 + crates/ui-egui/src/i18n/pt-br.tsv | 7 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 7 + crates/ui-egui/src/i18n/tests.rs | 24 ++ crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 7 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 7 + crates/ui-egui/src/i18n/zh-hant.tsv | 7 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels.rs | 2 + crates/ui-egui/src/panels/color_wheel.rs | 115 ++++++- .../src/panels/tests_color_wheel_box.rs | 26 +- .../src/panels/tests_color_wheel_opacity.rs | 322 ++++++++++++++++++ crates/ui-egui/src/state.rs | 2 +- crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/chips.rs | 11 +- crates/ui-egui/src/widgets/color.rs | 39 ++- docs/control-protocol.md | 7 +- docs/mcp.md | 17 +- docs/target-app-parity.md | 1 + 46 files changed, 1227 insertions(+), 110 deletions(-) create mode 100644 crates/engine/src/tests/paintopacity.rs create mode 100644 crates/ui-egui/src/panels/tests_color_wheel_opacity.rs diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 140fb3c933..412160134c 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -333,6 +333,25 @@ fn an_item_opacity_on_a_series_mark_survives_regeneration() { assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), None)); } +/// `paint.setFill {opacity}` and `paint.setStroke {opacity}` on one series mark are kept by the graph as the transparency +/// commands' item opacity is: every path of that series has them after the graph is drawn again. +#[test] +fn a_paint_opacity_on_a_series_mark_survives_regeneration() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = graph(&mut s, "column"); + let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.execute("paint.setFill", &json!({"ids": [bar.0], "opacity": 40})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [bar.0], "color": "#ff0000", "opacity": 60})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), Some(0.6))); + s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let marks = series(&n, 0).children().unwrap().to_vec(); + let opacities: Vec<(f32, f32)> = marks.iter().map(|m| (m.appearance.fill().unwrap().opacity, m.appearance.stroke().unwrap().opacity)).collect(); + assert!(opacities.iter().all(|o| *o == (0.4, 0.6)), "{opacities:?}"); +} + /// Clear Appearance and Reduce to Basic Appearance on a series mark take its fill and stroke opacity away, and the /// graph keeps none, so the series stays opaque when it is drawn again. #[test] diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 3ec28e7ce7..7039f62e5a 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors; the gradient mesh points last clicked with the Mesh tool or Direct Selection take it themselves; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Stroke", [], None, - "{…as paint.setFill, item?: the stroke item to set} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", + "{…as paint.setFill, item?: the stroke item to set, opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", has_doc, |s, p| { set_paint(s, p, false) } ), @@ -154,7 +154,7 @@ pub fn proxy_specs() -> Vec { "Fill and Stroke", [], None, - "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy}", + "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy, fillOpacity, strokeOpacity: 0..100, the opacity of the fill (stroke) item that paint.setFill {opacity} sets, from the first selected object (or painted object in a selected group) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, and when only type characters or objects without that item are selected}", always, proxies ), @@ -208,6 +208,44 @@ impl Session { nodes.first().map(|n| (Cow::Borrowed(*n), None)) } + /// The opacity (0..1) of the fill (or stroke) that `paint.setFill {opacity}` sets: the item's, + /// or for a gradient mesh with points picked the first picked point's. The rows the command + /// would edit are read in order (a group without an active Appearance row stands for its + /// contents), and the first that exists answers. `None` with nothing selected, for an object + /// selected in a symbol instance, and when only type characters or objects without that item + /// are selected. + pub fn proxy_opacity(&self, stroke: bool) -> Option { + let st = self.active()?; + if st.selection.symbol_part.is_some() { + return None; + } + let item = self.appearance_item(); + let of = |n: &Node, item: Option| -> Option { + if item.is_none() && matches!(n.kind, NodeKind::Text(_)) { + return None; + } + if !stroke + && item.is_none() + && let NodeKind::Mesh(m) = &n.kind + && let Some((_, points)) = picked_mesh_points(self, &[n.id]).first() + { + return points.first().and_then(|i| m.points.get(*i)).map(|q| q.opacity); + } + if stroke { n.appearance.stroke_at(item).map(|s| s.opacity) } else { n.appearance.fill_at(item).map(|f| f.opacity) } + }; + let subjects = st.selection.subjects(); + // As the command picks its rows (ItemTarget::of_kind): the active item when it is a row of + // this kind in the first selected object's stack, read in the selected objects' own + // stacks; else the topmost one of the painted leaves (a group's contents). + let first = subjects.first().and_then(|id| st.doc.node(*id)); + let active = item.filter(|i| first.and_then(|n| n.appearance.items.get(*i)).is_some_and(|it| it.is_fill() == !stroke)); + if active.is_some() { + return subjects.iter().filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, active)); + } + let leaves = super::leaf_targets(self, subjects).ok()?; + leaves.iter().filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None)) + } + pub(crate) fn remember_paint_now(&mut self, p: &Paint) { match p { Paint::Solid { color, .. } => { @@ -321,7 +359,12 @@ impl Session { fn proxies(s: &mut Session, _: &Value) -> Result { let (fill, stroke) = s.proxy_paints(); let (fill_mixed, stroke_mixed) = s.proxy_mixed(); - Ok(json!({"fill": fill, "stroke": stroke, "fillActive": s.fill_active, "fillMixed": fill_mixed, "strokeMixed": stroke_mixed})) + // As transparency.info answers an opacity: a percentage to two places. + let percent = |o: Option| o.map(|o| (f64::from(o) * 10_000.0).round() / 100.0); + Ok(json!({ + "fill": fill, "stroke": stroke, "fillActive": s.fill_active, "fillMixed": fill_mixed, "strokeMixed": stroke_mixed, + "fillOpacity": percent(s.proxy_opacity(false)), "strokeOpacity": percent(s.proxy_opacity(true)), + })) } /// `stroke` param, defaulting to the proxy that is in front. @@ -440,13 +483,34 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result { return Err(bad(cmd, "`tint` goes with a global or spot `swatch`")); } check_keep_model(p, cmd)?; - let paint = paint_from(s, p)?.ok_or_else(|| bad(cmd, "give color, none, swatch or gradient"))?; + let opacity = opacity_param(p, cmd)?; + let paint = paint_from(s, p)?; + if paint.is_none() && opacity.is_none() { + return Err(bad(cmd, "give color, none, swatch, gradient or opacity")); + } // As `paint.editGradient`: a `dither` given applies to gradient fills only. A gradient swatch // (named) keeps its own dither; `"swatch": null` names none. - if !fill && matches!(&paint, Paint::Gradient(g) if g.gradient.dither) && p.get("swatch").and_then(Value::as_str).is_none() { + if !fill && matches!(&paint, Some(Paint::Gradient(g)) if g.gradient.dither) && p.get("swatch").and_then(Value::as_str).is_none() { return Err(bad(cmd, "`dither` applies to gradient fills (paint.setFill)")); } - apply_paint(s, p, paint, fill) + apply_paint_opacity(s, p, paint, opacity, fill) +} + +/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None` +/// when it is left out or null. +fn opacity_param(p: &Value, cmd: &str) -> Result> { + match p.get("opacity") { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_f64() { + Some(o) if (0.0..=100.0).contains(&o) => Ok(Some((o / 100.0) as f32)), + _ => Err(bad(cmd, "`opacity` must be a number from 0 to 100")), + }, + } +} + +/// The error for an `opacity` that would go to type characters, which have no opacity of their own. +fn characters_have_no_opacity(cmd: &str) -> EngineError { + bad(cmd, "type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke") } /// [`apply_paint`] on the proxy named by `stroke` (default: the active one), focusing it. @@ -459,15 +523,28 @@ fn apply_to_proxy(s: &mut Session, p: &Value, paint: Paint, cmd: &str) -> Result /// `paint.setFill`) and of the defaults for new art, focus its proxy unless `focus` is false, and /// remember the paint. Replies `{objects}`: how many objects took the paint. pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) -> Result { + apply_paint_opacity(s, p, Some(paint), None, fill) +} + +/// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or +/// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points' +/// own opacity for a fill, nothing on a target without that item. The opacity alone changes neither +/// the defaults for new art nor the remembered colors. An opacity that would go only to type +/// characters, to an object selected in a symbol instance, or to no target at all is an error. +fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity: Option, fill: bool) -> Result { let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; let focus = switch_or(p, "focus", true, cmd)?; - let span = spans_targets(p, &paint).map_err(|e| bad(cmd, e))?; + let span = match &paint { + Some(paint) => spans_targets(p, paint).map_err(|e| bad(cmd, e))?, + None => false, + }; // Characters selected with the Type tool take the paint, not the whole type object (#1063). if p.get("ids").is_none() && p.get("item").is_none() && let Some((id, a, b)) = super::textedit::editing_range(s)? && a != b { + let (Some(paint), None) = (paint, opacity) else { return Err(characters_have_no_opacity(cmd)) }; // After Select All in threaded text, every frame's text takes it. let story = super::textedit::editing_story(s); let ranges: Vec<(NodeId, usize, usize)> = @@ -520,6 +597,9 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) // An object of a dynamic symbol instance's art selected with Direct Selection: that object's // fill or stroke changes for this instance only (solid, none, gradient or pattern). if let Some((id, path)) = selected_part_target(s, p, cmd)? { + let Some(paint) = paint.filter(|_| opacity.is_none()) else { + return Err(bad(cmd, "an object selected in a symbol instance has no fill or stroke opacity of its own")); + }; super::brushsym::edit_part(s, id, &path, if fill { "Fill Color" } else { "Stroke Color" }, |o| { if fill { o.fill = Some(paint.clone()); @@ -538,23 +618,124 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) let item = item_target(s, p, cmd)?.of_kind(s, fill); let selected = item.targets(s, p)?; let ids = super::graph::paint_targets(&s.doc()?.doc, &selected); - let paint = if span { placed_across(&s.doc()?.doc, &ids, paint, p, fill) } else { paint }; + // An opacity has nothing to go to without targets; with a paint, the defaults then stay too. + if opacity.is_some() && ids.is_empty() { + return Err(bad(cmd, "select objects or give ids")); + } + let paint = match paint { + Some(paint) if span => Some(placed_across(&s.doc()?.doc, &ids, paint, p, fill)), + paint => paint, + }; // The gradient mesh points picked with the Mesh tool or Direct Selection: a solid fill - // recolours just those points of their meshes. - let mesh_points = if fill && matches!(paint, Paint::Solid { .. }) { picked_mesh_points(s, &ids) } else { vec![] }; + // recolours just those points of their meshes, and a fill opacity fades just them. + let mesh_points = if fill && matches!(paint, Some(Paint::Solid { .. }) | None) { picked_mesh_points(s, &ids) } else { vec![] }; // Without `item`, unless the Appearance panel's active fill item takes the paint. - let colorized = if fill && p.get("item").is_none() && item == ItemTarget::Top { - colorized_images(&s.doc()?.doc, &ids, &paint).map_err(|e| bad(cmd, e))? - } else { - vec![] + let colorized = match &paint { + Some(paint) if fill && p.get("item").is_none() && item == ItemTarget::Top => { + colorized_images(&s.doc()?.doc, &ids, paint).map_err(|e| bad(cmd, e))? + } + _ => vec![], + }; + let label = match paint { + None => "Opacity", + Some(_) if fill => "Fill Color", + Some(_) => "Stroke Color", }; - let label = if fill { "Fill Color" } else { "Stroke Color" }; // Each object whose appearance took the paint, with the row it went to, for the paint a graph stores for its series // (a series mark is a path, so it always has a row here). let written = std::cell::RefCell::new(Vec::new()); // The type objects whose characters took the paint (no row targeted): only those change what a graph's labels keep // for their characters; a row edit is kept with the label's rows. let characters = std::cell::RefCell::new(Vec::new()); + // Whether a target took the opacity, and whether one would have given it to its characters. + let (took_opacity, characters_skipped) = (std::cell::Cell::new(false), std::cell::Cell::new(false)); + let paint_one = |n: &mut Node, index: Option, paint: &Paint| -> Result<()> { + if index.is_none() && matches!(n.kind, NodeKind::Text(_)) { + characters.borrow_mut().push(n.id); + } + if index.is_none() && colorized.contains(&n.id) { + n.extras_mut().colorize = paint.color().map(|_| Box::new(paint.clone())); + return Ok(()); + } + if index.is_none() + && let Paint::Solid { color, .. } = paint + && let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id) + && let NodeKind::Mesh(m) = &mut n.kind + { + for i in points { + if let Some(q) = m.points.get_mut(*i) { + q.color = *color; + } + } + return Ok(()); + } + if index.is_none() + && let NodeKind::Text(t) = &mut n.kind + { + let (xf, lb) = (t.xf, t.local_bounds()); + for r in &mut t.runs { + if !fill && !paint.is_none() { + run_stroke_weight(&mut r.style); + } + let (cur, b) = run_paint_mut(r, !fill, lb); + *cur = place_run_paint(paint, p, xf, b); + } + return Ok(()); + } + // A missing top fill or stroke is created first: a new stroke's weight sizes the box its + // gradient fits. + if n.appearance.paint_at(index, fill).is_none() { + n.appearance.set_paint_at(index, fill, Paint::None); + } + if !fill { + restore_unpainted_stroke(&mut n.appearance, index, paint); + } + let new_paint = keep_pattern_xf(paint, p, n.appearance.paint_at(index, fill)); + let placed = place_paint(&new_paint, p, item_paint_bounds(n, index, fill)); + n.appearance.set_paint_at(index, fill, placed); + if !fill + && paint.is_none() + && let Some(stroke) = n.appearance.stroke_at_mut(index) + { + // A stroke without paint has no weight; painting it again restores the 1 pt default. + stroke.width = 0.0; + } + if !fill { + super::object::snap_if_aligned(n); + } + let at = match index { + Some(_) => n.appearance.item_of_kind(index, fill), + None => n.appearance.items.iter().rposition(|it| it.is_fill() == fill), + }; + written.borrow_mut().extend(at.map(|at| (n.id, at))); + Ok(()) + }; + // The opacity goes to what the paint went to: the picked mesh points, else the fill or stroke + // item. Characters, and targets without that item, are left as they are. + let opacity_one = |n: &mut Node, index: Option, o: f32| { + if index.is_none() && matches!(n.kind, NodeKind::Text(_)) { + characters_skipped.set(true); + return; + } + if index.is_none() + && let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id) + && let NodeKind::Mesh(m) = &mut n.kind + { + for i in points { + if let Some(q) = m.points.get_mut(*i) { + q.opacity = o; + took_opacity.set(true); + } + } + return; + } + let item = + if fill { n.appearance.fill_at_mut(index).map(|f| &mut f.opacity) } else { n.appearance.stroke_at_mut(index).map(|s| &mut s.opacity) }; + if let Some(item) = item { + *item = o; + took_opacity.set(true); + } + }; edit_items_then( s, &ids, @@ -563,87 +744,47 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) label, fill, |n, index| { - if index.is_none() && matches!(n.kind, NodeKind::Text(_)) { - characters.borrow_mut().push(n.id); + if let Some(paint) = &paint { + paint_one(n, index, paint)?; } - if index.is_none() && colorized.contains(&n.id) { - n.extras_mut().colorize = paint.color().map(|_| Box::new(paint.clone())); - return Ok(()); + if let Some(o) = opacity { + opacity_one(n, index, o); } - if index.is_none() - && let Paint::Solid { color, .. } = &paint - && let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id) - && let NodeKind::Mesh(m) = &mut n.kind - { - for i in points { - if let Some(q) = m.points.get_mut(*i) { - q.color = *color; - } - } - return Ok(()); - } - if index.is_none() - && let NodeKind::Text(t) = &mut n.kind - { - let (xf, lb) = (t.xf, t.local_bounds()); - for r in &mut t.runs { - if !fill && !paint.is_none() { - run_stroke_weight(&mut r.style); - } - let (cur, b) = run_paint_mut(r, !fill, lb); - *cur = place_run_paint(&paint, p, xf, b); - } - return Ok(()); - } - // A missing top fill or stroke is created first: a new stroke's weight sizes the box its - // gradient fits. - if n.appearance.paint_at(index, fill).is_none() { - n.appearance.set_paint_at(index, fill, Paint::None); - } - if !fill { - restore_unpainted_stroke(&mut n.appearance, index, &paint); - } - let new_paint = keep_pattern_xf(&paint, p, n.appearance.paint_at(index, fill)); - let placed = place_paint(&new_paint, p, item_paint_bounds(n, index, fill)); - n.appearance.set_paint_at(index, fill, placed); - if !fill - && paint.is_none() - && let Some(stroke) = n.appearance.stroke_at_mut(index) - { - // A stroke without paint has no weight; painting it again restores the 1 pt default. - stroke.width = 0.0; - } - if !fill { - super::object::snap_if_aligned(n); - } - let at = match index { - Some(_) => n.appearance.item_of_kind(index, fill), - None => n.appearance.items.iter().rposition(|it| it.is_fill() == fill), - }; - written.borrow_mut().extend(at.map(|at| (n.id, at))); Ok(()) }, |before, d, changed| { + // An opacity that no target took is an error, which also takes back the paint given with it. + if opacity.is_some() && !took_opacity.get() { + if characters_skipped.get() { + return Err(characters_have_no_opacity(cmd)); + } + return Err(bad(cmd, "no target has that fill or stroke to take the opacity")); + } + // A graph keeps the opacity of a series mark's topmost visible fill and stroke for the whole series. + let kept = opacity.is_some() && super::appearance::capture_series_changes(before, d, changed); + let Some(paint) = &paint else { return Ok(kept) }; let series = super::appearance::capture_series_paint_writes(before, d, changed, &written.borrow()); let labels = super::graph::capture_label_styles(d, &characters.borrow(), &|st| { if fill { - st.fill = unplaced(&paint); + st.fill = unplaced(paint); } else { if !paint.is_none() { run_stroke_weight(st); } - st.stroke = unplaced(&paint); + st.stroke = unplaced(paint); } }); - Ok(series || labels) + Ok(series || labels || kept) }, )?; - // Rejected edits leave the next shape's appearance and active proxy untouched. - paint_new_art(s, &paint, fill); if focus { s.fill_active = fill; } - s.remember_paint(&paint); + // Rejected edits leave the next shape's appearance and active proxy untouched. + if let Some(paint) = &paint { + paint_new_art(s, paint, fill); + s.remember_paint(paint); + } Ok(json!({"objects": ids.iter().collect::>().len()})) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2f849901a4..ed7bfc6dd6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -116,6 +116,7 @@ mod outlineobject; pub(super) mod outlinestroke; mod overprint; mod package; +mod paintopacity; mod paintproxy; mod panelcmds; mod paragraphs; diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs new file mode 100644 index 0000000000..3c3fa12bbe --- /dev/null +++ b/crates/engine/src/tests/paintopacity.rs @@ -0,0 +1,293 @@ +//! `opacity` on `paint.setFill` and `paint.setStroke`: the opacity of the fill or stroke item the +//! paint goes to, and `fillOpacity` and `strokeOpacity` on `paint.proxies`. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use crate::tooling::ViewInfo; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + let r = s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 100, "height": 50})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn text(s: &mut Session) -> NodeId { + let r = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "Hi"})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn fill_opacity(s: &Session, id: NodeId) -> f32 { + node(s, id).appearance.fill().unwrap().opacity +} + +fn undo_labels(s: &Session) -> Vec { + s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect() +} + +fn proxies(s: &mut Session) -> Value { + s.execute("paint.proxies", &json!({})).unwrap() +} + +/// `paint.setFill {opacity}` alone sets the opacity of the selected object's top fill item, as one +/// undo step named Opacity, and leaves its paint, its stroke and the object's own opacity as they +/// were; `paint.setStroke {opacity}` does the same for the top stroke, and `paint.proxies` answers +/// both. +#[test] +fn opacity_alone_sets_the_fill_or_stroke_item() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let before = node(&s, id); + let undo = undo_labels(&s).len(); + s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + let n = node(&s, id); + assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6); + assert_eq!(n.appearance.fill_paint(), before.appearance.fill_paint()); + assert_eq!(n.appearance.stroke().unwrap().opacity, 1.0); + assert_eq!(n.opacity, 1.0); + let labels = undo_labels(&s); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity"))); + assert_eq!(proxies(&mut s)["fillOpacity"], 40.0); + assert_eq!(proxies(&mut s)["strokeOpacity"], 100.0); + // The defaults for new art keep their paint. + assert_eq!(s.paint.fill, Paint::solid(Color::WHITE)); + + s.execute("paint.setStroke", &json!({"opacity": 25})).unwrap(); + assert!((node(&s, id).appearance.stroke().unwrap().opacity - 0.25).abs() < 1e-6); + assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6); + assert_eq!(proxies(&mut s)["strokeOpacity"], 25.0); +} + +/// A selected group stands for its contents: every member's fill takes the opacity, as one undo step. +#[test] +fn a_group_sets_every_member_in_one_step() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a, b]); + s.execute("object.group", &json!({})).unwrap(); + let undo = undo_labels(&s).len(); + s.execute("paint.setFill", &json!({"opacity": 60})).unwrap(); + assert!((fill_opacity(&s, a) - 0.6).abs() < 1e-6 && (fill_opacity(&s, b) - 0.6).abs() < 1e-6); + assert_eq!(undo_labels(&s).len(), undo + 1); +} + +/// A group with a fill of its own: without an active Appearance row, `paint.proxies` answers the +/// opacity of the contents' fills, which `paint.setFill {opacity}` sets, not the group's own fill. +#[test] +fn a_group_with_its_own_fill_answers_for_its_contents() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a, b]); + s.execute("object.group", &json!({})).unwrap(); + let g = s.doc().unwrap().selection.subjects()[0]; + select(&mut s, &[g]); + s.execute("appearance.addFill", &json!({})).unwrap(); + let own = node(&s, g).appearance.items.iter().position(|it| it.is_fill()).unwrap(); + s.execute("paint.setFill", &json!({"item": own, "opacity": 30})).unwrap(); + select(&mut s, &[g]); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0); + s.execute("paint.setFill", &json!({"opacity": 60})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 60.0); + assert!((node(&s, g).appearance.items[own].opacity() - 0.3).abs() < 1e-6, "the group's own fill keeps its opacity"); +} + +/// With the Appearance panel's lower fill row active, that row takes the opacity and the top fill +/// keeps its own. +#[test] +fn the_active_appearance_row_takes_the_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + s.execute("appearance.addFill", &json!({})).unwrap(); // [Fill, Stroke, Fill] + s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap(); + s.execute("paint.setFill", &json!({"opacity": 30})).unwrap(); + let ap = node(&s, id).appearance; + assert!((ap.items[0].opacity() - 0.3).abs() < 1e-6); + assert_eq!(ap.items[2].opacity(), 1.0); + assert_eq!(proxies(&mut s)["fillOpacity"], 30.0); +} + +/// A color and an opacity change together in one undo step, and the same call again records no +/// step. +#[test] +fn color_and_opacity_are_one_step_and_a_repeat_records_none() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let undo = undo_labels(&s).len(); + let p = json!({"color": "#ff0000", "opacity": 50}); + s.execute("paint.setFill", &p).unwrap(); + assert_eq!(node(&s, id).appearance.fill_paint(), Paint::solid(Color::rgb8(255, 0, 0))); + assert!((fill_opacity(&s, id) - 0.5).abs() < 1e-6); + assert_eq!(undo_labels(&s).len(), undo + 1); + assert_eq!(undo_labels(&s).last().map(String::as_str), Some("Fill Color")); + s.execute("paint.setFill", &p).unwrap(); + s.execute("paint.setFill", &json!({"opacity": 50})).unwrap(); + assert_eq!(undo_labels(&s).len(), undo + 1); +} + +/// Bad values, nothing selected, and characters selected with the Type tool answer errors and leave +/// the document and the defaults for new art as they were. +#[test] +fn errors_leave_the_document_and_defaults_alone() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + for bad in [json!(101), json!(-1), json!("50"), json!(true)] { + let e = s.execute("paint.setFill", &json!({"opacity": bad})).unwrap_err(); + assert!(e.to_string().contains("`opacity` must be a number from 0 to 100"), "{bad}: {e}"); + } + let e = s.execute("paint.setFill", &json!({})).unwrap_err(); + assert!(e.to_string().contains("give color, none, swatch, gradient or opacity"), "{e}"); + s.execute("select.none", &json!({})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] { + let e = s.execute("paint.setFill", &p).unwrap_err(); + assert!(e.to_string().contains("select objects or give ids"), "{p}: {e}"); + } + assert_eq!(s.paint.fill, Paint::solid(Color::WHITE)); + assert_eq!(*s.doc().unwrap().doc, *doc); + + // Characters selected with the Type tool. + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 50.0, 250.0), v).unwrap(); + } + s.tool_text("Sample", v).unwrap(); + s.set_tool_option("select", &json!({"start": 0, "end": 3})); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] { + let e = s.execute("paint.setFill", &p).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{p}: {e}"); + } + assert_eq!(*s.doc().unwrap().doc, *doc); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); +} + +/// A type object whose characters take the paint is left alone beside a rectangle that takes the +/// opacity, with no error; alone, it answers the characters error. +#[test] +fn type_beside_other_art_is_left_alone() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let t = text(&mut s); + let runs = |s: &Session| match &node(s, t).kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("not type"), + }; + let before = (node(&s, t), runs(&s)); + select(&mut s, &[r, t]); + s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + assert!((fill_opacity(&s, r) - 0.4).abs() < 1e-6); + assert_eq!((node(&s, t), runs(&s)), before); + select(&mut s, &[t]); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}"); + assert_eq!((node(&s, t), runs(&s)), before); +} + +/// A color with an opacity on type alone answers the characters error and takes the color back too. +#[test] +fn type_alone_takes_back_the_paint_given_with_an_opacity() { + let mut s = session(); + let t = text(&mut s); + select(&mut s, &[t]); + let doc = s.doc().unwrap().doc.clone(); + let undo = undo_labels(&s).len(); + let e = s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}"); + assert_eq!(*s.doc().unwrap().doc, *doc); + assert_eq!(undo_labels(&s).len(), undo); + assert_eq!(s.paint.fill, Paint::solid(Color::WHITE), "the defaults keep their paint"); +} + +/// An opacity that no target takes (the only selected object has no fill item) is an error, with or +/// without a paint, and leaves the document as it was; `paint.proxies` answers null for it, and +/// beside an object with a fill item it answers that object's opacity. +#[test] +fn an_opacity_no_target_takes_is_an_error() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a]); + s.execute("appearance.removeItem", &json!({"index": 0})).unwrap(); + assert!(node(&s, a).appearance.fill().is_none()); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + let doc = s.doc().unwrap().doc.clone(); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("no target has that fill or stroke to take the opacity"), "{e}"); + assert_eq!(*s.doc().unwrap().doc, *doc); + // A paint given with the opacity creates the fill, which takes the opacity. + s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap(); + assert!((fill_opacity(&s, a) - 0.4).abs() < 1e-6); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *doc); + + select(&mut s, &[b]); + s.execute("paint.setFill", &json!({"opacity": 70})).unwrap(); + select(&mut s, &[a, b]); + assert_eq!(proxies(&mut s)["fillOpacity"], 70.0, "the first selected object with a fill item answers"); + s.execute("paint.setFill", &json!({"opacity": 20})).unwrap(); + assert!((fill_opacity(&s, b) - 0.2).abs() < 1e-6); + assert!(node(&s, a).appearance.fill().is_none()); +} + +/// An object selected in a dynamic symbol instance has no opacity of its own: `opacity` is an error +/// that leaves the document alone, and `paint.proxies` answers null. +#[test] +fn an_object_in_a_symbol_instance_refuses_an_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let inst = s.execute("symbol.new", &json!({"name": "One", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].clone(); + s.execute("symbol.instance.selectPart", &json!({"id": inst, "path": []})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] { + let e = s.execute("paint.setFill", &p).unwrap_err(); + assert!(e.to_string().contains("an object selected in a symbol instance has no fill or stroke opacity of its own"), "{p}: {e}"); + } + assert_eq!(*s.doc().unwrap().doc, *doc); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); +} + +/// A gradient mesh point picked with the Mesh tool takes a fill opacity itself, and the proxy shows +/// it; the object's fill item and the other points stay as they were. +#[test] +fn a_picked_mesh_point_takes_the_fill_opacity() { + let mut s = session(); + let m = rect(&mut s, 10.0); + select(&mut s, &[m]); + s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap(); + select(&mut s, &[m]); + let v = ViewInfo::default(); + let NodeKind::Mesh(g) = &node(&s, m).kind else { panic!("not a mesh") }; + let q = g.points[4].p; + s.select_tool("mesh", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, q.x, q.y), v).unwrap(); + } + s.execute("paint.setFill", &json!({"opacity": 30})).unwrap(); + let NodeKind::Mesh(g) = &node(&s, m).kind else { panic!("not a mesh") }; + let o: Vec = g.points.iter().map(|p| p.opacity).collect(); + assert!((o[4] - 0.3).abs() < 1e-6, "{o:?}"); + assert!(o.iter().enumerate().all(|(i, a)| i == 4 || *a == 1.0), "{o:?}"); + assert_eq!(proxies(&mut s)["fillOpacity"], 30.0); +} diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 943faa4782..d2a6f85f54 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1324,7 +1324,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); keys left out keep their values, params that are not an object, another key or a value off the list (opacity: not true or false) are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 348ac7b881..86050b1c37 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2287,6 +2287,7 @@ font-technology Variable Променливи One Point Perspective Preset 5 Предварителна настройка 5 за едноточкова перспектива Only Web Colors Само уеб цветове Opacity Непрозрачност + Show Opacity Показване на непрозрачността Opacity & Mask Define Knockout Shape Непрозрачността и маската определят формата на изрязване Opacity Mask Маска за непрозрачност Opacity Mask Info Информация за маската за непрозрачност diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 3b1a9e001c..f84c51db58 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -450,6 +450,7 @@ Fill & Stroke Ispuna i potez Fill Color Boja ispune Opacity Neprozirnost + Show Opacity Prikaži neprozirnost Stroke Color Boja poteza Fill Gradient Gradijent ispune Stroke Gradient Gradijent poteza diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 488b46c4f5..defcfbc432 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2911,6 +2911,7 @@ digits Malayalam Malaiàlam One Point Perspective Preset 5 Preajust 5 de perspectiva d’un punt Only Web Colors Només colors web Opacity Opacitat + Show Opacity Mostra l’opacitat Opacity & Mask Define Knockout Shape L’opacitat i la màscara defineixen la forma d’exclusió Opacity Mask Màscara d’opacitat Opacity Mask Info Informació de la màscara d’opacitat @@ -6550,6 +6551,11 @@ digits Malayalam Malaiàlam @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` i `maxItems` han de ser 0-{MAX_LIST}, `maxItems` com a mínim 1, i el valor predeterminat ha de tenir aquesta quantitat @msg `name` must be a string `name` ha de ser una cadena @msg `opacity` must be a number `opacity` ha de ser un nombre +@msg `opacity` must be a number from 0 to 100 `opacity` ha de ser un nombre del 0 al 100 +@msg `opacity` must be true or false `opacity` ha de ser true o false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke els caràcters de text no tenen opacitat pròpia: afegiu un farciment o un traç amb Afegeix un farciment nou o Afegeix un traç nou del tauler Aparença +@msg an object selected in a symbol instance has no fill or stroke opacity of its own un objecte seleccionat en una instància de símbol no té opacitat pròpia de farciment ni de traç +@msg no target has that fill or stroke to take the opacity cap objectiu no té aquest farciment o traç per rebre l'opacitat @msg `type` must be "path" or "compound" `type` ha de ser "path" o "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` ha de tenir 1-{MAX_UNIT} caràcters imprimibles @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` ha d’indicar d’1 a {MAX_CONDITION_VALUES} valors per a `{other}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6a57e90e37..6d482e73a1 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -463,6 +463,7 @@ Fill & Stroke Výplň a tah Fill Color Barva výplně Opacity Krytí + Show Opacity Zobrazit krytí Stroke Color Barva tahu Fill Gradient Přechod výplně Stroke Gradient Přechod tahu @@ -6445,6 +6446,11 @@ axis Y Axis osa Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` a `maxItems` musí být 0-{MAX_LIST}, `maxItems` alespoň 1 a výchozí hodnota musí mít tolik položek @msg `name` must be a string `name` musí být řetězec @msg `opacity` must be a number `opacity` musí být číslo +@msg `opacity` must be a number from 0 to 100 `opacity` musí být číslo od 0 do 100 +@msg `opacity` must be true or false `opacity` musí být true nebo false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke znaky textu nemají vlastní krytí: přidejte výplň nebo tah příkazem Přidat novou výplň nebo Přidat nový tah v panelu Vzhled +@msg an object selected in a symbol instance has no fill or stroke opacity of its own objekt vybraný v instanci symbolu nemá vlastní krytí výplně ani tahu +@msg no target has that fill or stroke to take the opacity žádný cíl nemá tuto výplň nebo tah, který by převzal krytí @msg `type` must be "path" or "compound" `type` musí být "path" nebo "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` musí mít 1-{MAX_UNIT} tisknutelných znaků @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` musí uvádět 1 až {MAX_CONDITION_VALUES} hodnot pro `{other}` @@ -8252,6 +8258,7 @@ breakText Glyphs Glyfy @msg give a pattern name or select an object painted with a pattern zadejte název vzorku nebo vyberte objekt vybarvený vzorkem @msg give at least one of clip, invert, disabled, linked zadejte alespoň jedno z clip, invert, disabled, linked @msg give color, none, swatch or gradient zadejte color, none, swatch nebo gradient +@msg give color, none, swatch, gradient or opacity zadejte color, none, swatch, gradient nebo opacity @msg give dataBase64 zadejte dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) zadejte buď at (kliknutí), nebo area (cestu nakreslenou kolem překryvů) @msg give exactly one of `at`, `rect` and `points` zadejte právě jedno z `at`, `rect` a `points` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 54a79e38e5..e2595a720b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -418,6 +418,7 @@ Fill & Stroke Fyld og streg Fill Color Fyldfarve Opacity Opacitet + Show Opacity Vis opacitet Stroke Color Stregfarve Fill Gradient Fyldgradient Stroke Gradient Streggradient diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index ab77cb0dd7..33988acfd7 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2321,6 +2321,7 @@ file-filter Templates Vorlagen One Point Perspective Preset 5 Einpunktperspektive – Vorgabe 5 Only Web Colors Nur Webfarben Opacity Deckkraft + Show Opacity Deckkraft einblenden Opacity & Mask Define Knockout Shape Deckkraft und Maske definieren Aussparungsform Opacity Mask Deckkraftmaske Opacity Mask Info Informationen zur Deckkraftmaske @@ -6037,6 +6038,11 @@ axis Y Axis Y-Achse @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` und `maxItems` müssen 0-{MAX_LIST} sein, `maxItems` mindestens 1, und der Standardwert muss so viele Einträge haben @msg `name` must be a string `name` muss eine Zeichenkette sein @msg `opacity` must be a number `opacity` muss eine Zahl sein +@msg `opacity` must be a number from 0 to 100 `opacity` muss eine Zahl von 0 bis 100 sein +@msg `opacity` must be true or false `opacity` muss true oder false sein +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke Textzeichen haben keine eigene Deckkraft: Fügen Sie mit „Neue Fläche hinzufügen“ oder „Neue Kontur hinzufügen“ im Bedienfeld „Aussehen“ eine Fläche oder Kontur hinzu +@msg an object selected in a symbol instance has no fill or stroke opacity of its own ein in einer Symbolinstanz ausgewähltes Objekt hat keine eigene Flächen- oder Konturdeckkraft +@msg no target has that fill or stroke to take the opacity kein Ziel hat diese Fläche oder Kontur, die die Deckkraft übernehmen könnte @msg `type` must be "path" or "compound" `type` muss "path" oder "compound" sein @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` muss 1-{MAX_UNIT} druckbare Zeichen haben @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` muss 1 bis {MAX_CONDITION_VALUES} Werte für `{other}` nennen @@ -8044,6 +8050,7 @@ breakText Glyphs Glyphen @msg give a pattern name or select an object painted with a pattern geben Sie einen Musternamen an, oder wählen Sie ein mit einem Muster gefärbtes Objekt aus @msg give at least one of clip, invert, disabled, linked geben Sie mindestens eines von clip, invert, disabled, linked an @msg give color, none, swatch or gradient geben Sie color, none, swatch oder gradient an +@msg give color, none, swatch, gradient or opacity geben Sie color, none, swatch, gradient oder opacity an @msg give dataBase64 geben Sie dataBase64 an @msg give either at (a click) or area (a path drawn around the overlaps) geben Sie entweder at (einen Klick) oder area (einen um die Überlappungen gezeichneten Pfad) an @msg give formats or a preset, not both geben Sie formats oder eine Vorgabe an, nicht beides diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a1a203a257..9dcd84a2d4 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1899,6 +1899,7 @@ font-technology Variable Μεταβλητές On Ενεργό Only Web Colors Μόνο χρώματα ιστού Opacity Αδιαφάνεια + Show Opacity Εμφάνιση αδιαφάνειας Opacity Mask Μάσκα αδιαφάνειας Opacity: Αδιαφάνεια: Open Άνοιγμα @@ -6397,6 +6398,11 @@ axis Y Axis Άξονας Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many τα `minItems` και `maxItems` πρέπει να είναι 0-{MAX_LIST}, το `maxItems` τουλάχιστον 1 και η προεπιλογή να έχει τόσα στοιχεία @msg `name` must be a string το `name` πρέπει να είναι συμβολοσειρά @msg `opacity` must be a number το `opacity` πρέπει να είναι αριθμός +@msg `opacity` must be a number from 0 to 100 το `opacity` πρέπει να είναι αριθμός από 0 έως 100 +@msg `opacity` must be true or false το `opacity` πρέπει να είναι true ή false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke οι χαρακτήρες κειμένου δεν έχουν δική τους αδιαφάνεια: προσθέστε γέμισμα ή περίγραμμα με την Προσθήκη νέου γεμίσματος ή την Προσθήκη νέου περιγράμματος του πίνακα Εμφάνιση +@msg an object selected in a symbol instance has no fill or stroke opacity of its own ένα αντικείμενο επιλεγμένο σε στιγμιότυπο συμβόλου δεν έχει δική του αδιαφάνεια γεμίσματος ή περιγράμματος +@msg no target has that fill or stroke to take the opacity κανένας στόχος δεν έχει αυτό το γέμισμα ή περίγραμμα για να λάβει την αδιαφάνεια @msg `type` must be "path" or "compound" το `type` πρέπει να είναι "path" ή "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters το `unit` πρέπει να έχει 1-{MAX_UNIT} εκτυπώσιμους χαρακτήρες @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` το `visibleWhen` πρέπει να αναφέρει 1 έως {MAX_CONDITION_VALUES} τιμές για το `{other}` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 45fd0d8235..f83c8b8e41 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2359,6 +2359,7 @@ font-technology Variable Variables One Point Perspective Preset 5 Preajuste de perspectiva de un punto 5 Only Web Colors Solo colores web Opacity Opacidad + Show Opacity Mostrar opacidad Opacity & Mask Define Knockout Shape La opacidad y la máscara definen la forma de exclusión Opacity Mask Máscara de opacidad Opacity Mask Info Información de máscara de opacidad @@ -6388,6 +6389,11 @@ axis Y Axis Eje Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` y `maxItems` deben ser 0-{MAX_LIST}, `maxItems` al menos 1, y el valor predeterminado debe tener esa cantidad @msg `name` must be a string `name` debe ser una cadena @msg `opacity` must be a number `opacity` debe ser un número +@msg `opacity` must be a number from 0 to 100 `opacity` debe ser un número de 0 a 100 +@msg `opacity` must be true or false `opacity` debe ser true o false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke los caracteres de texto no tienen opacidad propia: agregue un relleno o un trazo con Agregar nuevo relleno o Agregar nuevo trazo del panel Apariencia +@msg an object selected in a symbol instance has no fill or stroke opacity of its own un objeto seleccionado en una instancia de símbolo no tiene opacidad propia de relleno ni de trazo +@msg no target has that fill or stroke to take the opacity ningún destino tiene ese relleno o trazo para recibir la opacidad @msg `type` must be "path" or "compound" `type` debe ser "path" o "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` debe tener 1-{MAX_UNIT} caracteres imprimibles @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` debe indicar de 1 a {MAX_CONDITION_VALUES} valores para `{other}` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index f6db5b8ee1..aa3769a95a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -460,6 +460,7 @@ Fill & Stroke Täyttö ja viiva Fill Color Täyttöväri Opacity Peittävyys + Show Opacity Näytä peittävyys Stroke Color Viivan väri Fill Gradient Täytön liukuväri Stroke Gradient Viivan liukuväri @@ -6475,6 +6476,11 @@ axis Y Axis Y-akseli @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` ja `maxItems` on oltava 0-{MAX_LIST}, `maxItems` vähintään 1, ja oletusarvossa on oltava niin monta kohdetta @msg `name` must be a string `name` on oltava merkkijono @msg `opacity` must be a number `opacity` on oltava luku +@msg `opacity` must be a number from 0 to 100 `opacity` on oltava luku 0:sta 100:aan +@msg `opacity` must be true or false `opacity` on oltava true tai false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke tekstin merkeillä ei ole omaa peittävyyttä: lisää täyttö tai viiva Ulkoasu-paneelin komennolla Lisää uusi täyttö tai Lisää uusi viiva +@msg an object selected in a symbol instance has no fill or stroke opacity of its own symbolin ilmentymästä valitulla objektilla ei ole omaa täytön tai viivan peittävyyttä +@msg no target has that fill or stroke to take the opacity millään kohteella ei ole tätä täyttöä tai viivaa, joka ottaisi peittävyyden @msg `type` must be "path" or "compound" `type` on oltava "path" tai "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit`-kentässä on oltava 1-{MAX_UNIT} tulostettavaa merkkiä @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen`-kentässä on lueteltava 1-{MAX_CONDITION_VALUES} arvoa parametrille `{other}` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ae0bf3b436..623350954b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2351,6 +2351,7 @@ font-technology Variable Variables One Point Perspective Preset 5 Paramètre prédéfini de perspective à un point 5 Only Web Colors Couleurs Web uniquement Opacity Opacité + Show Opacity Afficher l’opacité Opacity & Mask Define Knockout Shape L’opacité et le masque définissent la forme de masquage Opacity Mask Masque d’opacité Opacity Mask Info Infos sur le masque d’opacité @@ -6440,6 +6441,11 @@ axis Y Axis Axe Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` et `maxItems` doivent valoir 0-{MAX_LIST}, `maxItems` au moins 1, et la valeur par défaut doit en compter autant @msg `name` must be a string `name` doit être une chaîne @msg `opacity` must be a number `opacity` doit être un nombre +@msg `opacity` must be a number from 0 to 100 `opacity` doit être un nombre compris entre 0 et 100 +@msg `opacity` must be true or false `opacity` doit valoir true ou false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke les caractères du texte n’ont pas d’opacité propre : ajoutez un fond ou un contour avec Ajouter un nouveau fond ou Ajouter un nouveau contour dans le panneau Aspect +@msg an object selected in a symbol instance has no fill or stroke opacity of its own un objet sélectionné dans une occurrence de symbole n’a pas d’opacité de fond ou de contour propre +@msg no target has that fill or stroke to take the opacity aucune cible n’a ce fond ou ce contour pour recevoir l’opacité @msg `type` must be "path" or "compound" `type` doit valoir "path" ou "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` doit compter 1-{MAX_UNIT} caractères imprimables @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` doit indiquer 1 à {MAX_CONDITION_VALUES} valeurs pour `{other}` @@ -8233,6 +8239,7 @@ breakText Glyphs Glyphes @msg give a pattern name or select an object painted with a pattern indiquez un nom de motif ou sélectionnez un objet peint avec un motif @msg give at least one of clip, invert, disabled, linked indiquez au moins l’un des paramètres clip, invert, disabled, linked @msg give color, none, swatch or gradient indiquez color, none, swatch ou gradient +@msg give color, none, swatch, gradient or opacity indiquez color, none, swatch, gradient ou opacity @msg give dataBase64 indiquez dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) indiquez soit at (un clic), soit area (un tracé dessiné autour des chevauchements) @msg give exactly one of `path`, `data` and `dataBase64` indiquez exactement un paramètre parmi `path`, `data` et `dataBase64` diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index f38612601c..cc24288383 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2391,6 +2391,7 @@ One page per artboard. દરેક આર્ટબોર્ડ માટે એક પેજ. Only Web Colors માત્ર વેબ રંગો Opacity અપારદર્શકતા + Show Opacity અપારદર્શકતા બતાવો Opacity & Mask Define Knockout Shape અપારદર્શકતા અને માસ્ક નૉકઆઉટ આકાર વ્યાખ્યાયિત કરે છે Opacity Mask Info અપારદર્શકતા માસ્ક માહિતી Opacity Mask Options અપારદર્શકતા માસ્ક વિકલ્પો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 624671acca..45bf8669ac 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3183,6 +3183,7 @@ antiAlias Sharp शार्प One Point Perspective Preset 5 एक बिंदु पर्सपेक्टिव पूर्व निर्धारित 5 Only Web Colors केवल वेब रंग Opacity ओपेसिटी + Show Opacity ओपेसिटी दिखाएँ Opacity & Mask Define Knockout Shape ओपेसिटी एंड मास्क डिफ़ाइन नॉकआउट शेप Opacity Mask ओपेसिटी मास्क Opacity Mask Info ओपेसिटी मास्क की जानकारी @@ -5601,6 +5602,11 @@ antiAlias Sharp शार्प @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` और `maxItems` 0-{MAX_LIST} होने चाहिए, `maxItems` कम से कम 1, और डिफ़ॉल्ट में उतने ही आइटम होने चाहिए @msg `name` must be a string `name` एक स्ट्रिंग होना चाहिए @msg `opacity` must be a number `opacity` एक संख्या होना चाहिए +@msg `opacity` must be a number from 0 to 100 `opacity` 0 से 100 तक की संख्या होना चाहिए +@msg `opacity` must be true or false `opacity` true या false होना चाहिए +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke टेक्स्ट के कैरेक्टर्स की अपनी ओपेसिटी नहीं होती: अपीयरेंस पैनल के नया फ़िल जोड़ें या नया स्ट्रोक जोड़ें से फ़िल या स्ट्रोक जोड़ें +@msg an object selected in a symbol instance has no fill or stroke opacity of its own सिंबल इंस्टेंस में सिलेक्ट किए गए ऑब्जेक्ट की अपनी फ़िल या स्ट्रोक ओपेसिटी नहीं होती +@msg no target has that fill or stroke to take the opacity किसी भी टारगेट में वह फ़िल या स्ट्रोक नहीं है जो ओपेसिटी ले सके @msg `type` must be "path" or "compound" `type` "path" या "compound" होना चाहिए @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` में 1-{MAX_UNIT} प्रिंट करने योग्य वर्ण होने चाहिए @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` में `{other}` के लिए 1 से {MAX_CONDITION_VALUES} मान होने चाहिए @@ -6908,6 +6914,7 @@ antiAlias Sharp शार्प @msg give at least one of clip, invert, disabled, linked कम से कम एक क्लिप, उलटा, विकलांग, लिंक्ड देना @msg give both `start` and `end` [x, y] (or neither) `start` और `end` दोनों [x, y] दें (या दोनों न दें) @msg give color, none, swatch or gradient color, none, swatch या gradient दें +@msg give color, none, swatch, gradient or opacity color, none, swatch, gradient या opacity दें @msg give corners of the path: anchors between two straight sides पाथ के कोने: दो सीधे पक्षों के बीच एंकर @msg give corners of the path: anchors where its sides meet at an angle पाथ के कोने: एंकर जहां इसके पक्ष एक कोण पर मिलते हैं @msg give dataBase64 dataBase64 दें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3e8a200697..14624b95a2 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2831,6 +2831,7 @@ file-filter Templates Sablonok One Point Perspective Preset 5 Egypontos perspektíva, 5. előbeállítás Only Web Colors Csak webes színek Opacity Átlátszatlanság + Show Opacity Átlátszatlanság megjelenítése Opacity & Mask Define Knockout Shape Az átlátszatlanság és a maszk adja a kiütés alakját Opacity Mask Átlátszósági maszk Opacity Mask Info Átlátszósági maszk adatai @@ -6428,6 +6429,11 @@ axis Y Axis Y tengely @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many a `minItems` és a `maxItems` 0-{MAX_LIST} legyen, a `maxItems` legalább 1, és az alapértelmezett érték ennyi elemből álljon @msg `name` must be a string `name`: karakterlánc kell @msg `opacity` must be a number `opacity`: szám kell +@msg `opacity` must be a number from 0 to 100 `opacity`: 0 és 100 közötti szám kell +@msg `opacity` must be true or false `opacity`: true vagy false kell +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke a szöveg karaktereinek nincs saját átlátszatlansága: adjon hozzá kitöltést vagy körvonalat a Megjelenés panel Új kitöltés hozzáadása vagy Új körvonal hozzáadása parancsával +@msg an object selected in a symbol instance has no fill or stroke opacity of its own a szimbólumpéldányban kijelölt objektumnak nincs saját kitöltési vagy körvonal-átlátszatlansága +@msg no target has that fill or stroke to take the opacity egyik célnak sincs olyan kitöltése vagy körvonala, amely felvehetné az átlátszatlanságot @msg `type` must be "path" or "compound" `type`: "path" vagy "compound" kell @msg `unit` must be 1-{MAX_UNIT} printable characters a `unit` 1-{MAX_UNIT} nyomtatható karakter legyen @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` a `visibleWhen` 1-{MAX_CONDITION_VALUES} értéket adjon meg ehhez: `{other}` diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 2107a23bf0..414ad92198 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -418,6 +418,7 @@ Fill & Stroke Isian & stroke Fill Color Warna isian Opacity Opasitas + Show Opacity Tampilkan opasitas Stroke Color Warna stroke Fill Gradient Gradien isian Stroke Gradient Gradien stroke diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index f75dc629db..4df059fdee 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2397,6 +2397,7 @@ file-filter Templates Modelli One Point Perspective Preset 5 Preset prospettiva a un punto 5 Only Web Colors Solo colori web Opacity Opacità + Show Opacity Mostra opacità Opacity & Mask Define Knockout Shape Opacità e maschera definiscono la forma di foratura Opacity Mask Maschera di opacità Opacity Mask Info Informazioni maschera di opacità @@ -6071,6 +6072,11 @@ axis Y Axis Asse Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` e `maxItems` devono essere 0-{MAX_LIST}, `maxItems` almeno 1, e il valore predefinito deve averne altrettanti @msg `name` must be a string `name` deve essere una stringa @msg `opacity` must be a number `opacity` deve essere un numero +@msg `opacity` must be a number from 0 to 100 `opacity` deve essere un numero compreso tra 0 e 100 +@msg `opacity` must be true or false `opacity` deve essere true o false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke i caratteri del testo non hanno un'opacità propria: aggiungi un riempimento o una traccia con Aggiungi nuovo riempimento o Aggiungi nuova traccia del pannello Aspetto +@msg an object selected in a symbol instance has no fill or stroke opacity of its own un oggetto selezionato in un'istanza di simbolo non ha un'opacità propria di riempimento o di traccia +@msg no target has that fill or stroke to take the opacity nessuna destinazione ha quel riempimento o quella traccia per ricevere l'opacità @msg `type` must be "path" or "compound" `type` deve essere "path" o "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` deve avere 1-{MAX_UNIT} caratteri stampabili @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` deve elencare da 1 a {MAX_CONDITION_VALUES} valori per `{other}` @@ -8092,6 +8098,7 @@ breakText Glyphs Glifi @msg give a pattern name or select an object painted with a pattern indica il nome di un motivo o seleziona un oggetto dipinto con un motivo @msg give at least one of clip, invert, disabled, linked indica almeno uno tra clip, invert, disabled, linked @msg give color, none, swatch or gradient indica color, none, swatch o gradient +@msg give color, none, swatch, gradient or opacity indica color, none, swatch, gradient o opacity @msg give dataBase64 indica dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) indica at (un clic) o area (un tracciato disegnato attorno alle sovrapposizioni) @msg give formats or a preset, not both indica formats o un predefinito, non entrambi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 67072cc8b3..0a13792e2a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -502,6 +502,7 @@ digits Malayalam マラヤーラム数字 Side Length: 辺の長さ: Make Sides Equal 辺の長さをそろえる Opacity 不透明度 + Show Opacity 不透明度を表示 Pie End Angle: 扇形の終了角度: Pie Start Angle: 扇形の開始角度: Stroke Color カラー (線) @@ -6137,6 +6138,11 @@ axis Y Axis Y 軸 @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` と `maxItems` は 0-{MAX_LIST}、`maxItems` は 1 以上にし、デフォルト値の項目数をその範囲にしてください @msg `name` must be a string `name` は文字列にしてください @msg `opacity` must be a number `opacity` には数値を指定してください +@msg `opacity` must be a number from 0 to 100 `opacity` には 0 から 100 までの数値を指定してください +@msg `opacity` must be true or false `opacity` には true または false を指定してください +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke 文字には独自の不透明度がありません。アピアランスパネルの「新規塗りを追加」または「新規線を追加」で塗りまたは線を追加してください +@msg an object selected in a symbol instance has no fill or stroke opacity of its own シンボルインスタンス内で選択したオブジェクトには、塗りや線の独自の不透明度がありません +@msg no target has that fill or stroke to take the opacity 不透明度を適用できる塗りまたは線を持つ対象がありません @msg `type` must be "path" or "compound" `type` は "path" または "compound" にしてください @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` は印刷可能な 1-{MAX_UNIT} 文字にしてください @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` には `{other}` の値を 1 から {MAX_CONDITION_VALUES} 個指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index c8513b84c3..d3e5c5ee05 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -389,6 +389,7 @@ Fill & Stroke შევსება და კონტური Fill Color შევსების ფერი Opacity გაუმჭვირვალობა + Show Opacity გაუმჭვირვალობის ჩვენება Stroke Color კონტურის ფერი Fill Gradient შევსების გრადიენტი Stroke Gradient კონტურის გრადიენტი @@ -6396,6 +6397,11 @@ axis Y Axis Y ღერძი @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` და `maxItems` უნდა იყოს 0-{MAX_LIST}, `maxItems` მინიმუმ 1, ხოლო ნაგულისხმევ მნიშვნელობაში უნდა იყოს ამდენი ელემენტი @msg `name` must be a string `name` უნდა იყოს სტრიქონი @msg `opacity` must be a number `opacity` უნდა იყოს რიცხვი +@msg `opacity` must be a number from 0 to 100 `opacity` უნდა იყოს რიცხვი 0-დან 100-მდე +@msg `opacity` must be true or false `opacity` უნდა იყოს true ან false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke ტექსტის სიმბოლოებს საკუთარი გაუმჭვირვალობა არ აქვთ: დაამატეთ შევსება ან კონტური იერსახის პანელის ბრძანებით ახალი შევსების დამატება ან ახალი კონტურის დამატება +@msg an object selected in a symbol instance has no fill or stroke opacity of its own სიმბოლოს ეგზემპლარში არჩეულ ობიექტს შევსების ან კონტურის საკუთარი გაუმჭვირვალობა არ აქვს +@msg no target has that fill or stroke to take the opacity არცერთ სამიზნეს არ აქვს ის შევსება ან კონტური, რომელიც გაუმჭვირვალობას მიიღებს @msg `type` must be "path" or "compound" `type` უნდა იყოს "path" ან "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` უნდა შედგებოდეს 1-{MAX_UNIT} დასაბეჭდი სიმბოლოსგან @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen`-ში `{other}`-ისთვის უნდა იყოს 1-დან {MAX_CONDITION_VALUES}-მდე მნიშვნელობა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 8aa0bc41ca..a7e79ee3f7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -495,6 +495,7 @@ digits Malayalam 말라얄람어 Side Length: 변 길이: Make Sides Equal 변 길이 같게 Opacity 불투명도 + Show Opacity 불투명도 표시 Pie End Angle: 파이 끝 각도: Pie Start Angle: 파이 시작 각도: Stroke Color 선 색상 @@ -6032,6 +6033,11 @@ axis Y Axis Y축 @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems`와 `maxItems`는 0-{MAX_LIST}, `maxItems`는 1 이상이어야 하며 기본값의 항목 수도 그 범위여야 합니다 @msg `name` must be a string `name`은(는) 문자열이어야 합니다 @msg `opacity` must be a number `opacity`은(는) 숫자여야 합니다 +@msg `opacity` must be a number from 0 to 100 `opacity`은(는) 0에서 100 사이의 숫자여야 합니다 +@msg `opacity` must be true or false `opacity`은(는) true 또는 false여야 합니다 +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke 문자에는 자체 불투명도가 없습니다. 모양새 패널의 새 칠 추가 또는 새 선 추가로 칠이나 선을 추가하세요 +@msg an object selected in a symbol instance has no fill or stroke opacity of its own 심볼 인스턴스에서 선택한 개체에는 자체 칠 또는 선 불투명도가 없습니다 +@msg no target has that fill or stroke to take the opacity 불투명도를 적용할 해당 칠 또는 선이 있는 대상이 없습니다 @msg `type` must be "path" or "compound" `type`은(는) "path" 또는 "compound"여야 합니다 @msg `unit` must be 1-{MAX_UNIT} printable characters `unit`은(는) 인쇄 가능한 문자 1-{MAX_UNIT}자여야 합니다 @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen`에는 `{other}`의 값을 1-{MAX_CONDITION_VALUES}개 나열해야 합니다 @@ -7845,6 +7851,7 @@ breakText Glyphs 글리프 @msg give a pattern name or select an object painted with a pattern 패턴 이름을 지정하거나 패턴으로 칠한 개체를 선택하세요 @msg give at least one of clip, invert, disabled, linked clip, invert, disabled, linked 중 하나 이상을 지정하세요 @msg give color, none, swatch or gradient color, none, swatch 또는 gradient를 지정하세요 +@msg give color, none, swatch, gradient or opacity color, none, swatch, gradient 또는 opacity를 지정하세요 @msg give dataBase64 dataBase64를 지정하세요 @msg give either at (a click) or area (a path drawn around the overlaps) at(클릭) 또는 area(겹친 부분 둘레에 그린 패스) 중 하나를 지정하세요 @msg give exactly one of `at`, `rect` and `points` `at`, `rect`, `points` 중 정확히 하나를 지정하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index de5b7a3cf6..a6d75a9685 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -334,6 +334,11 @@ @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` en `maxItems` moeten 0-{MAX_LIST} zijn, `maxItems` minstens 1, en de standaardwaarde zoveel items @msg `name` must be a string `name` moet een string zijn @msg `opacity` must be a number `opacity` moet een getal zijn +@msg `opacity` must be a number from 0 to 100 `opacity` moet een getal van 0 tot 100 zijn +@msg `opacity` must be true or false `opacity` moet true of false zijn +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke tekens van tekst hebben geen eigen dekking: voeg een vulling of streek toe met Nieuwe vulling toevoegen of Nieuwe streek toevoegen in het deelvenster Uiterlijk +@msg an object selected in a symbol instance has no fill or stroke opacity of its own een object dat in een symboolinstantie is geselecteerd, heeft geen eigen dekking voor vulling of streek +@msg no target has that fill or stroke to take the opacity geen enkel doel heeft die vulling of streek om de dekking te krijgen @msg `type` must be "path" or "compound" `type` moet "path" of "compound" zijn @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` moet uit 1-{MAX_UNIT} afdrukbare tekens bestaan @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` noemt 1 tot {MAX_CONDITION_VALUES} waarden voor `{other}` @@ -936,6 +941,7 @@ Fill & Stroke Vulling en contour Fill Color Vulkleur Opacity Dekking + Show Opacity Dekking tonen Stroke Color Contourkleur Fill Gradient Vulverloop Stroke Gradient Contourverloop diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f9bdc664f1..d6defd07cc 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -422,6 +422,7 @@ Fill & Stroke Wypełnienie i obrys Fill Color Kolor wypełnienia Opacity Krycie + Show Opacity Pokaż krycie Stroke Color Kolor obrysu Fill Gradient Gradient wypełnienia Stroke Gradient Gradient obrysu @@ -6300,6 +6301,11 @@ axis Y Axis Oś Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` i `maxItems` muszą wynosić 0-{MAX_LIST}, `maxItems` co najmniej 1, a wartość domyślna musi mieć tyle elementów @msg `name` must be a string `name` musi być ciągiem znaków @msg `opacity` must be a number `opacity` musi być liczbą +@msg `opacity` must be a number from 0 to 100 `opacity` musi być liczbą od 0 do 100 +@msg `opacity` must be true or false `opacity` musi mieć wartość true lub false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke znaki tekstu nie mają własnego krycia: dodaj wypełnienie lub obrys poleceniem Dodaj nowe wypełnienie lub Dodaj nowy obrys w panelu Wygląd +@msg an object selected in a symbol instance has no fill or stroke opacity of its own obiekt zaznaczony w wystąpieniu symbolu nie ma własnego krycia wypełnienia ani obrysu +@msg no target has that fill or stroke to take the opacity żaden cel nie ma tego wypełnienia ani obrysu, które przyjęłoby krycie @msg `type` must be "path" or "compound" `type` musi mieć wartość "path" lub "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` musi mieć 1-{MAX_UNIT} drukowalnych znaków @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` musi podawać od 1 do {MAX_CONDITION_VALUES} wartości dla `{other}` @@ -8330,6 +8336,7 @@ breakText Glyphs Glify @msg give a pattern name or select an object painted with a pattern podaj nazwę wzorka albo zaznacz obiekt pomalowany wzorkiem @msg give at least one of clip, invert, disabled, linked podaj co najmniej jedno z: clip, invert, disabled, linked @msg give color, none, swatch or gradient podaj color, none, swatch lub gradient +@msg give color, none, swatch, gradient or opacity podaj color, none, swatch, gradient lub opacity @msg give dataBase64 podaj dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) podaj at (kliknięcie) albo area (ścieżkę narysowaną wokół nakładających się obszarów) @msg give formats or a preset, not both podaj formats albo ustawienie, nie oba naraz diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 07cd9c6fd6..1b0348fca3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1953,6 +1953,7 @@ antiAlias Sharp Nítido One page per artboard. Uma página por mesa de trabalho. Only Web Colors Apenas Cores da Web Opacity Opacidade + Show Opacity Mostrar Opacidade Opacity & Mask Define Knockout Shape Opacidade e Máscara Definem Forma de Isolamento Opacity Mask Máscara de Opacidade Opacity Mask Info Informações da Máscara de Opacidade @@ -6360,6 +6361,11 @@ axis Y Axis Eixo Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` e `maxItems` devem ser 0-{MAX_LIST}, `maxItems` pelo menos 1, e o valor padrão deve ter essa quantidade @msg `name` must be a string `name` deve ser uma string @msg `opacity` must be a number `opacity` deve ser um número +@msg `opacity` must be a number from 0 to 100 `opacity` deve ser um número de 0 a 100 +@msg `opacity` must be true or false `opacity` deve ser true ou false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke os caracteres do texto não têm opacidade própria: adicione um preenchimento ou traçado com Adicionar Novo Preenchimento ou Adicionar Novo Traçado do painel Aparência +@msg an object selected in a symbol instance has no fill or stroke opacity of its own um objeto selecionado em uma instância de símbolo não tem opacidade própria de preenchimento ou traçado +@msg no target has that fill or stroke to take the opacity nenhum destino tem esse preenchimento ou traçado para receber a opacidade @msg `type` must be "path" or "compound" `type` deve ser "path" ou "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` deve ter 1-{MAX_UNIT} caracteres imprimíveis @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` deve listar de 1 a {MAX_CONDITION_VALUES} valores para `{other}` @@ -8319,6 +8325,7 @@ swatch Yellow Green Verde-amarelado @msg give a pattern name or select an object painted with a pattern informe o nome de um padrão ou selecione um objeto pintado com um padrão @msg give at least one of clip, invert, disabled, linked informe pelo menos um de clip, invert, disabled, linked @msg give color, none, swatch or gradient informe color, none, swatch ou gradient +@msg give color, none, swatch, gradient or opacity informe color, none, swatch, gradient ou opacity @msg give dataBase64 informe dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) informe at (um clique) ou area (um caminho desenhado em volta das sobreposições) @msg give exactly one of `at`, `rect` and `points` informe exatamente um de `at`, `rect` e `points` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fcf44192cd..fbd597e053 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2384,6 +2384,7 @@ file-filter Templates Шаблоны One Point Perspective Preset 5 Набор одноточечной перспективы 5 Only Web Colors Только web-цвета Opacity Непрозрачность + Show Opacity Показать непрозрачность Opacity & Mask Define Knockout Shape Непрозрачность и маска определяют форму вырезания Opacity Mask Непрозрачная маска Opacity Mask Info Сведения о непрозрачной маске @@ -6056,6 +6057,11 @@ axis Y Axis Ось Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` и `maxItems` должны быть 0-{MAX_LIST}, `maxItems` не меньше 1, а значение по умолчанию должно содержать столько элементов @msg `name` must be a string `name` должно быть строкой @msg `opacity` must be a number `opacity` должно быть числом +@msg `opacity` must be a number from 0 to 100 `opacity` должно быть числом от 0 до 100 +@msg `opacity` must be true or false `opacity` должно быть true или false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke у символов текста нет собственной непрозрачности: добавьте заливку или обводку командой «Добавить новую заливку» или «Добавить новую обводку» на панели «Оформление» +@msg an object selected in a symbol instance has no fill or stroke opacity of its own у объекта, выбранного в экземпляре символа, нет собственной непрозрачности заливки или обводки +@msg no target has that fill or stroke to take the opacity ни у одного объекта нет такой заливки или обводки, чтобы задать непрозрачность @msg `type` must be "path" or "compound" `type` должно быть "path" или "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` должно содержать 1-{MAX_UNIT} печатаемых символов @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` должно перечислять от 1 до {MAX_CONDITION_VALUES} значений для `{other}` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d68878734e..b1d4b9c704 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2298,6 +2298,7 @@ font-technology Variable Variabla One Point Perspective Preset 5 Förinställning 5 för enpunktsperspektiv Only Web Colors Endast webbfärger Opacity Opacitet + Show Opacity Visa opacitet Opacity & Mask Define Knockout Shape Opacitet och mask definierar utsparningsform Opacity Mask Opacitetsmask Opacity Mask Info Info om opacitetsmask @@ -6430,6 +6431,11 @@ axis Y Axis Y-axel @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` och `maxItems` måste vara 0-{MAX_LIST}, `maxItems` minst 1, och standardvärdet måste ha så många poster @msg `name` must be a string `name` måste vara en sträng @msg `opacity` must be a number `opacity` måste vara ett tal +@msg `opacity` must be a number from 0 to 100 `opacity` måste vara ett tal från 0 till 100 +@msg `opacity` must be true or false `opacity` måste vara true eller false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke tecken i text har ingen egen opacitet: lägg till en fyllning eller kontur med Lägg till ny fyllning eller Lägg till ny kontur i panelen Utseende +@msg an object selected in a symbol instance has no fill or stroke opacity of its own ett objekt som är markerat i en symbolinstans har ingen egen opacitet för fyllning eller kontur +@msg no target has that fill or stroke to take the opacity inget mål har den fyllningen eller konturen som kan ta emot opaciteten @msg `type` must be "path" or "compound" `type` måste vara "path" eller "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` måste ha 1-{MAX_UNIT} utskrivbara tecken @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` måste ange 1 till {MAX_CONDITION_VALUES} värden för `{other}` @@ -8030,6 +8036,7 @@ digits Hindi Hindi @msg give a pattern name or select an object painted with a pattern ange ett mönsternamn eller markera ett objekt som är målat med ett mönster @msg give at least one of clip, invert, disabled, linked ange minst en av clip, invert, disabled, linked @msg give color, none, swatch or gradient ange color, none, swatch eller gradient +@msg give color, none, swatch, gradient or opacity ange color, none, swatch, gradient eller opacity @msg give dataBase64 ange dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) ange antingen at (ett klick) eller area (en bana ritad runt överlappningarna) @msg give formats or a preset, not both ange formats eller en förinställning, inte båda diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index e51e321781..147a80067b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -362,6 +362,30 @@ fn objects_on_path_detach_strings_are_in_complete_catalogs() { } } +/// The Color Wheel panel's Show Opacity and the errors of `paint.setFill {opacity}` and +/// `ui.colorWheel {opacity}`. +#[test] +fn color_wheel_opacity_strings_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + assert!(lang.catalog().plain("Show Opacity").is_some(), "{} is missing Show Opacity", lang.code); + } + let messages = [ + "`opacity` must be a number from 0 to 100", + "`opacity` must be true or false", + "type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke", + "an object selected in a symbol instance has no fill or stroke opacity of its own", + "no target has that fill or stroke to take the opacity", + ]; + let literals = message_literals(); + for m in messages { + assert!(literals.contains(m), "{m}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, m), m, "{code}"); + } + } +} + /// The Window › Brush Libraries menu, built from the built-in library table, names each library. #[test] fn built_in_brush_library_names_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b3c88cc563..ef5a6dd45a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2143,6 +2143,7 @@ font-technology Variable Değişken One Point Perspective Preset 5 Tek Noktalı Perspektif Ön Ayarı 5 Only Web Colors Yalnızca Web Renkleri Opacity Opaklık + Show Opacity Opaklığı Göster Opacity & Mask Define Knockout Shape Opaklık ve Maske Tanımlama Nakavt Şekli Opacity Mask Opaklık Maskesi Opacity Mask Info Opaklık Maskesi Bilgisi @@ -6401,6 +6402,11 @@ axis Y Axis Y ekseni @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` ve `maxItems` 0-{MAX_LIST} olmalı, `maxItems` en az 1 olmalı ve varsayılan değer bu kadar öğe içermelidir @msg `name` must be a string `name` bir dize olmalıdır @msg `opacity` must be a number `opacity` bir sayı olmalıdır +@msg `opacity` must be a number from 0 to 100 `opacity` 0 ile 100 arasında bir sayı olmalıdır +@msg `opacity` must be true or false `opacity` true veya false olmalıdır +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke metin karakterlerinin kendi opaklığı yoktur: Görünüm panelindeki Yeni Dolgu Ekle veya Yeni Kontur Ekle ile bir dolgu veya kontur ekleyin +@msg an object selected in a symbol instance has no fill or stroke opacity of its own bir sembol örneğinde seçilen nesnenin kendi dolgu veya kontur opaklığı yoktur +@msg no target has that fill or stroke to take the opacity hiçbir hedefte opaklığı alacak o dolgu veya kontur yok @msg `type` must be "path" or "compound" `type` "path" veya "compound" olmalıdır @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` 1-{MAX_UNIT} yazdırılabilir karakter olmalıdır @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen`, `{other}` için 1 ile {MAX_CONDITION_VALUES} arasında değer listelemelidir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0ab6257df4..ef694e2548 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2389,6 +2389,7 @@ file-filter Templates Шаблони One Point Perspective Preset 5 Набір одноточкової перспективи 5 Only Web Colors Тільки web-кольору Opacity Непрозорість + Show Opacity Показати непрозорість Opacity & Mask Define Knockout Shape Непрозорість та маска визначають форму вирізування Opacity Mask Маска непрозорості Opacity Mask Info Відомості про маску непрозорості @@ -6051,6 +6052,11 @@ axis Y Axis Вісь Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` і `maxItems` мають бути 0-{MAX_LIST}, `maxItems` щонайменше 1, а типове значення має містити стільки елементів @msg `name` must be a string `name` має бути рядком @msg `opacity` must be a number `opacity` має бути числом +@msg `opacity` must be a number from 0 to 100 `opacity` має бути числом від 0 до 100 +@msg `opacity` must be true or false `opacity` має бути true або false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke символи тексту не мають власної непрозорості: додайте заливку або обведення командою «Додати нову заливку» або «Додати нове обведення» на панелі «Оформлення» +@msg an object selected in a symbol instance has no fill or stroke opacity of its own об’єкт, виділений в екземплярі символу, не має власної непрозорості заливки чи обведення +@msg no target has that fill or stroke to take the opacity жодна ціль не має такої заливки чи обведення, щоб задати непрозорість @msg `type` must be "path" or "compound" `type` має бути "path" або "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` має містити 1-{MAX_UNIT} друкованих символів @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` має перелічувати від 1 до {MAX_CONDITION_VALUES} значень для `{other}` @@ -7853,6 +7859,7 @@ breakText Glyphs Гліфи @msg give a pattern name or select an object painted with a pattern укажіть ім’я візерунка або виділіть об’єкт, зафарбований візерунком @msg give at least one of clip, invert, disabled, linked укажіть принаймні одне з: clip, invert, disabled, linked @msg give color, none, swatch or gradient укажіть color, none, swatch або gradient +@msg give color, none, swatch, gradient or opacity укажіть color, none, swatch, gradient або opacity @msg give dataBase64 укажіть dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) укажіть at (клацання) або area (контур, намальований навколо перекриттів) @msg give exactly one of `path`, `data` and `dataBase64` укажіть рівно одне з: `path`, `data`, `dataBase64` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 80cc4951cf..7270b86711 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2652,6 +2652,7 @@ digits Hindi Hindi One Point Perspective Preset 5 Thiết lập sẵn phối cảnh một điểm 5 Only Web Colors Chỉ màu web Opacity Độ mờ + Show Opacity Hiện độ mờ Opacity & Mask Define Knockout Shape Độ mờ & Mặt nạ xác định hình dạng Knockout Opacity Mask Mặt nạ độ mờ Opacity Mask Info Thông tin mặt nạ độ mờ @@ -6052,6 +6053,11 @@ axis Y Axis Trục Y @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` và `maxItems` phải là 0-{MAX_LIST}, `maxItems` ít nhất là 1, và giá trị mặc định phải có đúng số mục đó @msg `name` must be a string `name` phải là một chuỗi @msg `opacity` must be a number `opacity` phải là một số +@msg `opacity` must be a number from 0 to 100 `opacity` phải là một số từ 0 đến 100 +@msg `opacity` must be true or false `opacity` phải là true hoặc false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke ký tự văn bản không có độ mờ riêng: hãy thêm tô hoặc nét bằng Thêm tô mới hoặc Thêm nét mới trong bảng Diện mạo +@msg an object selected in a symbol instance has no fill or stroke opacity of its own đối tượng được chọn trong một phiên bản biểu tượng không có độ mờ tô hoặc nét riêng +@msg no target has that fill or stroke to take the opacity không đối tượng nào có tô hoặc nét đó để nhận độ mờ @msg `type` must be "path" or "compound" `type` phải là "path" hoặc "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` phải có 1-{MAX_UNIT} ký tự in được @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` phải liệt kê 1 đến {MAX_CONDITION_VALUES} giá trị cho `{other}` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9561a51baf..5de2f2b4e6 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2252,6 +2252,7 @@ file-filter Templates 模板 One Point Perspective Preset 5 一点透视预设 5 Only Web Colors 仅 Web 颜色 Opacity 不透明度 + Show Opacity 显示不透明度 Opacity & Mask Define Knockout Shape 不透明度与蒙版定义挖空形状 Opacity Mask 不透明度蒙版 Opacity Mask Info 不透明度蒙版信息 @@ -6284,6 +6285,11 @@ axis Y Axis Y 轴 @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` 和 `maxItems` 必须是 0-{MAX_LIST},`maxItems` 至少为 1,且默认值的项数在此范围内 @msg `name` must be a string `name` 必须是字符串 @msg `opacity` must be a number `opacity` 必须是数字 +@msg `opacity` must be a number from 0 to 100 `opacity` 必须是 0 到 100 之间的数字 +@msg `opacity` must be true or false `opacity` 必须是 true 或 false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke 文字字符没有自己的不透明度:请用“外观”面板的“添加新填色”或“添加新描边”添加填色或描边 +@msg an object selected in a symbol instance has no fill or stroke opacity of its own 在符号实例中选中的对象没有自己的填色或描边不透明度 +@msg no target has that fill or stroke to take the opacity 没有目标具有可接受该不透明度的填色或描边 @msg `type` must be "path" or "compound" `type` 必须是 "path" 或 "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` 必须是 1-{MAX_UNIT} 个可打印字符 @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` 必须为 `{other}` 列出 1 到 {MAX_CONDITION_VALUES} 个值 @@ -8316,6 +8322,7 @@ breakText Glyphs 字形 @msg give a pattern name or select an object painted with a pattern 请给出图案名称,或选择用图案上色的对象 @msg give at least one of clip, invert, disabled, linked 请至少给出 clip、invert、disabled、linked 之一 @msg give color, none, swatch or gradient 请给出 color、none、swatch 或 gradient +@msg give color, none, swatch, gradient or opacity 请给出 color、none、swatch、gradient 或 opacity @msg give dataBase64 请给出 dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) 请给出 at (一次单击) 或 area (围绕重叠处绘制的路径) @msg give formats or a preset, not both 请给出 formats 或一个预设,不能两者都给 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7489e3d4d9..88a9de0354 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3467,6 +3467,7 @@ file-filter Templates 範本 One Point Perspective Preset 5 一點透視預設集 5 Only Web Colors 僅限網頁色彩 Opacity 不透明度 + Show Opacity 顯示不透明度 Opacity & Mask Define Knockout Shape 不透明度與遮色片定義挖空形狀 Opacity Mask 不透明度遮色片 Opacity Mask Info 不透明度遮色片資訊 @@ -6091,6 +6092,11 @@ axis Y Axis Y 軸 @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` 和 `maxItems` 必須是 0-{MAX_LIST},`maxItems` 至少為 1,且預設值的項目數須在此範圍內 @msg `name` must be a string `name` 必須是字串 @msg `opacity` must be a number `opacity` 必須是數字 +@msg `opacity` must be a number from 0 to 100 `opacity` 必須是 0 到 100 之間的數字 +@msg `opacity` must be true or false `opacity` 必須是 true 或 false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke 文字字元沒有自己的不透明度:請用「外觀」面板的「新增填色」或「新增筆畫」新增填色或筆畫 +@msg an object selected in a symbol instance has no fill or stroke opacity of its own 在符號實體中選取的物件沒有自己的填色或筆畫不透明度 +@msg no target has that fill or stroke to take the opacity 沒有目標具有可接受該不透明度的填色或筆畫 @msg `type` must be "path" or "compound" `type` 必須是 "path" 或 "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` 必須是 1-{MAX_UNIT} 個可列印字元 @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` 必須為 `{other}` 列出 1 到 {MAX_CONDITION_VALUES} 個值 @@ -8125,6 +8131,7 @@ breakText Glyphs 字符 @msg give a pattern name or select an object painted with a pattern 請提供圖樣名稱,或選取以圖樣上色的物件 @msg give at least one of clip, invert, disabled, linked clip、invert、disabled、linked 請至少提供一個 @msg give color, none, swatch or gradient 請提供 color、none、swatch 或 gradient +@msg give color, none, swatch, gradient or opacity 請提供 color、none、swatch、gradient 或 opacity @msg give dataBase64 請提供 dataBase64 @msg give either at (a click) or area (a path drawn around the overlaps) 請提供 at (一次點按) 或 area (圍繞重疊處繪製的路徑) 其中之一 @msg give formats or a preset, not both 請提供 formats 或預設集,不要兩者都提供 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d36ecae60f..cd2d578a75 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1325,7 +1325,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); keys left out keep their values, params that are not an object, another key or a value off the list (opacity: not true or false) are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index d12c89d2af..5b74101284 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -698,6 +698,8 @@ mod tests_color_wheel; #[cfg(test)] mod tests_color_wheel_box; #[cfg(test)] +mod tests_color_wheel_opacity; +#[cfg(test)] mod tests_constrain; #[cfg(test)] mod tests_css_properties; diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 31522578e5..6356d96666 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -11,6 +11,13 @@ //! channel strip at its right, for the channel picked under Box Channel (Hue, Saturation, //! Brightness, Red, Green or Blue). The field shows the other two components on the Color //! Picker's axes. The view and the channel are kept with the preferences (`ui.colorWheel`). +//! +//! The panel menu's Show Opacity adds a row under the wheel or the box that sets the opacity of +//! what the panel edits: the fill or stroke item (`paint.setFill {opacity}`), the selected +//! gradient stop or the selected freeform point (the first stop or point when none is selected, +//! as for a color pick). The row is gray with nothing selected, for an object selected in a symbol +//! instance, and when the fill or stroke item it would set is on type characters or missing. The +//! setting is kept with the preferences (`ui.colorWheel`). use egui::{Ui, UiBuilder, vec2}; use serde::{Deserialize, Serialize}; @@ -20,7 +27,7 @@ use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb}; use vectorcraft_doc::{ColorMode, NodeId}; use super::color::{Target, apply, wheel_target}; -use super::{pstate, set_pstate}; +use super::{live_run, pstate, set_pstate}; use crate::VectorcraftApp; use crate::dialogs::color_picker::Channel; use crate::widgets::{self, FieldAxis, Live, SliderValue, menu_item}; @@ -32,6 +39,8 @@ const MAX_WHEEL: f32 = 200.0; const STRIP: f32 = 22.0; /// The space between the box's field and its channel strip. const STRIP_GAP: f32 = 6.0; +/// The width of the opacity row's percent field. +const OPACITY_FIELD: f32 = 46.0; /// What the panel shows right of the proxy: the wheel, or the box (a color field and a channel /// strip). @@ -67,6 +76,9 @@ pub struct Settings { pub view: View, #[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")] pub channel: Channel, + /// Show Opacity: the opacity row under the wheel or the box. + #[serde(deserialize_with = "deserialize_flag")] + pub opacity: bool, } fn deserialize_view<'de, D: serde::Deserializer<'de>>(d: D) -> Result { @@ -83,6 +95,11 @@ fn deserialize_channel<'de, D: serde::Deserializer<'de>>(d: D) -> Result>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(v.as_bool().unwrap_or_default()) +} + /// Serde reader for the saved settings ([`crate::UiState::color_wheel`]): a value that is not an /// object reads as the defaults, so it doesn't lose the rest of the preferences. pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result { @@ -90,11 +107,11 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result Result { - const KEYS: [&str; 2] = ["view", "channel"]; + const KEYS: [&str; 3] = ["view", "channel", "opacity"]; match p { Value::Null => {} Value::Object(o) => { @@ -113,11 +130,15 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result {} Some(v) => set.channel = v.as_str().and_then(Channel::parse).ok_or("`channel` must be hue, saturation, brightness, red, green or blue")?, } + match p.get("opacity") { + None | Some(Value::Null) => {} + Some(v) => set.opacity = v.as_bool().ok_or("`opacity` must be true or false")?, + } app.ui.color_wheel = set; Ok(json!(app.ui.color_wheel)) } -/// The panel menu: Wheel View and Box View, and Box Channel while the box shows. +/// The panel menu: Wheel View and Box View, Box Channel while the box shows, and Show Opacity. pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let set = app.ui.color_wheel.clone(); for (label, view) in [(tl!("Wheel View"), View::Wheel), (tl!("Box View"), View::Box)] { @@ -134,6 +155,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } }); }); + ui.separator(); + if menu_item(ui, tl!("Show Opacity"), true, set.opacity) { + command(app, &json!({ "opacity": !set.opacity })).ok(); + } } /// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness, @@ -205,6 +230,80 @@ fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> pick } +/// The opacity (0 to 1) the row shows for `tgt` and whether the row can set it: the selected +/// gradient stop's or freeform point's (the first when none is selected, as [`wheel_target`] +/// picks it), else that of the fill or stroke item +/// ([`vectorcraft_engine::Session::proxy_opacity`]), which nothing selected and type characters +/// do not have. A stop or point of a gradient on type characters belongs to the gradient, so the +/// row sets it. With nothing selected the stop or point belongs to the defaults for new art, which +/// the row leaves alone, and an object selected in a symbol instance has no opacity the row can set. +fn shown_opacity(app: &VectorcraftApp, tgt: &Target) -> (f32, bool) { + let stroke = !app.session.fill_active; + let selected = app.session.active().is_some_and(|d| !d.selection.is_empty() && d.selection.symbol_part.is_none()); + let point = |index: usize| match super::active_paint(app) { + Paint::Gradient(g) => super::gradient::shown_points(&g).points.get(index).map(|p| p.opacity), + _ => None, + }; + let found = match tgt { + _ if !selected => None, + Target::Stop { paint: Paint::Gradient(g), index, .. } => g.gradient.stops.get(*index).map(|s| s.opacity), + Target::Point { index, .. } => point(*index), + _ => app.session.proxy_opacity(stroke), + }; + (found.unwrap_or(1.0), found.is_some()) +} + +/// Set the opacity (0 to 1) of what the row edits for `tgt`: a stop through the Gradient panel's +/// edit, a freeform point through `paint.freeform.setPoint`, else the fill or stroke item through +/// `paint.setFill` or `paint.setStroke`. A drag previews and commits as one undo step. +fn apply_opacity(app: &mut VectorcraftApp, tgt: &Target, o: f32, phase: Live) { + let o = o.clamp(0.0, 1.0); + match tgt { + Target::Stop { paint: Paint::Gradient(g), index, .. } => { + let mut stops = g.gradient.stops.clone(); + if let Some(s) = stops.get_mut(*index) { + s.opacity = o; + } + super::gradient::set_stops_keeping_models(app, &stops, None, phase); + } + Target::Point { index, .. } => { + let p = json!({"index": index, "opacity": o, "stroke": !app.session.fill_active}); + live_run(app, "Opacity", "paint.freeform.setPoint", p, phase); + } + _ => { + let cmd = super::proxy_cmd(app, false); + live_run(app, "Opacity", cmd, json!({"opacity": f64::from(o) * 100.0}), phase); + } + } +} + +/// The Show Opacity row: the Transparency panel's icon, a slider whose track shows `color` from +/// clear to solid, and a percent field. Gray when [`shown_opacity`] finds nothing to set. +fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Color) { + let (o, live) = shown_opacity(app, tgt); + let percent = f64::from(o) * 100.0; + let mut edit: Option<(f32, Live)> = None; + ui.add_enabled_ui(live, |ui| { + ui.horizontal(|ui| { + let t = crate::theme::Tokens::get(ui.ctx()); + crate::icons::icon(ui, "dc-transparency", 16.0, if live { t.icon } else { t.text_disabled }).on_hover_text(tl!("Opacity")); + let width = (ui.available_width() - OPACITY_FIELD - ui.spacing().item_spacing.x).max(40.0); + let shown = SliderValue::field(percent, 0.0..=100.0, "%", 0); + match widgets::opacity_slider(ui, "color-wheel-opacity", tl!("Opacity"), Some(shown), o, width, super::c32(color)) { + (Some(v), phase, _) => edit = Some((v, phase)), + (None, _, Some(v)) => edit = Some(((v / 100.0) as f32, Live::Released)), + _ => {} + } + if let Some(v) = widgets::plain_field_named(ui, "color-wheel-opacity-field", Some(tl!("Opacity")), percent, "%", 0, OPACITY_FIELD) { + edit = Some(((v.clamp(0.0, 100.0) / 100.0) as f32, Live::Released)); + } + }); + }); + if let Some((v, phase)) = edit.filter(|_| live) { + apply_opacity(app, tgt, v, phase); + } +} + /// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored. const MEMORY: &str = "color-wheel-hsb"; @@ -344,6 +443,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { pick = Some(([hsb[0], x, 1.0 - y], field_phase)); } }); + if app.ui.color_wheel.opacity { + let shown = color.unwrap_or(app.session.last_solid); + opacity_row(app, ui, &tgt, &shown); + } let Some((hsb, phase)) = pick else { return }; let behind = super::alt_held(ui); let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index d3866fd5d9..a19d472d70 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -167,16 +167,16 @@ fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() { #[test] fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue"})); - assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue"})); - assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green"})); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue", "opacity": false})); + assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue", "opacity": false})); + assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green", "opacity": false})); let e = app.run("ui.colorWheel", json!({"view": "triangle"})).unwrap_err(); assert_eq!(e, "`view` must be wheel or box"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "channel": 7})).unwrap_err(); assert_eq!(e, "`channel` must be hue, saturation, brightness, red, green or blue"); - assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green }, "an error changes nothing"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green, ..Default::default() }, "an error changes nothing"); let ui = crate::control::inspect(&app, &egui::Context::default()); - assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green"})); + assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green", "opacity": false})); } /// The command's errors are translated in the catalogs that translate status and error messages, @@ -211,10 +211,10 @@ fn ui_color_wheel_rejects_other_params() { let e = app.run("ui.colorWheel", json!([1])).unwrap_err(); assert_eq!(e, "the params must be an object, not [1]"); let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err(); - assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel"); + assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, opacity"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); - assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel"); - assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red }, "an error changes nothing"); + assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, opacity"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } /// With None there is no color to edit: the strip reads 0 to screen readers, as the hue ring does, @@ -249,7 +249,11 @@ fn ui_color_wheel_answers_junk_params_without_a_panic() { /// not know reads as the key's default without losing the other preferences. #[test] fn the_settings_are_kept_and_read_leniently() { - let ui = crate::UiState { color_wheel: Settings { view: View::Box, channel: Channel::Blue }, color_rgb_percent: true, ..Default::default() }; + let ui = crate::UiState { + color_wheel: Settings { view: View::Box, channel: Channel::Blue, ..Default::default() }, + color_rgb_percent: true, + ..Default::default() + }; let saved = serde_json::to_value(&ui).unwrap(); let back: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); assert_eq!(back.color_wheel, ui.color_wheel); @@ -262,11 +266,11 @@ fn the_settings_are_kept_and_read_leniently() { let mut odd = saved.clone(); odd["color_wheel"] = json!({"view": "box", "channel": 7}); let back: crate::UiState = serde_json::from_value(odd).unwrap(); - assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default() }); + assert_eq!(back.color_wheel, Settings { view: View::Box, ..Default::default() }); let mut odd = saved.clone(); odd["color_wheel"] = json!({"view": "triangle", "channel": "blue"}); let back: crate::UiState = serde_json::from_value(odd).unwrap(); - assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue }); + assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue, ..Default::default() }); let mut odd = saved; odd["color_wheel"] = json!("box"); let back: crate::UiState = serde_json::from_value(odd).unwrap(); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs new file mode 100644 index 0000000000..8dbcf0f15f --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -0,0 +1,322 @@ +//! The Color Wheel panel's Show Opacity row drawn headless: the setting and `ui.colorWheel`, the +//! slider on a fill, a gradient stop and a freeform point, the keys, screen readers, the percent +//! field and the gray row. + +use egui::accesskit::{Action, ActionData, ActionRequest, Role}; +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use vectorcraft_color::Paint; +use vectorcraft_engine::Session; + +use super::color_wheel::{Settings, show}; +use crate::VectorcraftApp; + +/// An app with a selected red rectangle and Show Opacity checked. +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("ui.colorWheel", json!({"opacity": true})).unwrap(); + app +} + +fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 360.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h +} + +fn click(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2) { + for pressed in [true, false] { + h.event(Event::PointerMoved(pos)); + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(1); +} + +fn slider_rect(h: &Harness<'static, VectorcraftApp>) -> egui::Rect { + h.get_by_role_and_label(Role::Slider, "Opacity").rect() +} + +/// The middle of the slider's bar (the rail draws its bar 4 points in from each side). +fn middle(h: &Harness<'static, VectorcraftApp>) -> Pos2 { + let r = slider_rect(h); + Pos2::new(r.center().x, r.top() + 7.0) +} + +fn fill_opacity(app: &VectorcraftApp) -> f32 { + app.session.proxy_opacity(false).expect("a fill item") +} + +fn undo_labels(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect() +} + +fn action(h: &mut Harness<'static, VectorcraftApp>, action: Action, data: Option) { + let (target_node, target_tree) = h.get_by_role_and_label(Role::Slider, "Opacity").accesskit_node().locate(); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action, data })); + h.run_steps(2); +} + +/// The panel menu's Show Opacity and `ui.colorWheel {opacity}` check and uncheck the row; a bad +/// value is an error and changes nothing. +#[test] +fn show_opacity_is_a_setting_of_the_panel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["opacity"], json!(false)); + assert_eq!(app.run("ui.colorWheel", json!({"opacity": true})).unwrap()["opacity"], json!(true)); + let e = app.run("ui.colorWheel", json!({"opacity": "no"})).unwrap_err(); + assert_eq!(e, "`opacity` must be true or false"); + assert!(app.ui.color_wheel.opacity); + assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_wheel"]["opacity"], json!(true)); + let set = app.run("ui.colorWheel", json!({"view": "box"})).unwrap(); + assert_eq!(set["opacity"], json!(true), "another key keeps Show Opacity"); + app.run("ui.colorWheel", json!({"opacity": false})).unwrap(); + let h = harness({ + let mut app = self::app(); + app.run("ui.colorWheel", json!({"opacity": false})).unwrap(); + app + }); + assert!(h.query_by_role_and_label(Role::Slider, "Opacity").is_none(), "no row while unchecked"); +} + +/// The row also shows under the box, and a click at its middle sets the fill item's opacity there. +#[test] +fn the_row_shows_under_the_box_view() { + let mut app = app(); + app.run("ui.colorWheel", json!({"view": "box"})).unwrap(); + let mut h = harness(app); + assert!(h.query_by_label("Color box").is_some(), "the box shows"); + let at = middle(&h); + click(&mut h, at); + assert!((fill_opacity(h.state()) - 0.5).abs() < 0.03, "{}", fill_opacity(h.state())); +} + +/// A value this build does not read keeps the rest of the preferences and reads as the default. +#[test] +fn saved_settings_read_leniently() { + let mut saved = serde_json::to_value(crate::UiState::default()).unwrap(); + saved["color_rgb_percent"] = json!(true); + for bad in [json!("box"), json!({"opacity": "yes"}), json!(7)] { + saved["color_wheel"] = bad.clone(); + let ui: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(ui.color_wheel, Settings::default(), "{bad}"); + assert!(ui.color_rgb_percent, "{bad}"); + } + saved["color_wheel"] = json!({"opacity": true, "later": 1}); + let ui: crate::UiState = serde_json::from_value(saved).unwrap(); + assert!(ui.color_wheel.opacity); +} + +/// A click at the middle of the track sets the fill item's opacity to about 50 % as one undo step +/// named Opacity, the fill keeps its color, and → then adds 1 %. +#[test] +fn the_slider_sets_the_fill_opacity_and_takes_the_arrow_keys() { + let mut h = harness(app()); + let undo = undo_labels(h.state()).len(); + let at = middle(&h); + click(&mut h, at); + let o = fill_opacity(h.state()); + assert!((o - 0.5).abs() < 0.02, "{o}"); + let labels = undo_labels(h.state()); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity"))); + assert_eq!(crate::panels::current_paints(h.state()).0.color().unwrap().to_hex(), "#ff0000"); + let before = (o * 100.0).round(); + h.key_press_modifiers(Modifiers::NONE, egui::Key::ArrowRight); + h.run_steps(2); + assert_eq!((fill_opacity(h.state()) * 100.0).round(), before + 1.0); +} + +/// Screen readers get a slider named Opacity with its percentage and its range, and can step it and +/// set it. +#[test] +fn screen_readers_read_and_set_the_opacity() { + let mut h = harness(app()); + let node = h.get_by_role_and_label(Role::Slider, "Opacity"); + let data = node.accesskit_node(); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| data.data().supports_action(*a))); + assert_eq!(data.numeric_value(), Some(100.0)); + assert_eq!((data.min_numeric_value(), data.max_numeric_value()), (Some(0.0), Some(100.0))); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(25.0))); + assert!((fill_opacity(h.state()) - 0.25).abs() < 1e-6); + action(&mut h, Action::Decrement, None); + assert!((fill_opacity(h.state()) - 0.24).abs() < 1e-6); +} + +/// The stroke proxy in front: the row sets the stroke item's opacity and leaves the fill's. +#[test] +fn with_the_stroke_in_front_the_row_sets_the_stroke() { + let mut app = app(); + app.run("paint.toggleActive", json!({})).unwrap(); + let mut h = harness(app); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(40.0))); + assert!((h.state().session.proxy_opacity(true).unwrap() - 0.4).abs() < 1e-6); + assert_eq!(fill_opacity(h.state()), 1.0); +} + +/// A selected gradient stop takes the opacity, and the other stop keeps its own. +#[test] +fn a_selected_gradient_stop_takes_the_opacity() { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap(); + app.select_tool("gradient"); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let mut h = harness(app); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(30.0))); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let o: Vec = g.gradient.stops.iter().map(|s| s.opacity).collect(); + assert!((o[0] - 1.0).abs() < 1e-6 && (o[1] - 0.3).abs() < 1e-6, "{o:?}"); + assert_eq!(fill_opacity(h.state()), 1.0, "the fill item keeps its opacity"); +} + +/// With no stop selected, the first stop takes the opacity, as it takes a color pick. +#[test] +fn without_a_selected_stop_the_first_takes_the_opacity() { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap(); + assert_eq!(app.session.selected_stop(), None); + let mut h = harness(app); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(30.0))); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let o: Vec = g.gradient.stops.iter().map(|s| s.opacity).collect(); + assert!((o[0] - 0.3).abs() < 1e-6 && (o[1] - 1.0).abs() < 1e-6, "{o:?}"); +} + +/// A drag across the slider previews and ends as one undo step named Opacity. +#[test] +fn a_drag_is_one_undo_step() { + let mut h = harness(app()); + let undo = undo_labels(h.state()).len(); + let r = slider_rect(&h); + let y = r.top() + 7.0; + let (from, to) = (Pos2::new(r.left() + 10.0, y), Pos2::new(r.right() - 20.0, y)); + h.event(Event::PointerMoved(from)); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + for k in 1..=6 { + h.event(Event::PointerMoved(from + (to - from) * (k as f32 / 6.0))); + h.run_steps(1); + } + h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + let o = fill_opacity(h.state()); + assert!(o > 0.7 && o < 1.0, "{o}"); + let labels = undo_labels(h.state()); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity"))); +} + +/// A selected object without a fill item beside one with a fill item: the row shows and sets the +/// second one's opacity. +#[test] +fn an_object_without_a_fill_item_leaves_the_row_to_the_next() { + let mut app = app(); + let first = app.session.doc().unwrap().selection.objects[0]; + app.run("appearance.removeItem", json!({"index": 0})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 10, "width": 50, "height": 50})).unwrap(); + let second = app.session.doc().unwrap().selection.objects[0]; + app.run("select.set", json!({"ids": [first.0, second.0]})).unwrap(); + let mut h = harness(app); + assert!(!h.get_by_role_and_label(Role::Slider, "Opacity").accesskit_node().is_disabled()); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(45.0))); + let n = h.state().session.doc().unwrap().doc.node(second).unwrap().clone(); + assert!((n.appearance.fill().unwrap().opacity - 0.45).abs() < 1e-6); +} + +/// Type painted with a gradient: the row sets the gradient's stop, which belongs to the gradient. +#[test] +fn a_gradient_stop_on_type_takes_the_opacity() { + let mut app = app(); + app.run("text.create", json!({"x": 10, "y": 150, "text": "Hi"})).unwrap(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops}})).unwrap(); + let mut h = harness(app); + assert!(!h.get_by_role_and_label(Role::Slider, "Opacity").accesskit_node().is_disabled()); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(30.0))); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + assert!((g.gradient.stops[0].opacity - 0.3).abs() < 1e-6, "{:?}", g.gradient.stops); +} + +/// The selected freeform point takes the opacity. +#[test] +fn the_selected_freeform_point_takes_the_opacity() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {"kind": "freeform"}})).unwrap(); + let mut h = harness(app); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(60.0))); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let f = super::gradient::shown_points(&g); + assert!((f.points[0].opacity - 0.6).abs() < 1e-6, "{:?}", f.points.iter().map(|p| p.opacity).collect::>()); +} + +/// The percent field takes a typed value. +#[test] +fn the_percent_field_takes_a_typed_value() { + let mut h = harness(app()); + h.get_by_role_and_label(Role::TextInput, "Opacity").click(); + h.run_steps(1); + h.get_by_role_and_label(Role::TextInput, "Opacity").type_text("35"); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!((fill_opacity(h.state()) - 0.35).abs() < 1e-6, "{}", fill_opacity(h.state())); +} + +/// With nothing selected, and with only type selected (its characters take the paint), the row is +/// gray and screen readers cannot set it. +#[test] +fn the_row_is_gray_with_nothing_selected_and_on_type() { + let mut app = app(); + app.run("select.none", json!({})).unwrap(); + let mut h = harness(app); + assert!(h.get_by_role_and_label(Role::Slider, "Opacity").accesskit_node().is_disabled()); + let doc = h.state().session.doc().unwrap().doc.clone(); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(25.0))); + assert_eq!(*h.state().session.doc().unwrap().doc, *doc); + + let mut app = self::app(); + app.run("text.create", json!({"x": 10, "y": 150, "text": "Hi"})).unwrap(); + let h = harness(app); + assert!(h.get_by_role_and_label(Role::Slider, "Opacity").accesskit_node().is_disabled()); + + // A gradient left as the default for new art: its stop is not the row's to change. + let mut app = self::app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let mut h = harness(app); + assert!(h.get_by_role_and_label(Role::Slider, "Opacity").accesskit_node().is_disabled()); + let defaults = h.state().session.paint.fill.clone(); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(25.0))); + assert_eq!(h.state().session.paint.fill, defaults); + + // An object with a gradient fill selected in a dynamic symbol instance. + let mut app = self::app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + let id = app.session.doc().unwrap().selection.objects[0].0; + let inst = app.run("symbol.new", json!({"name": "One", "ids": [id], "type": "dynamic"})).unwrap()["id"].clone(); + app.run("symbol.instance.selectPart", json!({"id": inst, "path": []})).unwrap(); + let h = harness(app); + assert!(h.get_by_role_and_label(Role::Slider, "Opacity").accesskit_node().is_disabled()); +} + +/// `ui.colorWheel` answers every junk parameter, with and without a document, without a panic. +#[test] +fn ui_color_wheel_answers_junk_params_without_a_panic() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3; + for mut app in [app(), VectorcraftApp::new(Session::new(), Default::default())] { + for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) { + let _ = app.run("ui.colorWheel", p); + } + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d1722e8b72..17f28fe888 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -734,7 +734,7 @@ pub struct UiState { /// of an RGB field, `ui.colorPanel`, [`crate::panels::color::deserialize_rgb_percent`]). #[serde(default, deserialize_with = "crate::panels::color::deserialize_rgb_percent")] pub color_rgb_percent: bool, - /// Color Wheel panel: the wheel or the box, and the box's channel (`ui.colorWheel`, + /// Color Wheel panel: the wheel or the box, the box's channel and Show Opacity (`ui.colorWheel`, /// [`crate::panels::color_wheel::deserialize_settings`]). #[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")] pub color_wheel: crate::panels::color_wheel::Settings, diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 2ace2c7a67..2b39fb2199 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -37,7 +37,7 @@ pub use chips::{ProxyClicks, chip_button, chip_button_named, fill_stroke_proxy, pub use color::{ FieldAxis, Live, RingResponse, SliderValue, WheelResponse, channel_slider, channel_slider_named, channel_slider_stepped, channel_slider_valued, color_field, color_mesh, color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, - hsb32, hue_ring, region_texture, ring_square, segment_color, segmented_wheel, stepped_area, + hsb32, hue_ring, opacity_slider, region_texture, ring_square, segment_color, segmented_wheel, stepped_area, }; pub(crate) use color::{HEX_FIELD_CHARS, hex_text, pointer_phase}; pub use drag::{ diff --git a/crates/ui-egui/src/widgets/chips.rs b/crates/ui-egui/src/widgets/chips.rs index 1b814728a1..9af718c1a8 100644 --- a/crates/ui-egui/src/widgets/chips.rs +++ b/crates/ui-egui/src/widgets/chips.rs @@ -90,18 +90,23 @@ pub(super) fn chip_grid(g: &vectorcraft_color::Gradient, width: f32, height: f32 /// A white and light gray checkerboard filling `rect`, with cells a quarter of its shorter side /// (3 to 8 points). fn checkerboard(ui: &Ui, rect: Rect) { - let p = ui.painter(); - p.rect_filled(rect, 0.0, Color32::WHITE); let cell = (rect.width().min(rect.height()) / 4.0).clamp(3.0, 8.0); + ui.painter().extend(checkerboard_shapes(rect, cell)); +} + +/// The shapes of a white and light gray checkerboard filling `rect`, with `cell` point cells. +pub(super) fn checkerboard_shapes(rect: Rect, cell: f32) -> Vec { + let mut shapes = vec![egui::Shape::rect_filled(rect, 0.0, Color32::WHITE)]; let cols = (rect.width() / cell).ceil() as usize; let rows = (rect.height() / cell).ceil() as usize; for j in 0..rows { for i in (j % 2..cols).step_by(2) { let min = pos2(rect.left() + cell * i as f32, rect.top() + cell * j as f32); let square = Rect::from_min_size(min, Vec2::splat(cell)).intersect(rect); - p.rect_filled(square, 0.0, Color32::from_gray(204)); + shapes.push(egui::Shape::rect_filled(square, 0.0, Color32::from_gray(204))); } } + shapes } /// The colours at the `(cols + 1) x (rows + 1)` grid points (row by row) of a `width` x `height` diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index f7c1d9365b..3229c09260 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -145,6 +145,38 @@ pub fn color_slider_stepped( (picked, phase, stepped.filter(|_| picked.is_none())) } +/// [`color_slider_stepped`] for an opacity: its track shows `color` from clear at 0 to solid at 1 +/// over a checkerboard of 4 pt cells. +pub fn opacity_slider( + ui: &mut Ui, + id: impl std::hash::Hash, + name: &str, + shown: Option, + value: f32, + width: f32, + color: Color32, +) -> (Option, Live, Option) { + let id = id_with(ui.scope_id(), id); + // The checkerboard and the ramp go under the rail's thumb and border, which the rail draws. + let under = ui.painter().add(egui::Shape::Noop); + let (resp, picked, phase) = color_rail(ui, id, name, shown.clone(), value, width, &|_| Color32::TRANSPARENT); + let bar = rail_bar(resp.rect, width); + let mut shapes = super::chips::checkerboard_shapes(bar, 4.0); + let [r, g, b, _] = color.to_srgba_unmultiplied(); + let mut ramp = egui::Mesh::default(); + let clear = Color32::from_rgba_unmultiplied(r, g, b, 0); + let solid = Color32::from_rgb(r, g, b); + for (p, c) in [(bar.left_top(), clear), (bar.right_top(), solid), (bar.right_bottom(), solid), (bar.left_bottom(), clear)] { + ramp.colored_vertex(p, c); + } + ramp.add_triangle(0, 1, 2); + ramp.add_triangle(0, 2, 3); + shapes.push(egui::Shape::mesh(ramp)); + ui.painter().set(under, egui::Shape::Vec(shapes)); + let stepped = slider_keys(ui, &resp, shown); + (picked, phase, stepped.filter(|_| picked.is_none())) +} + /// A control that its caller draws and reads the pointer on (`resp`, from a click-and-drag /// [`Ui::interact`]), which screen readers get as a slider named `name` (already translated) with /// `shown`, and which takes the focus, the keys and the screen readers' actions as the rail of @@ -278,7 +310,7 @@ fn color_rail( ) -> (Response, Option, Live) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(vec2(width, 22.0), Sense::hover()); - let bar = Rect::from_min_size(pos2(rect.left() + 4.0, rect.top() + 4.0), vec2(width - 8.0, 7.0)); + let bar = rail_bar(rect, width); let resp = ui.interact(rect, id, Sense::click_and_drag()); gradient_strip(ui, bar, (bar.width() / 2.0).ceil().max(2.0) as usize, false, track); ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside); @@ -296,6 +328,11 @@ fn color_rail( (resp, picked, phase) } +/// The bar of a rail `width` wide in `rect`, above its thumb. +fn rail_bar(rect: Rect, width: f32) -> Rect { + Rect::from_min_size(pos2(rect.left() + 4.0, rect.top() + 4.0), vec2(width - 8.0, 7.0)) +} + /// The pointer of a click or drag on `resp` and its phase (dragging, or released on click/drop). pub(crate) fn pointer_phase(resp: &Response) -> Option<(Pos2, Live)> { if !(resp.dragged() || resp.clicked() || resp.drag_stopped()) { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bb13e0d5f5..b34deca9fa 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -265,9 +265,10 @@ My Themes tab lists the saved themes; every action runs a command (`colorTheme.s Color Wheel panel (`window.panel {panel: "colorWheel"}`): a hue ring around a saturation and brightness square. A pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint.setStroke` with `keepModel`, `paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected -point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?}` shows the wheel or the box (a -color field with a channel strip at its right) and picks the box's channel; it returns the settings, and `ui.inspect` -reports them as `ui.color_wheel`. +point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, opacity?}` shows the wheel or +the box (a color field with a channel strip at its right), picks the box's channel and checks or unchecks Show Opacity +(an opacity row under the wheel or the box); it returns the settings, and `ui.inspect` reports them as +`ui.color_wheel`. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ `global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`, diff --git a/docs/mcp.md b/docs/mcp.md index 12c1f38184..0db92c9e21 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -622,9 +622,13 @@ RGB fields in percent, as a double-click right of an RGB field does, and `false` and answers true when the fields show in percent. `ui.colorWheel {"view": "box", "channel": "red"}` shows the Color Wheel panel's box (a color field with the channel's strip at its right) in place of the wheel, as the panel menu's Box View and Box Channel do, and `"view": "wheel"` -shows the wheel again. Keys left out keep their values. Params that are not an object, another key or a value off -the list return an error and change nothing. The command returns `{view, channel}`, and both settings are kept with -the preferences. +shows the wheel again. `"opacity": true` checks Show Opacity, as the panel menu does: a row under the wheel or the +box with a slider and a percent field sets the opacity of the fill or stroke row (`paint.setFill {opacity}`), the +selected gradient stop or the selected freeform point (the first stop or point when none is selected), and `false` +hides the row. The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill +or stroke row it would set is on type characters or missing. Keys left out keep their values. +Params that are not an object, another key or a value off the list return an error and change nothing. The command +returns `{view, channel, opacity}`, and the settings are kept with the preferences. In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop @@ -756,7 +760,12 @@ Cmd+Alt+/ runs `appearance.addStroke` (`press_key {key: "/", mods: {cmd: true, a `item` to edit one of them; `run_command appearance.setActiveItem {"index": n}` makes that row the target of later calls that omit `item` (as clicking the row in the Appearance panel does) until the selection changes; the proxy of its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. -`inspect_document` reports it as `paint.appearanceItem`. Live effects take the same `item` to apply to one fill or +`inspect_document` reports it as `paint.appearanceItem`. `paint.setFill` and `paint.setStroke` also take `opacity` +(0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with +or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint +undone. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has +that row. It answers null with nothing selected, for an object selected in a symbol instance, and when only type +characters (which have no opacity of their own) or objects without that row are selected. Live effects take the same `item` to apply to one fill or stroke instead of the whole object: `run_command effect.apply {"effect": "path.offsetPath", "item": 0}`, and `effect.remove`, `effect.setParams` (`visible` toggles one) and `effect.duplicate` address that item's effects; `apply_effect` uses the active item. `effect.list` reports each object's item effects under `applied[].items`. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e34f814534..f6fd60781c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1503,6 +1503,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Scores and estimates are unchanged. + VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill or stroke row (`paint.setFill {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. Scores and estimates are unchanged. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). Recent Colors keeps the last 30 solid colors applied, newest first and each once, and the list stays the same when another document is opened or made active; a 31st color drops the oldest ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). The list lasts for the session. In the Color and Swatches panels the chips wrap onto further rows when the panel is too narrow for one row (`paint.recent`). Tests: `recent_colors_keep_thirty_colors_across_documents` in `crates/engine/src/tests/paintproxy.rs`, `all_thirty_recent_colors_wrap_into_a_narrow_panel` in `crates/ui-egui/src/panels/color/tests.rs`. From 83b20bc95372ccb941fc112368216ac8369de8ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:30:05 -0800 Subject: [PATCH 02/78] i18n: Danish rows for the Color Wheel opacity messages --- crates/ui-egui/src/i18n/da.tsv | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 1215adae26..3eb97b8b3f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -438,6 +438,11 @@ @msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` og `maxItems` skal være 0-{MAX_LIST}, `maxItems` mindst 1, og standardværdien skal have så mange @msg `name` must be a string `name` skal være en streng @msg `opacity` must be a number `opacity` skal være et tal +@msg `opacity` must be a number from 0 to 100 `opacity` skal være et tal fra 0 til 100 +@msg `opacity` must be true or false `opacity` skal være true eller false +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke tegn i tekst har ingen egen opacitet: tilføj en udfyldning eller kontur med Tilføj ny udfyldning eller Tilføj ny kontur i panelet Udseende +@msg an object selected in a symbol instance has no fill or stroke opacity of its own et objekt, der er markeret i en symbolforekomst, har ingen egen opacitet for udfyldning eller kontur +@msg no target has that fill or stroke to take the opacity intet mål har den udfyldning eller kontur, der kan modtage opaciteten @msg `type` must be "path" or "compound" `type` skal være "path" eller "compound" @msg `unit` must be 1-{MAX_UNIT} printable characters `unit` skal være 1-{MAX_UNIT} tegn, der kan udskrives @msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` angiver 1 til {MAX_CONDITION_VALUES} værdier for `{other}` From 401dc96ef2bcdacf7cb9a3b360d85ee7797c9b0e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:54:25 -0800 Subject: [PATCH 03/78] Color Wheel: opacity row follows the Type tool's characters and keeps the hue - paint.proxies answers no fill or stroke opacity while the Type tool has characters selected, so the Color Wheel's opacity row is gray instead of offering a value that paint.setFill {opacity} refuses. - paint.setFill and paint.setStroke with `id` paint that object while the Type tool has characters selected, as they already do with `ids`. - An opacity edit of a gradient stop or freeform point keeps the hue picked last for an achromatic color. - With a None fill, a screen reader's set value on the Brightness strip sets the fill even when the value equals the hidden number of the last color. --- crates/engine/src/cmd/paint.rs | 13 ++++-- crates/engine/src/cmd/textedit.rs | 13 ++++-- crates/engine/src/tests/paintopacity.rs | 43 +++++++++++++++++++ crates/ui-egui/src/panels/color_wheel.rs | 12 ++++++ .../src/panels/tests_color_wheel_box.rs | 16 +++++++ .../src/panels/tests_color_wheel_opacity.rs | 22 ++++++++++ crates/ui-egui/src/widgets/color.rs | 19 ++++++-- docs/mcp.md | 5 ++- 8 files changed, 131 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index a77f613d11..42b0298987 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?:\"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors; the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?:\"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors; the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -154,7 +154,7 @@ pub fn proxy_specs() -> Vec { "Fill and Stroke", [], None, - "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill (stroke) item that paint.setFill {opacity} sets, from the first selected object (or painted object in a selected group) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, and when only type characters or objects without that item are selected}", + "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill (stroke) item that paint.setFill {opacity} sets, from the first selected object (or painted object in a selected group) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Type tool has characters selected, and when only type characters or objects without that item are selected}", always, proxies ), @@ -216,13 +216,17 @@ impl Session { /// or for a gradient mesh with points picked the first picked point's. The rows the command /// would edit are read in order (a group without an active Appearance row stands for its /// contents), and the first that exists answers. `None` with nothing selected, for an object - /// selected in a symbol instance, and when only type characters or objects without that item - /// are selected. + /// selected in a symbol instance, while the Type tool has characters selected, and when only + /// type characters or objects without that item are selected. pub fn proxy_opacity(&self, stroke: bool) -> Option { let st = self.active()?; if st.selection.symbol_part.is_some() { return None; } + // The command would give the opacity to the characters, which have none of their own. + if super::textedit::selected_range(self).is_some_and(|(_, a, b)| a != b) { + return None; + } let item = self.appearance_item(); let of = |n: &Node, item: Option| -> Option { if item.is_none() && matches!(n.kind, NodeKind::Text(_)) { @@ -555,6 +559,7 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity }; // Characters selected with the Type tool take the paint, not the whole type object (#1063). if p.get("ids").is_none() + && p.get("id").is_none() && p.get("item").is_none() && let Some((id, a, b)) = super::textedit::editing_range(s)? && a != b diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index eb62962ad9..4bf97055d0 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1884,14 +1884,21 @@ enum Step { /// The Type tool's selected text while it edits (its typing session ends first: one undo step). pub(crate) fn editing_range(s: &mut Session) -> Result> { - let o = s.tool_options(); - let Some(id) = o.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) }; + let Some(range) = selected_range(s) else { return Ok(None) }; if super::edit::typing_in_progress(s) { s.set_tool_option("commitTyping", &Value::Bool(true)); s.commit_interaction()?; } + Ok(Some(range)) +} + +/// The Type tool's selected text while it edits, as [`editing_range`] reads it, with its typing +/// session left running. +pub(crate) fn selected_range(s: &Session) -> Option<(NodeId, usize, usize)> { + let o = s.tool_options(); + let id = o.get("editing").and_then(Value::as_u64).map(NodeId)?; let at = |k: &str| byte_param(&o, k).unwrap_or(0); - Ok(Some((id, at("start"), at("end")))) + Some((id, at("start"), at("end"))) } /// The frames of the story whose whole text the Type tool has selected after Select All in a diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index 3c3fa12bbe..a1e2018e83 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -182,6 +182,49 @@ fn errors_leave_the_document_and_defaults_alone() { assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); } +/// Select characters of `t` with the Type tool. +fn select_characters(s: &mut Session, t: NodeId) { + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": t.0, "anchor": 0, "caret": 2})); +} + +/// While the Type tool has characters selected, `paint.proxies` answers no opacity even when the +/// type object has a fill row of its own that the Appearance panel has active, since +/// `paint.setFill {opacity}` would give the opacity to the characters. +#[test] +fn with_characters_selected_the_proxy_answers_no_opacity() { + let mut s = session(); + let t = text(&mut s); + select(&mut s, &[t]); + s.execute("appearance.addFill", &json!({})).unwrap(); + let row = node(&s, t).appearance.items.iter().position(|it| it.is_fill()).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the type object's own fill row"); + select_characters(&mut s, t); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}"); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); +} + +/// While the Type tool has characters selected, an object named by `id` takes the opacity and the +/// paint, and the characters keep theirs. +#[test] +fn with_characters_selected_an_id_takes_the_opacity() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let t = text(&mut s); + select(&mut s, &[t]); + select_characters(&mut s, t); + let before = node(&s, t); + s.execute("paint.setFill", &json!({"id": r.0, "opacity": 40})).unwrap(); + assert!((fill_opacity(&s, r) - 0.4).abs() < 1e-6); + s.execute("paint.setStroke", &json!({"id": r.0, "color": "#ff0000", "opacity": 30})).unwrap(); + let stroke = node(&s, r).appearance.stroke().unwrap().clone(); + assert!((stroke.opacity - 0.3).abs() < 1e-6); + assert_eq!(stroke.paint, Paint::solid(Color::rgb8(255, 0, 0))); + assert_eq!(node(&s, t), before, "the characters keep their paint"); +} + /// A type object whose characters take the paint is left alone beside a rectangle that takes the /// opacity, with no error; alone, it answers the characters error. #[test] diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 6356d96666..d453aceb29 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -445,7 +445,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); if app.ui.color_wheel.opacity { let shown = color.unwrap_or(app.session.last_solid); + let owner = color.map(|c| Owner::of(app, &tgt, c)); opacity_row(app, ui, &tgt, &shown); + // An opacity edit of a gradient stop or point changes the gradient its owner holds, and the + // HSB picked last stays with the new gradient. + if let (Some(c), Some(was)) = (color, owner) + && let Some((remembered, rgb, hsb)) = pstate::>(ui.ctx(), MEMORY) + && remembered == was + { + let now = Owner::of(app, &tgt, c); + if now != was { + set_pstate(ui.ctx(), MEMORY, Some((now, rgb, hsb))); + } + } } let Some((hsb, phase)) = pick else { return }; let behind = super::alt_held(ui); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index a19d472d70..048aff00ea 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -235,6 +235,22 @@ fn with_a_none_fill_the_strip_reads_zero_and_its_actions_set_the_fill() { assert!(near(hsb(&fill(h.state())), [last[0], last[1], 0.25], 0.01), "{last:?} → {:?}", hsb(&fill(h.state()))); } +/// With None, a screen reader's set value equal to the last solid color's own number still sets +/// the fill. +#[test] +fn with_a_none_fill_a_set_value_equal_to_the_hidden_number_sets_the_fill() { + let mut app = app(json!("#ff0000"), "brightness"); + app.run("paint.setFill", json!({"none": true})).unwrap(); + let mut h = harness(app); + let last = hsb(&h.state().session.last_solid); + assert!((last[2] - 1.0).abs() < 0.01, "{last:?}"); + let (target_node, target_tree) = h.get_by_label("Brightness").accesskit_node().locate(); + let data = Some(ActionData::NumericValue(100.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + h.run_steps(1); + assert!(near(hsb(&fill(h.state())), last, 0.01), "{last:?} → {:?}", crate::panels::current_paints(h.state()).0); +} + /// `ui.colorWheel` answers every junk parameter without a panic. #[test] fn ui_color_wheel_answers_junk_params_without_a_panic() { diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index 8dbcf0f15f..b794dc3c54 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -194,6 +194,28 @@ fn without_a_selected_stop_the_first_takes_the_opacity() { assert!((o[0] - 0.3).abs() < 1e-6 && (o[1] - 1.0).abs() < 1e-6, "{o:?}"); } +/// The hue picked last for a white gradient stop stays on the ring after the row sets the stop's +/// opacity. +#[test] +fn an_opacity_edit_keeps_the_hue_picked_for_a_white_stop() { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap(); + app.select_tool("gradient"); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + let mut h = harness(app); + let ring = |h: &Harness<'static, VectorcraftApp>| h.get_by_label("Hue ring").accesskit_node().numeric_value(); + let (target_node, target_tree) = h.get_by_label("Hue ring").accesskit_node().locate(); + let data = Some(ActionData::NumericValue(120.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + h.run_steps(2); + assert_eq!(ring(&h), Some(120.0), "the ring shows the hue picked for white"); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(30.0))); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + assert!((g.gradient.stops[0].opacity - 0.3).abs() < 1e-6, "{:?}", g.gradient.stops); + assert_eq!(ring(&h), Some(120.0), "the ring keeps the hue after the opacity edit"); +} + /// A drag across the slider previews and ends as one undo step named Opacity. #[test] fn a_drag_is_one_undo_step() { diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 3229c09260..a2503626a8 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -545,8 +545,9 @@ pub fn channel_slider_valued( /// the rail of [`color_slider_stepped`] does: a click or a drag gives it the keyboard focus, and /// while it has the focus ↑ and → raise the number `shown` holds and ↓ and ← lower it. When not /// `marked`, the rail draws no arrows and screen readers read 0, as [`hue_ring`] does, while the -/// keys and actions still step from `shown`. Returns the new value from 0 to 1 that a click or a -/// drag gives, its phase, and the number in `shown`'s units that a key or an action gives. +/// keys and actions still step from `shown`, and a set value applies even when it equals `shown`'s +/// number. Returns the new value from 0 to 1 that a click or a drag gives, its phase, and the +/// number in `shown`'s units that a key or an action gives. #[allow(clippy::too_many_arguments)] pub fn channel_slider_stepped( ui: &mut Ui, @@ -558,10 +559,22 @@ pub fn channel_slider_stepped( size: Vec2, track: &dyn Fn(f32) -> Color32, ) -> (Option, Live, Option) { + use egui::accesskit::{Action, ActionData}; let id = id_with(ui.scope_id(), id); let read = if marked { shown.clone() } else { shown.as_ref().map(|s| SliderValue { value: 0.0, text: None, ..s.clone() }) }; let (resp, picked, phase) = channel_rail(ui, id, name, read, value, marked, size, track); - let stepped = slider_keys(ui, &resp, shown); + let unmarked = shown.as_ref().filter(|_| !marked && ui.is_enabled()).map(|s| s.value); + let mut stepped = slider_keys(ui, &resp, shown); + // Without a marker there is no color yet, so a set value applies even when it leaves the number + // as it was. + if stepped.is_none() + && let Some(v) = unmarked + && ui.input(|i| { + i.accesskit_action_requests(resp.id, Action::SetValue).any(|r| matches!(r.data, Some(ActionData::NumericValue(n)) if n.is_finite())) + }) + { + stepped = Some(v); + } (picked, phase, stepped.filter(|_| picked.is_none())) } diff --git a/docs/mcp.md b/docs/mcp.md index 547a9b05ff..f4be29c572 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -788,8 +788,9 @@ its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. (0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint undone. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has -that row. It answers null with nothing selected, for an object selected in a symbol instance, and when only type -characters (which have no opacity of their own) or objects without that row are selected. Live effects take the same `item` to apply to one fill or +that row. It answers null with nothing selected, for an object selected in a symbol instance, while the Type tool +has characters selected, and when only type characters (which have no opacity of their own) or objects without that +row are selected. Live effects take the same `item` to apply to one fill or stroke instead of the whole object: `run_command effect.apply {"effect": "path.offsetPath", "item": 0}`, and `effect.remove`, `effect.setParams` (`visible` toggles one) and `effect.duplicate` address that item's effects; `apply_effect` uses the active item. `effect.list` reports each object's item effects under `applied[].items`. From 436bbe504af148d014b938718c73cc33800f3ea2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 01:50:18 -0800 Subject: [PATCH 04/78] Color: Show Opacity leaves out the art of a graph design The fill and stroke opacity the Color Wheel panel shows now skips the art of a column or marker design in a graph series, which paint.setFill and paint.setStroke leave out. With only that art selected the panel shows no opacity, also when a row of the art is the Appearance panel's active item, instead of offering an edit the command refuses. --- crates/engine/src/cmd/graph/tests.rs | 21 +++++++++++++++++++++ crates/engine/src/cmd/paint.rs | 17 ++++++++++++----- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 4b81d56802..62b2fd569a 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -1443,6 +1443,27 @@ fn paint_targets_leave_a_graph_designs_copy_out() { assert_eq!(super::paint_targets(d, &[copy, art, mark]), [mark]); } +/// The fill opacity the proxies show leaves out the art of a column or marker design in a series, which +/// `paint.setFill {opacity}` leaves out too: with only that art selected there is none, also with a row of the art +/// active, and with a mark selected after it the mark's. +#[test] +fn proxy_opacity_leaves_a_graph_designs_art_out() { + let (mut s, _, _, art, mark) = design_art(); + let (mut m, _, marker_art) = marker_design_art(); + for (s, art) in [(&mut s, art), (&mut m, marker_art)] { + s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); + assert_eq!(s.proxy_opacity(false), None); + assert!(s.execute("paint.setFill", &json!({"opacity": 50})).is_err()); + let fill = top_row(s, art, true); + s.execute("appearance.setActiveItem", &json!({"index": fill})).unwrap(); + assert_eq!(s.proxy_opacity(false), None, "with the art's fill row active"); + assert!(s.execute("paint.setFill", &json!({"opacity": 50})).is_err()); + } + s.execute("paint.setFill", &json!({"ids": [mark.0], "opacity": 40})).unwrap(); + s.execute("select.set", &json!({"ids": [art.0, mark.0]})).unwrap(); + assert!((s.proxy_opacity(false).unwrap() - 0.4).abs() < 1e-6, "the mark's fill opacity"); +} + /// The art of a marker design in series 1 of a line graph: the design's copy and a path inside it. fn marker_design_art() -> (Session, NodeId, NodeId) { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 787aefa6de..ef17c5c960 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -217,7 +217,8 @@ impl Session { /// would edit are read in order (a group without an active Appearance row stands for its /// contents), and the first that exists answers. `None` with nothing selected, for an object /// selected in a symbol instance, while the Type tool has characters selected, and when only - /// type characters or objects without that item are selected. + /// type characters, objects without that item or the art of graph designs in a graph series + /// are selected. pub fn proxy_opacity(&self, stroke: bool) -> Option { let st = self.active()?; if st.selection.symbol_part.is_some() { @@ -242,16 +243,22 @@ impl Session { if stroke { n.appearance.stroke_at(item).map(|s| s.opacity) } else { n.appearance.fill_at(item).map(|f| f.opacity) } }; let subjects = st.selection.subjects(); + // The command leaves out the art of a graph design in a series, which the graph draws again + // from the design, and a series group stands for the paths directly in it + // (graph::paint_targets). + let editable = |id: &&NodeId| !super::graph::is_design_art(&st.doc, **id); // As the command picks its rows (ItemTarget::of_kind): the active item when it is a row of // this kind in the first selected object's stack, read in the selected objects' own - // stacks; else the topmost one of the painted leaves (a group's contents). - let first = subjects.first().and_then(|id| st.doc.node(*id)); + // stacks; else the topmost one of the painted leaves (a group's contents). A row of a + // graph design's art selected first stands for nothing (item_target_at). + let first = subjects.first().filter(editable).and_then(|id| st.doc.node(*id)); let active = item.filter(|i| first.and_then(|n| n.appearance.items.get(*i)).is_some_and(|it| it.is_fill() == !stroke)); if active.is_some() { - return subjects.iter().filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, active)); + let targets = super::graph::series_group_marks_where(&st.doc, subjects, |n| n.extras().series_index.is_some()); + return targets.iter().filter(editable).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, active)); } let leaves = super::leaf_targets(self, subjects).ok()?; - leaves.iter().filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None)) + leaves.iter().filter(editable).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None)) } pub(crate) fn remember_paint_now(&mut self, p: &Paint) { From 42e5553c867675089462504a8a15cb722a5e54b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 02:11:06 -0800 Subject: [PATCH 05/78] Color: an opacity alone refuses a span other than "object" paint.setFill and paint.setStroke given only `opacity` now check `span` as they do with a paint: "selection" asks for a gradient, and an unknown value is an error, instead of the opacity going through unchecked. --- crates/engine/src/cmd/paint.rs | 6 ++---- crates/engine/src/tests/paintopacity.rs | 9 +++++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index ef17c5c960..2a2cab339d 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -560,10 +560,8 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity: Option, fill: bool) -> Result { let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; let focus = switch_or(p, "focus", true, cmd)?; - let span = match &paint { - Some(paint) => spans_targets(p, paint).map_err(|e| bad(cmd, e))?, - None => false, - }; + // An opacity alone places no gradient, so `span` may only be "object" with it. + let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?; // Characters selected with the Type tool take the paint, not the whole type object (#1063). if p.get("ids").is_none() && p.get("id").is_none() diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index a1e2018e83..e733bbab1c 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -156,6 +156,15 @@ fn errors_leave_the_document_and_defaults_alone() { } let e = s.execute("paint.setFill", &json!({})).unwrap_err(); assert!(e.to_string().contains("give color, none, swatch, gradient or opacity"), "{e}"); + // An opacity alone places no gradient across the selection. + let doc = s.doc().unwrap().doc.clone(); + for (span, says) in [(json!("selection"), "give `gradient`"), (json!("all"), "span must be \"object\" or \"selection\"")] { + let e = s.execute("paint.setFill", &json!({"opacity": 40, "span": span})).unwrap_err(); + assert!(e.to_string().contains(says), "{span}: {e}"); + } + assert_eq!(*s.doc().unwrap().doc, *doc); + s.execute("paint.setFill", &json!({"opacity": 40, "span": "object"})).unwrap(); + assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6); s.execute("select.none", &json!({})).unwrap(); let doc = s.doc().unwrap().doc.clone(); for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] { From 053804b2635ee657a712617ecd7c0a878bd571f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 02:50:35 -0800 Subject: [PATCH 06/78] Color: a targeted layer shows the opacity of its editable art With a layer targeted and no Appearance row active, the Opacity readback walked the layer itself and could answer for a locked or hidden object, while paint.setFill and paint.setStroke {opacity} edit the layer's selected editable art. The readback now reads the painted leaves of the selected objects, as the command does. --- crates/engine/src/cmd/paint.rs | 5 +++-- crates/engine/src/tests/paintopacity.rs | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 2a2cab339d..3a4f7bae4e 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -249,7 +249,8 @@ impl Session { let editable = |id: &&NodeId| !super::graph::is_design_art(&st.doc, **id); // As the command picks its rows (ItemTarget::of_kind): the active item when it is a row of // this kind in the first selected object's stack, read in the selected objects' own - // stacks; else the topmost one of the painted leaves (a group's contents). A row of a + // stacks; else the topmost one of the painted leaves of the selected objects (a group's + // contents; for a targeted layer, its editable art, ItemTarget::targets). A row of a // graph design's art selected first stands for nothing (item_target_at). let first = subjects.first().filter(editable).and_then(|id| st.doc.node(*id)); let active = item.filter(|i| first.and_then(|n| n.appearance.items.get(*i)).is_some_and(|it| it.is_fill() == !stroke)); @@ -257,7 +258,7 @@ impl Session { let targets = super::graph::series_group_marks_where(&st.doc, subjects, |n| n.extras().series_index.is_some()); return targets.iter().filter(editable).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, active)); } - let leaves = super::leaf_targets(self, subjects).ok()?; + let leaves = super::leaf_targets(self, &st.selection.objects).ok()?; leaves.iter().filter(editable).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None)) } diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index e733bbab1c..c6c1b12a7b 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -108,6 +108,24 @@ fn a_group_with_its_own_fill_answers_for_its_contents() { assert!((node(&s, g).appearance.items[own].opacity() - 0.3).abs() < 1e-6, "the group's own fill keeps its opacity"); } +/// A targeted layer without an active Appearance row: `paint.proxies` answers the opacity of the +/// layer's editable art, which `paint.setFill {opacity}` sets, not that of a locked object before it. +#[test] +fn a_targeted_layer_answers_for_its_editable_art() { + let mut s = session(); + let (locked, open) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + s.execute("paint.setFill", &json!({"ids": [locked.0], "opacity": 20})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [open.0], "opacity": 80})).unwrap(); + s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 80.0); + s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + assert!((fill_opacity(&s, open) - 0.4).abs() < 1e-6); + assert!((fill_opacity(&s, locked) - 0.2).abs() < 1e-6, "the locked object keeps its opacity"); + assert_eq!(proxies(&mut s)["fillOpacity"], 40.0); +} + /// With the Appearance panel's lower fill row active, that row takes the opacity and the top fill /// keeps its own. #[test] From 79ad7d0256ccef75f60cc3853133b84a9602acff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 02:59:35 -0800 Subject: [PATCH 07/78] i18n: the French type-characters opacity message takes a no-break space before its colon --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4c852c0bee..33a8fecbcf 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6676,7 +6676,7 @@ axis Y Axis Axe Y @msg `opacity` must be a number `opacity` doit être un nombre @msg `opacity` must be a number from 0 to 100 `opacity` doit être un nombre compris entre 0 et 100 @msg `opacity` must be true or false `opacity` doit valoir true ou false -@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke les caractères du texte n’ont pas d’opacité propre : ajoutez un fond ou un contour avec Ajouter un nouveau fond ou Ajouter un nouveau contour dans le panneau Aspect +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke les caractères du texte n’ont pas d’opacité propre : ajoutez un fond ou un contour avec Ajouter un nouveau fond ou Ajouter un nouveau contour dans le panneau Aspect @msg an object selected in a symbol instance has no fill or stroke opacity of its own un objet sélectionné dans une occurrence de symbole n’a pas d’opacité de fond ou de contour propre @msg no target has that fill or stroke to take the opacity aucune cible n’a ce fond ou ce contour pour recevoir l’opacité @msg `type` must be "path" or "compound" `type` doit valoir "path" ou "compound" From 8395796a4c50e0c390d01a5361c686415412c652 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 04:28:01 -0800 Subject: [PATCH 08/78] Color: a selected compound-path member shows its compound path's opacity With a path of a compound path selected and a fill or stroke row active in the Appearance panel, paint.proxies read the opacity of the member's own row, while paint.setFill and paint.setStroke edit the compound path's. The readback now takes the targets the command edits (appearance_targets) and, in each one, the row the command resolves (ItemTarget::per_target and ItemTarget::resolve): the row equal to the active one, else the topmost row of that kind. --- crates/engine/src/cmd/paint.rs | 29 +++++++++++++++++----- crates/engine/src/tests/paintopacity.rs | 33 +++++++++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 57 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index bd886f9a4a..7f4316ac80 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -154,7 +154,7 @@ pub fn proxy_specs() -> Vec { "Fill and Stroke", [], None, - "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill (stroke) item that paint.setFill {opacity} sets, from the first selected object (or painted object in a selected group) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Type tool has characters selected, and when only type characters or objects without that item are selected}", + "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill (stroke) item that paint.setFill {opacity} sets, from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Type tool has characters selected, and when only type characters or objects without that item are selected}", always, proxies ), @@ -248,15 +248,32 @@ impl Session { // (graph::paint_targets). let editable = |id: &&NodeId| !super::graph::is_design_art(&st.doc, **id); // As the command picks its rows (ItemTarget::of_kind): the active item when it is a row of - // this kind in the first selected object's stack, read in the selected objects' own - // stacks; else the topmost one of the painted leaves of the selected objects (a group's + // this kind in the first selected object's stack, read in the stacks the command edits; + // else the topmost one of the painted leaves of the selected objects (a group's // contents; for a targeted layer, its editable art, ItemTarget::targets). A row of a // graph design's art selected first stands for nothing (item_target_at). let first = subjects.first().filter(editable).and_then(|id| st.doc.node(*id)); let active = item.filter(|i| first.and_then(|n| n.appearance.items.get(*i)).is_some_and(|it| it.is_fill() == !stroke)); - if active.is_some() { - let targets = super::graph::series_group_marks_where(&st.doc, subjects, |n| n.extras().series_index.is_some()); - return targets.iter().filter(editable).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, active)); + if let Some(index) = active { + // The objects whose own stacks the command edits (appearance_targets: a selected + // compound-path member stands for its compound, and an object inside another selected + // one is left out), with the one whose stack the row belongs to first. + // Each target reads the row the command edits there (ItemTarget::per_target and + // ItemTarget::resolve): the row equal to the active one, else its topmost of the kind. + let row = ItemTarget::Item { index, explicit: false, aligned: true }; + let mut roots = super::appearance::appearance_targets(self, &Value::Null).ok()?; + let anchor = row.anchor(self, &roots); + if let Some(head) = roots.get_mut(..=anchor) { + head.rotate_right(1); + } + let targets: Vec = super::graph::series_group_marks_where(&st.doc, &roots, |n| n.extras().series_index.is_some()) + .into_iter() + .filter(|id| editable(&id)) + .collect(); + return targets.iter().zip(row.per_target(self, &targets)).find_map(|(id, at)| { + let n = st.doc.node(*id)?; + of(n, at?.resolve(&n.appearance, !stroke, "paint.proxies").ok()?) + }); } let leaves = super::leaf_targets(self, &st.selection.objects).ok()?; leaves.iter().filter(editable).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None)) diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index c6c1b12a7b..380ab6fd6f 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -142,6 +142,39 @@ fn the_active_appearance_row_takes_the_opacity() { assert_eq!(proxies(&mut s)["fillOpacity"], 30.0); } +/// With a path of a compound path selected and its fill row active, the command edits the compound +/// path's fill, and `paint.proxies` answers that fill's opacity, not the member's own. +#[test] +fn an_active_row_of_a_compound_member_answers_for_its_compound() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [compound.0], "opacity": 40})).unwrap(); + // A fill row of the member's own, at 100%. + s.execute("appearance.addFill", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(fill_opacity(&s, a), 1.0); + select(&mut s, &[a]); + let row = node(&s, a).appearance.items.iter().position(|it| it.is_fill()).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 40.0); + s.execute("paint.setFill", &json!({"opacity": 70})).unwrap(); + assert!((fill_opacity(&s, compound) - 0.7).abs() < 1e-6); + assert_eq!(proxies(&mut s)["fillOpacity"], 70.0); + + // A fill row of the member's at an index that is not a fill in the compound path: the command + // edits the compound path's top fill, which the proxy answers. + s.execute("appearance.addFill", &json!({"ids": [a.0]})).unwrap(); + let (member, outer) = (node(&s, a).appearance, node(&s, compound).appearance); + let row = (0..member.items.len()).find(|i| member.items[*i].is_fill() && !outer.items.get(*i).is_some_and(|it| it.is_fill())).unwrap(); + select(&mut s, &[a]); + s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 70.0); + s.execute("paint.setFill", &json!({"opacity": 20})).unwrap(); + assert!((fill_opacity(&s, compound) - 0.2).abs() < 1e-6); + assert_eq!(proxies(&mut s)["fillOpacity"], 20.0); +} + /// A color and an opacity change together in one undo step, and the same call again records no /// step. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index d3d2bdcdf2..5443ba32ff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -802,7 +802,7 @@ its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. (0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint undone. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has -that row. It answers null with nothing selected, for an object selected in a symbol instance, while the Type tool +that row (a selected path of a compound path answers with its compound path's row, which the commands edit). It answers null with nothing selected, for an object selected in a symbol instance, while the Type tool has characters selected, and when only type characters (which have no opacity of their own) or objects without that row are selected. Live effects take the same `item` to apply to one fill or stroke instead of the whole object: `run_command effect.apply {"effect": "path.offsetPath", "item": 0}`, and From 596ff5c9540f633193e791e33f1cde97846968b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 21:47:43 -0800 Subject: [PATCH 09/78] Paint: an opacity alone counts only the targets that took it paint.setFill and paint.setStroke with only `opacity` reported every selected target in `objects`, including type and objects without the fill or stroke row, which the opacity leaves alone. They now count only the targets whose row or mesh points took the opacity. --- crates/engine/src/cmd/paint.rs | 14 ++++++++------ crates/engine/src/tests/paintopacity.rs | 6 ++++-- docs/mcp.md | 2 +- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 7f4316ac80..a3fec4a9e6 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -702,8 +702,8 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity // The type objects whose characters took the paint (no row targeted): only those change what a graph's labels keep // for their characters; a row edit is kept with the label's rows. let characters = std::cell::RefCell::new(Vec::new()); - // Whether a target took the opacity, and whether one would have given it to its characters. - let (took_opacity, characters_skipped) = (std::cell::Cell::new(false), std::cell::Cell::new(false)); + // The targets that took the opacity, and whether one would have given it to its characters. + let (took_opacity, characters_skipped) = (std::cell::RefCell::new(std::collections::BTreeSet::new()), std::cell::Cell::new(false)); let paint_one = |n: &mut Node, index: Option, paint: &Paint| -> Result<()> { if index.is_none() && matches!(n.kind, NodeKind::Text(_)) { characters.borrow_mut().push(n.id); @@ -779,7 +779,7 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity for i in points { if let Some(q) = m.points.get_mut(*i) { q.opacity = o; - took_opacity.set(true); + took_opacity.borrow_mut().insert(n.id); } } return; @@ -788,7 +788,7 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity if fill { n.appearance.fill_at_mut(index).map(|f| &mut f.opacity) } else { n.appearance.stroke_at_mut(index).map(|s| &mut s.opacity) }; if let Some(item) = item { *item = o; - took_opacity.set(true); + took_opacity.borrow_mut().insert(n.id); } }; // The objects counted: with a design's art, those with a row equal to the art's. @@ -811,7 +811,7 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity }, |before, d, changed| { // An opacity that no target took is an error, which also takes back the paint given with it. - if opacity.is_some() && !took_opacity.get() { + if opacity.is_some() && took_opacity.borrow().is_empty() { if characters_skipped.get() { return Err(characters_have_no_opacity(cmd)); } @@ -844,7 +844,9 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity paint_new_art(s, paint, fill); s.remember_paint(paint); } - Ok(json!({"objects": ids.iter().collect::>().len()})) + // An opacity alone counts only the targets that took it. + let objects = if paint.is_none() { took_opacity.borrow().len() } else { ids.iter().collect::>().len() }; + Ok(json!({"objects": objects})) } /// The instance whose object is selected with Direct Selection, and that object's path diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index 380ab6fd6f..2a8b753366 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -298,7 +298,8 @@ fn type_beside_other_art_is_left_alone() { }; let before = (node(&s, t), runs(&s)); select(&mut s, &[r, t]); - s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + let out = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + assert_eq!(out["objects"], 1, "only the rectangle took the opacity"); assert!((fill_opacity(&s, r) - 0.4).abs() < 1e-6); assert_eq!((node(&s, t), runs(&s)), before); select(&mut s, &[t]); @@ -348,7 +349,8 @@ fn an_opacity_no_target_takes_is_an_error() { s.execute("paint.setFill", &json!({"opacity": 70})).unwrap(); select(&mut s, &[a, b]); assert_eq!(proxies(&mut s)["fillOpacity"], 70.0, "the first selected object with a fill item answers"); - s.execute("paint.setFill", &json!({"opacity": 20})).unwrap(); + let out = s.execute("paint.setFill", &json!({"opacity": 20})).unwrap(); + assert_eq!(out["objects"], 1, "the object without a fill item is not counted"); assert!((fill_opacity(&s, b) - 0.2).abs() < 1e-6); assert!(node(&s, a).appearance.fill().is_none()); } diff --git a/docs/mcp.md b/docs/mcp.md index 986cde2002..5a3d6d54e1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -841,7 +841,7 @@ its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. `inspect_document` reports it as `paint.appearanceItem`. `paint.setFill` and `paint.setStroke` also take `opacity` (0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint -undone. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has +undone. Without a new paint, `objects` counts only the targets that took the opacity. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has that row (a selected path of a compound path answers with its compound path's row, which the commands edit). It answers null with nothing selected, for an object selected in a symbol instance, while the Type tool has characters selected, and when only type characters (which have no opacity of their own) or objects without that row are selected. Live effects take the same `item` to apply to one fill or From ed8bfd173a502f2dfe09ecce42222ca9e21dea4f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 15:31:59 -0800 Subject: [PATCH 10/78] Color Wheel: docs say a null opacity keeps the setting docs/mcp.md now says that ui.colorWheel keeps the opacity setting when the key is null, as the code and the params text already do. The opacity row uses the Tokens import that the merge of main added. --- crates/ui-egui/src/panels/color_wheel.rs | 2 +- docs/mcp.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 88c57136b4..f9a03d2614 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -305,7 +305,7 @@ fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Colo let mut edit: Option<(f32, Live)> = None; ui.add_enabled_ui(live, |ui| { ui.horizontal(|ui| { - let t = crate::theme::Tokens::get(ui.ctx()); + let t = Tokens::get(ui.ctx()); crate::icons::icon(ui, "dc-transparency", 16.0, if live { t.icon } else { t.text_disabled }).on_hover_text(tl!("Opacity")); let width = (ui.available_width() - OPACITY_FIELD - ui.spacing().item_spacing.x).max(40.0); let shown = SliderValue::field(percent, 0.0..=100.0, "%", 0); diff --git a/docs/mcp.md b/docs/mcp.md index 9353d0b6e1..a574487c89 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -687,7 +687,7 @@ shows the wheel again. `"opacity": true` checks Show Opacity, as the panel menu box with a slider and a percent field sets the opacity of the fill or stroke row (`paint.setFill {opacity}`), the selected gradient stop or the selected freeform point (the first stop or point when none is selected), and `false` hides the row. The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill -or stroke row it would set is on type characters or missing. Keys left out keep their values. +or stroke row it would set is on type characters or missing. Keys left out or null keep their values. Params that are not an object, another key or a value off the list return an error and change nothing. The command returns `{view, channel, opacity, vision}`, and the settings are kept with the preferences. `ui.colorWheel {"vision": true}` turns on the Color Wheel panel's Show Color Vision Preview, as its panel menu From 379bc18b33d74103d13f2d4773bde5da7efb84f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 17:18:58 -0800 Subject: [PATCH 11/78] Color Wheel: docs name paint.setStroke for the stroke opacity The Show Opacity row sets a stroke's opacity with paint.setStroke {opacity}, as apply_opacity sends it. The panel docs, params text, docs/mcp.md and the progress-doc line now name that command for the stroke row. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/color_wheel.rs | 4 ++-- docs/mcp.md | 4 ++-- docs/target-app-parity.md | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 3d6d868837..9e97cf4113 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1495,7 +1495,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list (opacity or vision: not true or false) are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, vision}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list (opacity or vision: not true or false) are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, vision}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fee13bfe00..e937ad8ae9 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1496,7 +1496,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list (opacity or vision: not true or false) are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, vision}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list (opacity or vision: not true or false) are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, vision}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index f9a03d2614..1247463a89 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -13,8 +13,8 @@ //! Picker's axes. //! //! The panel menu's Show Opacity adds a row under the wheel or the box that sets the opacity of -//! what the panel edits: the fill or stroke item (`paint.setFill {opacity}`), the selected -//! gradient stop or the selected freeform point (the first stop or point when none is selected, +//! what the panel edits: the fill item (`paint.setFill {opacity}`), the stroke item +//! (`paint.setStroke {opacity}`), the selected gradient stop or the selected freeform point (the first stop or point when none is selected, //! as for a color pick). The row is gray with nothing selected, for an object selected in a symbol //! instance, and when the fill or stroke item it would set is on type characters or missing. //! diff --git a/docs/mcp.md b/docs/mcp.md index a574487c89..39a80b0a0b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -684,8 +684,8 @@ and answers true when the fields show in percent. `ui.colorWheel {"view": "box", "channel": "red"}` shows the Color Wheel panel's box (a color field with the channel's strip at its right) in place of the wheel, as the panel menu's Box View and Box Channel do, and `"view": "wheel"` shows the wheel again. `"opacity": true` checks Show Opacity, as the panel menu does: a row under the wheel or the -box with a slider and a percent field sets the opacity of the fill or stroke row (`paint.setFill {opacity}`), the -selected gradient stop or the selected freeform point (the first stop or point when none is selected), and `false` +box with a slider and a percent field sets the opacity of the fill row (`paint.setFill {opacity}`), the stroke row +(`paint.setStroke {opacity}`), the selected gradient stop or the selected freeform point (the first stop or point when none is selected), and `false` hides the row. The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. Keys left out or null keep their values. Params that are not an object, another key or a value off the list return an error and change nothing. The command diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 947a9ab025..0b8d2b353f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1879,7 +1879,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Scores and estimates are unchanged. - VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill or stroke row (`paint.setFill {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. Scores and estimates are unchanged. + VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill row (`paint.setFill {opacity}`) or the stroke row (`paint.setStroke {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. Scores and estimates are unchanged. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). **Color panel spectrum mode tooltip (part of #7235):** hovering the spectrum names the displayed mode (Grayscale, RGB, HSB, CMYK, Web Safe RGB or Lab), including after Shift-clicking to switch modes and with Show Options or Hide Options. Hovering changes no paint or undo history. Spectrum rendering and vertical resizing remain open. Evidence: `spectrum_tooltip_names_its_displayed_mode` and `spectrum_tooltip_follows_shift_cycle_without_painting` in `crates/ui-egui/tests/color_working_components.rs`. Scores and estimates unchanged. From 98692d9d4828da2e430863e989a716166b8a8bb0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:32:34 -0800 Subject: [PATCH 12/78] Color Wheel: a null id keeps the paint on the selected characters paint.setFill and paint.setStroke read a null `ids` or `id` as naming no object, as the other paint commands do, so while the Type tool has characters selected the paint goes to those characters and the rest of the type keeps its paint. Before, a null `id` or `ids` recolored the whole type object. While the Live Paint Bucket is the active tool, paint.proxies answers null for fillOpacity and strokeOpacity, so the Color Wheel's opacity row is gray: a fill or stroke chosen then goes to the bucket, and an opacity has nothing to go to. The doc comment of proxy_opacity names paint.setStroke for the stroke opacity. --- crates/engine/src/cmd/paint.rs | 27 ++++++++++-------- crates/engine/src/tests/paintopacity.rs | 37 +++++++++++++++++++++++++ docs/mcp.md | 4 +-- 3 files changed, 54 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index f9f1bd5eb9..ab0bb5f57b 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -160,7 +160,7 @@ pub fn proxy_specs() -> Vec { "Fill and Stroke", [], None, - "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill item that paint.setFill {opacity} sets (the stroke item that paint.setStroke {opacity} sets), from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Type tool has characters selected, and when only type characters or objects without that item are selected}", + "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill item that paint.setFill {opacity} sets (the stroke item that paint.setStroke {opacity} sets), from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Live Paint Bucket is the active tool, while the Type tool has characters selected, and when only type characters or objects without that item are selected}", always, proxies ), @@ -234,16 +234,19 @@ impl Session { None } - /// The opacity (0..1) of the fill (or stroke) that `paint.setFill {opacity}` sets: the item's, - /// or for a gradient mesh with points picked the first picked point's. The rows the command - /// would edit are read in order (a group without an active Appearance row stands for its - /// contents), and the first that exists answers. `None` with nothing selected, for an object - /// selected in a symbol instance, while the Type tool has characters selected, and when only - /// type characters, objects without that item or the art of graph designs in a graph series - /// are selected. + /// The opacity (0..1) of the fill that `paint.setFill {opacity}` sets (or of the stroke that + /// `paint.setStroke {opacity}` sets): the item's, or for a gradient mesh with points picked the + /// first picked point's. The rows the command would edit are read in order (a group without an + /// active Appearance row stands for its contents), and the first that exists answers. `None` + /// with nothing selected, for an object selected in a symbol instance, while the Live Paint + /// Bucket is the active tool, while the Type tool has characters selected, and when only type + /// characters, objects without that item or the art of graph designs in a graph series are + /// selected. pub fn proxy_opacity(&self, stroke: bool) -> Option { let st = self.active()?; - if st.selection.symbol_part.is_some() { + // The Live Paint Bucket takes a fill or stroke chosen as the color it paints with, and the + // selection keeps its own (for_bucket). + if st.selection.symbol_part.is_some() || self.tool_id() == LIVE_PAINT_BUCKET { return None; } // The command would give the opacity to the characters, which have none of their own. @@ -638,9 +641,9 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity let focus = switch_or(p, "focus", true, cmd)?; // An opacity alone places no gradient, so `span` may only be "object" with it. let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?; - // Characters selected with the Type tool take the paint, not the whole type object (#1063). - if p.get("ids").is_none() - && p.get("id").is_none() + // Characters selected with the Type tool take the paint, not the whole type object (#1063). A + // null `ids` or `id` names no object, as `given_nodes` reads it. + if ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none() && let Some((id, a, b)) = super::textedit::editing_range(s)? && a != b diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index 2a8b753366..f9bfb00e3e 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -396,3 +396,40 @@ fn a_picked_mesh_point_takes_the_fill_opacity() { assert!(o.iter().enumerate().all(|(i, a)| i == 4 || *a == 1.0), "{o:?}"); assert_eq!(proxies(&mut s)["fillOpacity"], 30.0); } + +/// A null `id` or `ids` names no object, so while the Type tool has characters selected the paint +/// goes to those characters only, and the rest of the type keeps its paint. +#[test] +fn a_null_id_leaves_the_paint_to_the_selected_characters() { + for key in ["id", "ids"] { + let mut s = session(); + let t = text(&mut s); + select(&mut s, &[t]); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": t.0, "anchor": 0, "caret": 1})); + s.execute("paint.setFill", &json!({"color": "#ff0000", key: null})).unwrap(); + let NodeKind::Text(tx) = &node(&s, t).kind else { panic!("not type") }; + let fills: Vec = tx.runs.iter().map(|r| r.style.fill.clone()).collect(); + assert_eq!(fills.first(), Some(&Paint::solid(Color::rgb8(255, 0, 0))), "{key}: {fills:?}"); + assert!(fills.len() > 1 && fills[1..].iter().all(|f| *f != Paint::solid(Color::rgb8(255, 0, 0))), "{key}: {fills:?}"); + let e = s.execute("paint.setFill", &json!({"opacity": 40, key: null})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{key}: {e}"); + } +} + +/// While the Live Paint Bucket is the active tool, a fill or stroke chosen goes to the bucket, so +/// `paint.proxies` answers no opacity for the selection and an opacity is an error that leaves the +/// document as it was. +#[test] +fn the_live_paint_bucket_answers_no_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + assert_eq!(proxies(&mut s)["strokeOpacity"], Value::Null); + let doc = s.doc().unwrap().doc.clone(); + assert!(s.execute("paint.setFill", &json!({"opacity": 40})).is_err()); + assert_eq!(*s.doc().unwrap().doc, *doc); +} diff --git a/docs/mcp.md b/docs/mcp.md index d5be9fe47c..ec50aba777 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -862,8 +862,8 @@ its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. (0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint undone. Without a new paint, `objects` counts only the targets that took the opacity. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has -that row (a selected path of a compound path answers with its compound path's row, which the commands edit). It answers null with nothing selected, for an object selected in a symbol instance, while the Type tool -has characters selected, and when only type characters (which have no opacity of their own) or objects without that +that row (a selected path of a compound path answers with its compound path's row, which the commands edit). It answers null with nothing selected, for an object selected in a symbol instance, while the Live Paint Bucket is the +active tool, while the Type tool has characters selected, and when only type characters (which have no opacity of their own) or objects without that row are selected. Live effects take the same `item` to apply to one fill or stroke instead of the whole object: `run_command effect.apply {"effect": "path.offsetPath", "item": 0}`, and `effect.remove`, `effect.setParams` (`visible` toggles one) and `effect.duplicate` address that item's effects; From 256a1a2f478c16fa2ddd1bf7fb8b33f24fc96f9b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:52:18 -0800 Subject: [PATCH 13/78] Color Wheel: a Live Paint group answers the opacity of the parts it sets paint.setFill {opacity} sets a selected Live Paint group's faces and paint.setStroke {opacity} its edges. paint.proxies now reads fillOpacity from the faces and strokeOpacity from the edges, so the Color Wheel's opacity row shows the value the row sets. Before, strokeOpacity could answer a face's stroke. --- crates/engine/src/cmd/paint.rs | 7 +++++-- crates/engine/src/tests/paintopacity.rs | 16 ++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index ab0bb5f57b..6987c87864 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -160,7 +160,7 @@ pub fn proxy_specs() -> Vec { "Fill and Stroke", [], None, - "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill item that paint.setFill {opacity} sets (the stroke item that paint.setStroke {opacity} sets), from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Live Paint Bucket is the active tool, while the Type tool has characters selected, and when only type characters or objects without that item are selected}", + "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill item that paint.setFill {opacity} sets (the stroke item that paint.setStroke {opacity} sets), from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound, and a Live Paint group for its faces' fills and its edges' strokes) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Live Paint Bucket is the active tool, while the Type tool has characters selected, and when only type characters or objects without that item are selected}", always, proxies ), @@ -300,8 +300,11 @@ impl Session { of(n, at?.resolve(&n.appearance, !stroke, "paint.proxies").ok()?) }); } + // A Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit + // (ItemTarget::targets_for). let leaves = super::leaf_targets(self, &st.selection.objects).ok()?; - leaves.iter().filter(editable).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None)) + let skipped = live_paint_parts_skipped(&st.doc, &st.selection.objects, !stroke); + leaves.iter().filter(editable).filter(|id| !skipped.contains(*id)).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None)) } pub(crate) fn remember_paint_now(&mut self, p: &Paint) { diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index f9bfb00e3e..8c21702196 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -417,6 +417,22 @@ fn a_null_id_leaves_the_paint_to_the_selected_characters() { } } +/// A selected Live Paint group stands for its faces in a fill opacity and for its edges in a stroke +/// opacity, and `paint.proxies` answers from those same parts. +#[test] +fn a_live_paint_group_answers_from_the_parts_it_sets() { + let mut s = session(); + let id = rect(&mut s, 10.0); + s.execute("livePaint.make", &json!({"ids": [id.0]})).unwrap(); + let g = s.doc().unwrap().selection.objects[0]; + select(&mut s, &[g]); + s.execute("paint.setStroke", &json!({"opacity": 30})).unwrap(); + assert_eq!(proxies(&mut s)["strokeOpacity"], 30.0); + s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 40.0); + assert_eq!(proxies(&mut s)["strokeOpacity"], 30.0); +} + /// While the Live Paint Bucket is the active tool, a fill or stroke chosen goes to the bucket, so /// `paint.proxies` answers no opacity for the selection and an opacity is an error that leaves the /// document as it was. diff --git a/docs/mcp.md b/docs/mcp.md index ec50aba777..bc1640e431 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -862,7 +862,8 @@ its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. (0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint undone. Without a new paint, `objects` counts only the targets that took the opacity. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has -that row (a selected path of a compound path answers with its compound path's row, which the commands edit). It answers null with nothing selected, for an object selected in a symbol instance, while the Live Paint Bucket is the +that row (a selected path of a compound path answers with its compound path's row, which the commands edit, and a +selected Live Paint group answers with its faces' fills and its edges' strokes). It answers null with nothing selected, for an object selected in a symbol instance, while the Live Paint Bucket is the active tool, while the Type tool has characters selected, and when only type characters (which have no opacity of their own) or objects without that row are selected. Live effects take the same `item` to apply to one fill or stroke instead of the whole object: `run_command effect.apply {"effect": "path.offsetPath", "item": 0}`, and From f9367c4c100041c95a4a09e83fea8b834b1817df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 11:49:19 -0800 Subject: [PATCH 14/78] Pen: Quick Pen handles at a path's ends make its line or arc longer or shorter The Quick Pen tool shows a handle beyond the start and the end of the path being drawn, or, while none is, of the selected path, where that end is a straight line or a circular arc. Dragging the handle changes the length of the line or arc there, as the Quick Pen help page describes: https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html - A line keeps its other point and its direction. An arc keeps its other point, its circle and the way it turns; its sweep follows the pointer around the circle, up to 359 degrees. A drag stops where the path would reach past the canvas. - Each drag is one undo step, and Escape during the drag takes it back. The path being drawn goes on from the new end. The pieces the drag does not change stay pieces, so C and [ ] still change the last one, and a dragged last arc keeps at least 1 degree. - A click on a handle that does not drag adds a point, closes the path or starts one, as a click anywhere else does. - path.quickPenLength {id, subpath?, end?, length} sets the same length for agents and scripts (params text and docs/mcp.md). The handle's place 20 screen points beyond the end, the 359 degree limit, the 1 degree minimum, Escape during a drag, the handles on a selected path and the dragged end not snapping to Smart Guides are VectorCraft's own rules. Part of #2660 (reported by earlvanze). --- ROADMAP.md | 1 + crates/engine/src/cmd/draw2/commands.rs | 11 +- crates/engine/src/cmd/draw2/quickpen.rs | 60 +++- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests/quickpen.rs | 273 ++++++++++++++++ crates/tools/src/quickpen.rs | 300 +++++++++++++++++- crates/tools/src/quickpen/length.rs | 246 ++++++++++++++ crates/tools/src/quickpen/tests.rs | 105 ++++++ crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 26 ++ docs/target-app-parity.md | 2 + docs/ui-parity.md | 2 +- 36 files changed, 1045 insertions(+), 7 deletions(-) create mode 100644 crates/tools/src/quickpen/length.rs diff --git a/ROADMAP.md b/ROADMAP.md index ef05d5dc9a..fc44750491 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -146,6 +146,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. +- 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index e4846367b5..972c938a8f 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -1,7 +1,7 @@ use super::anchors::{convert_anchor, curvature, curvature_edit, remove_anchor, remove_anchors, reshape_segment}; use super::cut::{erase_region, erase_segments, knife, split}; use super::freehand::{blob, freehand}; -use super::quickpen::quick_pen; +use super::quickpen::{quick_pen, quick_pen_length}; use super::smooth::{join_scrub, smooth_region}; use super::{CommandSpec, cmd, has_anchors, has_doc, has_selection}; @@ -43,6 +43,15 @@ pub fn specs() -> Vec { has_doc, quick_pen ), + cmd!( + "path.quickPenLength", + "Quick Pen", + [], + None, + "{id, subpath?: index (0), end?: \"end\" (default)|\"start\", length: pt} make the line or arc at that end of the open subpath `length` long, as dragging the Quick Pen tool's length handle does: a line keeps its other point and its direction; an arc (the segments before the end that lie on one circle and turn the same way) keeps its other point, its circle and the way it turns, with a sweep of at most 359°. length runs from 0.001 to 1000000 pt for a line, and to 359° of the circle for an arc. A length the piece already has changes nothing; otherwise the path is selected, as one undo step → {id, kind: \"line\"|\"arc\", length}. An end that is neither straight nor a circular arc, a closed subpath, a locked or hidden path, a length outside the range and a result that would reach past the canvas are errors", + has_doc, + quick_pen_length + ), cmd!( "path.removeAnchor", "Delete Anchor Point", diff --git a/crates/engine/src/cmd/draw2/quickpen.rs b/crates/engine/src/cmd/draw2/quickpen.rs index 84640bc876..fc826b9b42 100644 --- a/crates/engine/src/cmd/draw2/quickpen.rs +++ b/crates/engine/src/cmd/draw2/quickpen.rs @@ -1,9 +1,12 @@ -//! The Quick Pen tool's command (`path.quickPen`): a path of straight lines and circular arcs. +//! The Quick Pen tool's commands: `path.quickPen` draws a path of straight lines and circular arcs, +//! and `path.quickPenLength` makes the line or arc at an end of a path longer or shorter. +use vectorcraft_tools::quickpen::length as qpl; use vectorcraft_tools::quickpen::{self as qp, Piece, Stroke}; use super::common::{path_kind, path_mut, point_entry, usize_opt, within_input_bound}; use super::{Color, Paint, PathData, Result, Session, SubPath, Value, add_look, bad, json, number_or, object_param, switch_or}; +use crate::cmd::f64_req; const C: &str = "path.quickPen"; /// The most pieces one request takes. @@ -94,3 +97,58 @@ pub(super) fn quick_pen(s: &mut Session, p: &Value) -> Result { })?; Ok(json!({ "id": id.0 })) } + +const L: &str = "path.quickPenLength"; + +/// `path.quickPenLength`: the line or arc at an end of an open subpath made `length` long. +pub(super) fn quick_pen_length(s: &mut Session, p: &Value) -> Result { + let Some(id) = object_param(p, "id", L)? else { return Err(bad(L, "missing `id`")) }; + let si = usize_opt(p, "subpath", L)?.unwrap_or(0); + let at_start = match p.get("end") { + None | Some(Value::Null) => false, + Some(v) => match v.as_str() { + Some("end") => false, + Some("start") => true, + _ => { + let key = "end"; + return Err(bad(L, format!("`{key}` must be one of {}", ["start", "end"].join(", ")))); + } + }, + }; + let length = f64_req(p, "length", L)?; + let d = &s.doc()?.doc; + let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(L, "`id` is not a path"))?; + if !d.is_editable(id) { + return Err(bad(L, "the path is locked or hidden")); + } + let sp = path.subpaths.get(si).ok_or_else(|| bad(L, "no such subpath"))?; + if sp.closed { + return Err(bad(L, "the subpath is closed")); + } + let piece = qpl::end_piece(sp, at_start).ok_or_else(|| bad(L, "the end is not a straight line or a circular arc"))?; + let (key, lo, hi) = ("length", qpl::MIN_LENGTH, piece.max_length()); + if !(lo..=hi).contains(&length) { + // An arc's limit, 359° of its circle, is given to the thousandth of a point, rounded down. + let hi = (hi * 1000.0).floor() / 1000.0; + return Err(bad(L, format!("`{key}` must be from {lo} to {hi}"))); + } + let out = qpl::with_length(sp, at_start, length).ok_or_else(|| bad(L, "the end is not a straight line or a circular arc"))?; + if !out.anchors.iter().all(|a| within_input_bound(a.p) && within_input_bound(a.h_in) && within_input_bound(a.h_out)) { + return Err(bad(L, "result would exceed the canvas (coordinates out of range)")); + } + let kind = match piece.shape { + qpl::EndShape::Line => "line", + qpl::EndShape::Arc { .. } => "arc", + }; + if (length - piece.length).abs() <= 1e-9 * length.max(1.0) { + return Ok(json!({ "id": id.0, "kind": kind, "length": piece.length })); + } + let top = super::super::path::compound_or_self(d, id); + s.edit("Quick Pen", |d, sel| { + let slot = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| crate::EngineError::Other("no such subpath".into()))?; + *slot = out; + sel.set([top]); + Ok(()) + })?; + Ok(json!({ "id": id.0, "kind": kind, "length": length })) +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index fa41a609c8..fd0c6791a3 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -465,6 +465,7 @@ pub(super) const ALLOWED: &[&str] = &[ "path.moveAnchor", "path.moveAnchors", "path.quickPen", + "path.quickPenLength", "path.rectCut", "path.removeAnchor", "path.removeAnchors", diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 66283183b9..7ed7371519 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -288,6 +288,279 @@ fn path_quick_pen_refuses_bad_params() { assert_eq!(paths(&s).len(), before.len()); } +/// The handle beyond the end of the path being drawn makes its last line longer, as one undo step, +/// and the next click goes on from the new end. +#[test] +fn dragging_the_end_handle_lengthens_the_last_line() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + // The handle stands 20 screen points beyond the end, along the line. + press(&mut s, &[(220.0, 100.0), (250.0, 130.0), (280.0, 140.0)]); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + click(&mut s, 260.0, 200.0); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0), pt(260.0, 200.0)], "the drawing went on"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(200.0, 100.0)); +} + +/// Dragged by its end handle, the last sharp-corner arc goes on around its circle and stays the +/// last piece, so C still flips it and `[` `]` still change its size. +#[test] +fn a_dragged_last_arc_still_flips() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + let undo = undo_steps(&s); + // The half circle over (200, 300) ends heading down, so its end handle is 20 points below. The + // handle turned a quarter around the center, to (180, 400), takes the end to (200, 400). + press(&mut s, &[(300.0, 320.0), (260.0, 400.0), (180.0, 400.0)]); + let sp = only_path(&s); + assert!(sp.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6, "three quarters around: {:?}", sp.anchors.last()); + assert_eq!(sp.anchors.len(), 4); + assert_eq!(undo_steps(&s), undo + 1); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); + key(&mut s, ToolKey::Letter('c')); + let flipped = only_path(&s); + assert_ne!(flipped, sp); + assert!(flipped.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); + assert_eq!(undo_steps(&s), undo + 2); + // `]` makes the dragged arc 15° larger: it keeps its ends and gains its own undo step. + key(&mut s, ToolKey::BracketRight); + let larger = only_path(&s); + assert_ne!(larger, flipped); + assert!(larger.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); + assert_eq!(undo_steps(&s), undo + 3); +} + +/// Dragged back past its start, the last sharp-corner arc stops at 1°. +#[test] +fn a_dragged_last_arc_keeps_at_least_one_degree() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + // The half circle about (200, 300) runs over the top from (100, 300) to (300, 300); its end + // handle is 20 points below the end. The pointer goes back around the circle from there, past + // the start of the arc. + let (c, r) = (pt(200.0, 300.0), (100.0f64 * 100.0 + 20.0 * 20.0).sqrt()); + let a0 = 20.0f64.atan2(100.0); + let mut pts = vec![(300.0, 320.0)]; + for d in [45.0f64, 90.0, 135.0, 175.0, 185.0] { + let a = a0 - d.to_radians(); + pts.push((c.x + r * a.cos(), c.y + r * a.sin())); + } + press(&mut s, &pts); + let sp = only_path(&s); + let one = 181f64.to_radians(); + let end = pt(200.0 + 100.0 * one.cos(), 300.0 + 100.0 * one.sin()); + assert!(sp.anchors.last().unwrap().p.distance(end) < 1e-6, "{:?}", sp.anchors.last()); + assert_eq!(sp.anchors.first().unwrap().p, pt(100.0, 300.0)); +} + +/// When the last arc goes on around the circle of the arc before it, its end handle still changes +/// the last arc alone, which C then still flips. +#[test] +fn the_end_handle_changes_the_last_arc_on_a_shared_circle() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "turn", "value": 90})).unwrap(); + // A quarter more around the circle about (200, 300), ending heading left. + click(&mut s, 200.0, 400.0); + let r = 100.0 * std::f64::consts::FRAC_1_SQRT_2; + let to = pt(200.0 - r, 300.0 + r); + // The handle at (180, 400) turned 45° more around the center takes the end there with it. + let (sin, cos) = std::f64::consts::FRAC_PI_4.sin_cos(); + let (hx, hy) = (-20.0, 100.0); + let pointer = (200.0 + hx * cos - hy * sin, 300.0 + hx * sin + hy * cos); + press(&mut s, &[(180.0, 400.0), (170.0, 400.0), pointer]); + let sp = only_path(&s); + assert!(sp.anchors.last().unwrap().p.distance(to) < 1e-6, "135° from (300, 300): {:?}", sp.anchors.last()); + assert!(sp.anchors.get(2).unwrap().p.distance(pt(300.0, 300.0)) < 1e-9, "the first arc stays"); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); +} + +/// Once another path is selected while one was being drawn, the selected path shows its handles. +#[test] +fn another_selected_path_shows_its_handles() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let r = s.execute("shape.line", &json!({"x1": 300, "y1": 300, "x2": 400, "y2": 300})).unwrap(); + s.execute("select.set", &json!({"ids": [r["id"]]})).unwrap(); + let handle = + |s: &mut Session| s.overlays(view()).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Handle { p, .. } if *p == pt(420.0, 300.0))); + assert!(handle(&mut s)); + assert_eq!(s.cursor(pt(420.0, 300.0), Mods::default(), view()), vectorcraft_tools::Cursor::Move); +} + +/// A selected path that is not being drawn shows its handles: the one before its start makes the +/// first arc shorter around its circle. Escape during a drag takes the drag back. +#[test] +fn the_start_handle_of_a_selected_path_shortens_its_arc() { + let mut s = session(); + let r = s + .execute("path.quickPen", &json!({"start": [100, 100], "pieces": [{"x": 200, "y": 100, "action": "sharpArc"}, {"x": 300, "y": 100}]})) + .unwrap(); + s.execute("select.set", &json!({"ids": [r["id"]]})).unwrap(); + quick_pen(&mut s); + let undo = undo_steps(&s); + let before = only_path(&s); + // The half circle leaves (100, 100) heading up, so its start handle is 20 points below. + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 120.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 70.0), v).unwrap(); + assert_ne!(only_path(&s), before, "previewed"); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 70.0), v).unwrap(); + assert_eq!(only_path(&s), before, "taken back"); + assert_eq!(undo_steps(&s), undo); + // The handle turned a quarter around the center, to (130, 50), takes the start to the top of + // the circle: the arc is a quarter from there to (200, 100). + press(&mut s, &[(100.0, 120.0), (130.0, 50.0)]); + let sp = only_path(&s); + assert!(sp.anchors.first().unwrap().p.distance(pt(150.0, 50.0)) < 1e-6, "{:?}", sp.anchors.first()); + assert_eq!(sp.anchors.len(), 3); + assert_eq!(undo_steps(&s), undo + 1); +} + +/// A click on a length handle that does not drag is an ordinary click: while drawing it adds a +/// point there, and with no path being drawn it starts a new path. +#[test] +fn a_click_on_a_handle_adds_a_point() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + click(&mut s, 220.0, 100.0); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(220.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + // After Escape the path stays selected with its handles; a click on one starts a new path. + key(&mut s, ToolKey::Escape); + assert_eq!(s.cursor(pt(240.0, 100.0), Mods::default(), view()), vectorcraft_tools::Cursor::Move); + click(&mut s, 240.0, 100.0); + assert_eq!(paths(&s).len(), 2); +} + +/// During a length drag the tool shows the handle and no preview of a next piece to where the +/// pointer was before the press. +#[test] +fn a_length_drag_shows_no_next_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Move, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 100.0), v).unwrap(); + let o = s.overlays(v); + assert!(o.iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Handle { .. }))); + assert!(!o.iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. } | vectorcraft_tools::Overlay::Measure { .. })), "{o:?}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(260.0, 100.0)); +} + +/// A length drag that would take the path past the canvas leaves it where the drag last put it, +/// and the drawing goes on from there. +#[test] +fn a_length_drag_stays_on_the_canvas() { + let mut s = session(); + quick_pen(&mut s); + let x = vectorcraft_doc::MAX_COORD - 1000.0; + click(&mut s, x, 100.0); + click(&mut s, x + 500.0, 100.0); + let undo = undo_steps(&s); + let before = only_path(&s); + // The end handle is at x + 520; a drag to x + 2000 would put the end at x + 1980, past the canvas. + press(&mut s, &[(x + 520.0, 100.0), (x + 2000.0, 100.0)]); + assert_eq!(only_path(&s), before); + assert_eq!(undo_steps(&s), undo); + press(&mut s, &[(x + 520.0, 100.0), (x + 820.0, 100.0)]); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(x + 800.0, 100.0)); + assert_eq!(undo_steps(&s), undo + 1); + click(&mut s, x + 800.0, 200.0); + assert_eq!(only_path(&s).anchors.len(), 3, "the drawing went on"); +} + +/// Dragged by the start handle while the path is being drawn, the first line changes and the last +/// sharp-corner arc stays the last piece, so C still flips it. +#[test] +fn the_start_handle_keeps_the_last_arc_a_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 300.0); + click(&mut s, 200.0, 300.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 400.0, 300.0); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); + let undo = undo_steps(&s); + // The line leaves (100, 300) heading left, seen from the start, so its handle is 20 points left. + press(&mut s, &[(80.0, 300.0), (60.0, 300.0), (50.0, 300.0)]); + let sp = only_path(&s); + assert_eq!(sp.anchors.first().unwrap().p, pt(70.0, 300.0)); + assert_eq!(undo_steps(&s), undo + 1); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view()), "the last arc is still a piece"); + key(&mut s, ToolKey::Letter('c')); + let flipped = only_path(&s); + assert_ne!(flipped, sp); + assert_eq!(flipped.anchors.first().unwrap().p, pt(70.0, 300.0)); + assert!(flipped.anchors.last().unwrap().p.distance(pt(400.0, 300.0)) < 1e-9); +} + +/// `path.quickPenLength` sets the length of a line or an arc at either end; the same length +/// changes nothing and records no undo step; bad params are refused. +#[test] +fn path_quick_pen_length_sets_an_end() { + let mut s = session(); + let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 200, "y": 0, "action": "sharpArc"}]})).unwrap(); + let id = r["id"].as_u64().unwrap(); + let r = s.execute("path.quickPenLength", &json!({"id": id, "end": "start", "length": 40})).unwrap(); + assert_eq!((r["kind"].as_str(), r["length"].as_f64()), (Some("line"), Some(40.0))); + assert_eq!(only_path(&s).anchors.first().unwrap().p, pt(60.0, 0.0)); + let undo = undo_steps(&s); + let r = s.execute("path.quickPenLength", &json!({"id": id, "length": std::f64::consts::PI * 50.0})).unwrap(); + assert_eq!(r["kind"], "arc"); + assert_eq!(undo_steps(&s), undo, "unchanged"); + s.execute("path.quickPenLength", &json!({"id": id, "length": std::f64::consts::PI * 25.0})).unwrap(); + assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(150.0, -50.0)) < 1e-9); + assert_eq!(undo_steps(&s), undo + 1); + let before = paths(&s); + let bad: [Value; 7] = [ + json!({"length": 10}), + json!({"id": id}), + json!({"id": id, "length": "10"}), + json!({"id": id, "length": 0}), + json!({"id": id, "length": 1e7, "end": "start"}), + json!({"id": id, "length": 10, "end": "middle"}), + json!({"id": id, "length": 10, "subpath": 1}), + ]; + for p in bad { + assert!(s.execute("path.quickPenLength", &p).is_err(), "{p}"); + } + let curve = s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap(); + s.execute("path.convertAnchor", &json!({"id": curve["id"], "anchor": 1, "to": "smooth", "x": 150, "y": 360})).unwrap(); + assert!(s.execute("path.quickPenLength", &json!({"id": curve["id"], "length": 10})).is_err(), "not a line or an arc"); + s.execute("path.quickPen", &json!({"id": id, "closed": true})).unwrap(); + assert!(s.execute("path.quickPenLength", &json!({"id": id, "length": 10})).is_err(), "closed"); + assert_eq!(paths(&s).len(), before.len() + 1); +} + /// With `id` and `keep`, the points after the first `keep` are replaced by the pieces. #[test] fn path_quick_pen_replaces_the_points_after_keep() { diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 140278719d..3fbe5418c5 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -11,17 +11,25 @@ //! point closes the path, a click on an end of an open path goes on drawing from it, and Escape //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. +//! +//! A handle stands beyond each end of the path being drawn, or, while none is, of the selected +//! path, where that end is a straight line or a circular arc. Dragging it makes the line or arc +//! longer or shorter, as one undo step (`path.quickPenLength`): a line keeps its direction, and +//! an arc keeps its circle. The dragged end stays on its line or circle and does not snap to Smart +//! Guides. A click on a handle that does not drag is an ordinary click: it adds a point, closes the +//! path or starts one. use std::f64::consts::{FRAC_PI_2, PI}; use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{MAX_COORD, NodeId, NodeKind}; use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; use crate::draw2::FEEDBACK; use crate::guides::{DrawSnap, Leave}; use crate::pen::{continue_from, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use length::EndPiece; /// The tool's id. pub const ID: &str = "quickPen"; @@ -34,8 +42,12 @@ pub const TURN_STEP: f64 = 15.0; /// The smallest and largest arc size (degrees). pub const MIN_TURN: f64 = 1.0; pub const MAX_TURN: f64 = 359.0; +/// The command that makes the line or arc at an end of a path longer or shorter. +pub const LENGTH_COMMAND: &str = "path.quickPenLength"; /// Screen points the pointer moves after a press before the press drags. const DRAG_PX: f64 = 3.0; +/// Screen points a length handle stands beyond the end of the path, along the way it leaves the end. +pub const LENGTH_HANDLE_PX: f64 = 20.0; /// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight /// behind, is drawn as a line: no circle runs there in the path's direction. const STRAIGHT: f64 = 1e-6; @@ -230,6 +242,36 @@ impl Drawing { fn drawn(&self) -> Option { Some(build(self.base.as_ref()?, &self.pieces, false)) } + + /// The last piece as drawn in `drawn` (the path [`Self::drawn`] builds): the points from where + /// it starts to the end of the path. + fn last_tail(&self, drawn: &SubPath) -> Option { + let (_, rest) = self.pieces.split_last()?; + let from = build(self.base.as_ref()?, rest, false).anchors.len().checked_sub(1)?; + Some(SubPath::new(drawn.anchors.get_range(from..)?, false)) + } + + /// Splits `changed`, the drawn path with its start changed, into a base and the most pieces at + /// its end that build it again point for point, so the pieces a drag did not touch stay pieces + /// (C and `[` `]` go on changing the last one). None when no piece builds it again. + fn rebase(&self, changed: &SubPath) -> Option<(SubPath, Vec)> { + let base = self.base.as_ref()?; + let m = changed.anchors.len(); + let total = build(base, &self.pieces, false).anchors.len(); + for k in 0..self.pieces.len() { + let (before, kept) = self.pieces.split_at(k); + let added = total.checked_sub(build(base, before, false).anchors.len())?; + let Some(keep) = m.checked_sub(added) else { continue }; + if keep == 0 { + continue; + } + let new_base = SubPath::new(changed.anchors.get_range(..keep)?, false); + if build(&new_base, kept, false).anchors == changed.anchors { + return Some((new_base, kept.to_vec())); + } + } + None + } } /// The press in progress: where it went down, whether it has dragged, and whether it began an undo @@ -241,18 +283,43 @@ struct Press { begun: bool, } +/// A length handle: the line or arc at one end of subpath `si` of `id`, and where its handle is. +#[derive(Clone, Copy, Debug, PartialEq)] +struct LengthHandle { + id: NodeId, + si: usize, + at_start: bool, + piece: EndPiece, + at: Point, +} + +/// A length handle being dragged: the handle as the press found it, the length the drag has set, +/// whether the press has moved far enough to drag, and whether the drag began an undo step. +#[derive(Clone, Copy, Debug, PartialEq)] +struct LengthDrag { + handle: LengthHandle, + press: Point, + length: f64, + dragged: bool, + begun: bool, + /// The last piece of the path being drawn as it was before the drag, when the handle is at the + /// end of that piece: the drag changes the piece, so C and [ ] still shape it afterwards. + last: Option, +} + pub struct QuickPenTool { action: Stroke, turn: f64, drawing: Option, press: Option, + length: Option, hover: Option, snap: DrawSnap, } impl Default for QuickPenTool { fn default() -> Self { - Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, hover: None, snap: DrawSnap::default() } + Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, length: None, hover: None, snap: DrawSnap::default() } } } @@ -262,6 +329,11 @@ fn selected_alone(cx: &ToolContext, id: NodeId) -> bool { sel == [id] || cx.doc.parent_of(id).is_some_and(|p| sel == [p] && cx.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) } +/// Whether every point and handle of `sp` lies on the canvas. +fn on_canvas(sp: &SubPath) -> bool { + sp.anchors.iter().all(|a| [a.p, a.h_in, a.h_out].iter().all(|q| q.x.abs() <= MAX_COORD && q.y.abs() <= MAX_COORD)) +} + fn point_tol(cx: &ToolContext) -> f64 { cx.tol(5.0).max(cx.point_tol()) } @@ -325,6 +397,18 @@ impl QuickPenTool { if self.drawing.is_some() && self.active(cx).is_none() { self.drawing = None; } + // A press on a length handle waits to see whether it drags; one let go without dragging is + // the click `click` makes. + if let Some(handle) = self.length_handle_at(cx, p) { + let last = self.drawn_last_piece(cx, &handle); + self.length = Some(LengthDrag { handle, press: p, length: handle.piece.length, dragged: false, begun: false, last }); + return vec![]; + } + self.click(cx, p) + } + + /// What a press away from a length handle, or a click on one, draws. + fn click(&mut self, cx: &ToolContext, p: Point) -> Vec { let tol = point_tol(cx); if let Some((id, sp)) = self.active(cx) { let (first, last) = match (sp.anchors.first(), sp.anchors.last()) { @@ -395,6 +479,112 @@ impl QuickPenTool { SubPath::new(added, false).to_bezpath_into(&mut bp); Some(bp) } + + /// The length handles: at both ends of the path being drawn, or, while none is, of each open + /// subpath of the one editable path selected, wherever the end is a line or an arc. + fn length_handles(&self, cx: &ToolContext) -> Vec { + // At the end of the path being drawn, the handle changes the last piece drawn alone, even + // where the piece before it goes on around the same circle. + let mut tail = None; + let subpaths: Vec<(NodeId, usize, &SubPath)> = if let Some((id, sp)) = self.active(cx) { + tail = self.drawing.as_ref().and_then(|dr| dr.last_tail(sp)); + self.drawing.as_ref().map(|dr| (id, dr.si, sp)).into_iter().collect() + } else if let [id] = cx.selection.objects.as_slice() + && cx.doc.is_editable(*id) + && let Some(pd) = cx.doc.node(*id).and_then(|n| n.path_data()) + { + pd.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed).map(|(si, sp)| (*id, si, sp)).collect() + } else { + vec![] + }; + let off = cx.tol(LENGTH_HANDLE_PX); + let mut out = vec![]; + for (id, si, sp) in subpaths { + for at_start in [false, true] { + let piece = match &tail { + Some(t) if !at_start => length::end_piece(t, false), + _ => length::end_piece(sp, at_start), + }; + if let Some(piece) = piece { + out.push(LengthHandle { id, si, at_start, piece, at: piece.end + piece.out * off }); + } + } + } + out + } + + /// The length handle under `p`, the nearest when several are. + fn length_handle_at(&self, cx: &ToolContext, p: Point) -> Option { + let tol = point_tol(cx); + self.length_handles(cx).into_iter().filter(|h| h.at.distance(p) <= tol).min_by(|a, b| a.at.distance(p).total_cmp(&b.at.distance(p))) + } + + /// The last piece of the path being drawn, when `handle` is at its end and the piece is the + /// line or arc there. + fn drawn_last_piece(&self, cx: &ToolContext, handle: &LengthHandle) -> Option { + let (id, _) = self.active(cx)?; + let dr = self.drawing.as_ref()?; + if handle.at_start || id != handle.id || dr.si != handle.si { + return None; + } + let (last, rest) = dr.pieces.split_last()?; + let from = build(dr.base.as_ref()?, rest, false).anchors.last()?.p; + let same = match handle.piece.shape { + length::EndShape::Line => last.stroke == Stroke::Line, + length::EndShape::Arc { .. } => last.stroke != Stroke::Line, + }; + (same && from.distance(handle.piece.fixed) <= 1e-9).then_some(*last) + } + + /// Puts back the last piece a length drag changed, when the drag is taken back. + fn restore_last_piece(&mut self, drag: &LengthDrag) { + if let (Some(last), Some(l)) = (drag.last, self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut())) { + *l = last; + } + } + + /// `path.quickPenLength`'s params for the length drag. + fn length_params(drag: &LengthDrag) -> Value { + let h = &drag.handle; + json!({"id": h.id.0, "subpath": h.si, "end": if h.at_start { "start" } else { "end" }, "length": drag.length}) + } + + /// A length drag let go: once it changed the path being drawn, the drawing goes on from the + /// changed path, which `path.quickPenLength` made from the same points. A press on a handle let + /// go without dragging is a click there. + fn end_length_drag(&mut self, cx: &ToolContext) -> Vec { + let Some(drag) = self.length.take() else { return vec![] }; + if !drag.dragged { + let mut out = self.click(cx, drag.press); + if self.press.take().is_some_and(|pr| pr.begun) { + out.push(Action::Commit); + } + self.snap.clear(); + return out; + } + if !drag.begun { + return vec![]; + } + // The command leaves a piece that already has the length unchanged; a drag that drew the + // last piece again has already changed the drawing. + let changed = (drag.length - drag.handle.piece.length).abs() > 1e-9 * drag.length.max(1.0); + if changed + && drag.last.is_none() + && let Some(dr) = self.drawing.as_mut() + && dr.id == Some(drag.handle.id) + && dr.si == drag.handle.si + && let Some(drawn) = dr.drawn() + { + match length::with_length(&drawn, drag.handle.at_start, drag.length) { + Some(changed) => { + let (base, pieces) = dr.rebase(&changed).unwrap_or((changed, vec![])); + (dr.base, dr.pieces) = (Some(base), pieces); + } + None => self.drawing = None, + } + } + vec![Action::Commit] + } } impl Tool for QuickPenTool { @@ -403,7 +593,7 @@ impl Tool for QuickPenTool { } fn busy(&self) -> bool { - self.press.is_some() + self.press.is_some() || self.length.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { @@ -415,11 +605,70 @@ impl Tool for QuickPenTool { vec![] } PointerKind::Down => { - if self.press.is_some() { + if self.press.is_some() || self.length.is_some() { return vec![]; } self.press_down(cx, p) } + PointerKind::Drag if self.length.is_some() => { + let Some(mut drag) = self.length else { return vec![] }; + if !drag.dragged && p.distance(drag.press) < cx.tol(DRAG_PX) { + return vec![]; + } + drag.dragged = true; + self.length = Some(drag); + // The end follows the pointer, as far behind it as the press was. + let piece = drag.handle.piece; + let mut length = piece.length_dragged(drag.press, p, drag.length); + // The last piece drawn goes on being a piece of the drawing, drawn again to its new + // end; an arc piece keeps an arc size of at least 1°. + let mut redrawn = None; + let before = self.drawing.as_ref().and_then(|dr| { + let mut dr = dr.clone(); + *dr.pieces.last_mut()? = drag.last?; + dr.last_tail(&dr.drawn()?) + }); + let changed = if let (Some(last), Some(drawn)) = (drag.last, before) { + if let length::EndShape::Arc { radius, .. } = piece.shape { + length = length.max(MIN_TURN.to_radians() * radius); + } + let changed = length::with_length(&drawn, false, length); + redrawn = changed.as_ref().and_then(|sp| sp.anchors.last().map(|a| a.p)).map(|to| { + let turn = match piece.shape { + length::EndShape::Arc { radius, .. } => (length / radius).to_degrees().clamp(MIN_TURN, MAX_TURN), + length::EndShape::Line => last.turn, + }; + Piece { to, turn, ..last } + }); + changed + } else { + let h = &drag.handle; + let sp = cx.doc.node(h.id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(h.si)); + sp.and_then(|sp| length::with_length(sp, h.at_start, length)) + }; + // A length that would take the path past the canvas is not taken: the end stays + // where the drag last put it. + if !changed.is_some_and(|sp| on_canvas(&sp)) { + return vec![]; + } + let mut out = vec![]; + if !drag.begun { + drag.begun = true; + out.push(Action::Begin("Quick Pen".into())); + } + drag.length = length; + self.length = Some(drag); + match redrawn { + Some(pc) => { + if let Some(l) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { + *l = pc; + } + out.push(Action::Preview(COMMAND.into(), self.params(false))); + } + None => out.push(Action::Preview(LENGTH_COMMAND.into(), Self::length_params(&drag))), + } + out + } PointerKind::Drag => { let Some(mut pr) = self.press else { return vec![] }; if !pr.dragged && p.distance(pr.at) < cx.tol(DRAG_PX) { @@ -440,6 +689,9 @@ impl Tool for QuickPenTool { } PointerKind::Up => { self.snap.clear(); + if self.length.is_some() { + return self.end_length_drag(cx); + } match self.press.take() { Some(pr) if pr.begun => vec![Action::Commit], _ => vec![], @@ -476,6 +728,9 @@ impl Tool for QuickPenTool { /// A dropped press does not end the path being drawn: the piece it added goes. fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + if let Some(drag) = self.length.take() { + self.restore_last_piece(&drag); + } if self.press.take().is_some_and(|pr| pr.begun) && let Some(dr) = self.drawing.as_mut() { @@ -487,6 +742,16 @@ impl Tool for QuickPenTool { fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { match key { + // Escape during a length drag takes the drag back and leaves the path being drawn; Enter + // does nothing until the drag ends. + ToolKey::Escape if self.length.is_some() => match self.length.take() { + Some(drag) if drag.begun => { + self.restore_last_piece(&drag); + vec![Action::Cancel] + } + _ => vec![], + }, + ToolKey::Enter if self.length.is_some() => vec![], ToolKey::Escape | ToolKey::Enter => self.end(), ToolKey::Letter('c') => { if self.last_sharp_arc(cx).is_none() { @@ -532,6 +797,9 @@ impl Tool for QuickPenTool { fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.drawing = None; self.snap.clear(); + if self.length.take().is_some_and(|drag| drag.begun) { + return vec![Action::Commit]; + } match self.press.take() { Some(pr) if pr.begun => vec![Action::Commit], _ => vec![], @@ -551,8 +819,27 @@ impl Tool for QuickPenTool { fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = self.snap.guides().to_vec(); + // The length handles: a line from each end to a handle circle beyond it; during a drag, the + // one being dragged, where the changed end is. + let handles: Vec<(Point, Point)> = match &self.length { + Some(drag) => { + let h = &drag.handle; + let sp = cx.doc.node(h.id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(h.si)); + let piece = sp.and_then(|sp| length::end_piece(sp, h.at_start)); + piece.map(|pc| (pc.end, pc.end + pc.out * cx.tol(LENGTH_HANDLE_PX))).into_iter().collect() + } + None if self.press.is_none() => self.length_handles(cx).iter().map(|h| (h.piece.end, h.at)).collect(), + None => vec![], + }; + for &(a, b) in &handles { + o.push(Overlay::Line { a, b, color: FEEDBACK, dashed: false }); + o.push(Overlay::Handle { p: b, color: FEEDBACK }); + } let Some((id, sp)) = self.active(cx) else { return o }; + let on_handle = self.hover.is_some_and(|h| handles.iter().any(|&(_, at)| at.distance(h) <= point_tol(cx))); if self.press.is_none() + && self.length.is_none() + && !on_handle && let Some(h) = self.hover { if cx.pen_rubber_band @@ -576,6 +863,9 @@ impl Tool for QuickPenTool { fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor { let tol = point_tol(cx); + if self.length.is_some() || self.length_handle_at(cx, p).is_some() { + return Cursor::Move; + } if let Some((_, sp)) = self.active(cx) { let close = sp.anchors.len() >= 2 && sp.anchors.first().is_some_and(|f| f.p.distance(p) <= tol); return if close { Cursor::PenClose } else { Cursor::PenDrawing }; @@ -612,5 +902,7 @@ impl Tool for QuickPenTool { } } +pub mod length; + #[cfg(test)] mod tests; diff --git a/crates/tools/src/quickpen/length.rs b/crates/tools/src/quickpen/length.rs new file mode 100644 index 0000000000..a32751d120 --- /dev/null +++ b/crates/tools/src/quickpen/length.rs @@ -0,0 +1,246 @@ +//! The line or arc at an end of an open path, and that line or arc made longer or shorter: what the +//! Quick Pen's length handles drag and `path.quickPenLength` sets. +//! +//! The piece at an end is the path's last segment when it is straight, or the run of segments +//! before the end that lie on one circle and turn the same way (an arc drawn as several cubic +//! segments of at most 90° each). A line keeps its other point and its direction; an arc keeps its +//! other point, its circle and the way it turns, and its sweep grows or shrinks. + +use std::f64::consts::{FRAC_PI_2, PI}; + +use vectorcraft_geom::{Anchor, Point, SubPath, Vec2}; + +use super::{MAX_TURN, rot, unit}; + +/// The shortest length a line or arc can be set to (points). +pub const MIN_LENGTH: f64 = 0.001; +/// The longest a line can be set to (points). +pub const MAX_LINE_LENGTH: f64 = 1e6; +/// How close, relative to the radius, the points and handles of a segment must be to a circular +/// arc's for the segment to count as one. +const ARC_TOL: f64 = 1e-6; +/// How far, relative to the segment's length, a straight segment's handles may lie off its line. +const LINE_TOL: f64 = 1e-9; + +/// What the piece at an end is. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum EndShape { + Line, + /// An arc around `center` of `radius`, turning through `sweep` radians from the piece's other + /// point to the end (positive as [`rot`] turns). + Arc { + center: Point, + radius: f64, + sweep: f64, + }, +} + +/// The line or arc at one end of an open subpath. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct EndPiece { + pub shape: EndShape, + /// The point the piece leaves from, which stays where it is. + pub fixed: Point, + /// The end of the path. + pub end: Point, + /// The direction the path leaves the end in, away from the rest of the path. + pub out: Vec2, + /// The piece's length along the line or the arc. + pub length: f64, +} + +impl EndPiece { + /// The longest length the piece can be set to: for an arc, a sweep of 359°. + pub fn max_length(&self) -> f64 { + match self.shape { + EndShape::Line => MAX_LINE_LENGTH, + EndShape::Arc { radius, .. } => MAX_TURN.to_radians() * radius, + } + } + + /// The length the piece takes when its end is dragged to `p`: for a line, how far along its + /// direction `p` lies; for an arc, the arc to the angle `p` lies at around its center, taken + /// nearest to `near` (the length before), so a drag goes on past a full half turn. Kept within + /// [`MIN_LENGTH`] and [`Self::max_length`]. + pub fn length_toward(&self, p: Point, near: f64) -> f64 { + let l = match self.shape { + EndShape::Line => { + let Some(u) = unit(self.end - self.fixed) else { return self.length }; + u.dot(p - self.fixed) + } + EndShape::Arc { center, radius, sweep } => { + let (a, b) = (self.fixed - center, p - center); + if b.hypot() <= 1e-12 || radius <= 0.0 { + return near; + } + // The angle from the fixed point to `p`, in the way the arc turns, 0 to 2π. + let phi = a.cross(b).atan2(a.dot(b)) * sweep.signum(); + let phi = if phi < 0.0 { phi + 2.0 * PI } else { phi }; + let at = near / radius; + let turns = ((at - phi) / (2.0 * PI)).round(); + (phi + turns * 2.0 * PI) * radius + } + }; + l.clamp(MIN_LENGTH, self.max_length()) + } + + /// The length the piece takes when its handle, pressed at `press`, is dragged to `p`: the end + /// moves with the pointer and stays where it was relative to it. On a line the end keeps the + /// offset the press had from it; on an arc the offset turns with the pointer around the center, + /// so the end stays the same angle behind the pointer at any radius and zoom. + pub fn length_dragged(&self, press: Point, p: Point, near: f64) -> f64 { + let to = match self.shape { + EndShape::Line => p - (press - self.end), + EndShape::Arc { center, .. } => { + let (a, b) = (press - center, self.end - center); + center + rot(p - center, a.cross(b).atan2(a.dot(b))) + } + }; + self.length_toward(to, near) + } +} + +/// `sp`, or a copy reversed when `at_start`, so the end in question is the last point. +fn oriented(sp: &SubPath, at_start: bool) -> SubPath { + let mut o = sp.clone(); + if at_start { + o.reverse(); + } + o +} + +/// The anchor `i` places from the end in question of `sp` (0 is that end), as it would be in `sp` +/// reversed when `at_start`, read without copying the subpath. +fn from_end(sp: &SubPath, at_start: bool, i: usize) -> Option { + if at_start { sp.anchors.get(i).map(Anchor::reversed) } else { sp.anchors.get(sp.anchors.len().checked_sub(i + 1)?).copied() } +} + +/// Does the cubic from `a` to `b` run straight along its chord? +fn straight(a: &Anchor, b: &Anchor) -> bool { + let c = b.p - a.p; + let l = c.hypot(); + if l <= 1e-9 || !l.is_finite() { + return false; + } + let u = c / l; + let (h1, h2) = (a.h_out - a.p, b.p - b.h_in); + let along = |h: Vec2| u.cross(h).abs() <= LINE_TOL * l && (-LINE_TOL * l..=l * (1.0 + LINE_TOL)).contains(&u.dot(h)); + along(h1) && along(h2) +} + +/// The circle and signed turn of the cubic from `a` to `b` when it is a circular arc as the Quick +/// Pen draws one (handles along the tangents, each 4/3·tan(turn/4) of the radius long). +fn arc_of(a: &Anchor, b: &Anchor) -> Option<(Point, f64, f64)> { + let (d0, d1) = (a.h_out - a.p, b.p - b.h_in); + let (t0, t1) = (unit(d0)?, unit(d1)?); + let turn = t0.cross(t1).atan2(t0.dot(t1)); + if turn.abs() <= 1e-9 || turn.abs() > FRAC_PI_2 + 1e-6 { + return None; + } + let chord = (b.p - a.p).hypot(); + let r = chord / (2.0 * (turn.abs() / 2.0).sin()); + // An arc whose 359° is shorter than the shortest length has no length to set. + if !r.is_finite() || MAX_TURN.to_radians() * r < MIN_LENGTH { + return None; + } + let center = a.p + rot(t0, FRAC_PI_2 * turn.signum()) * r; + let k = 4.0 / 3.0 * (turn.abs() / 4.0).tan() * r; + let tol = ARC_TOL * r.max(1.0); + // The end lies where the turn takes the start around the circle, not only at the right distance. + let on = + (center + rot(a.p - center, turn)).distance(b.p) <= tol && (d0.hypot() - k).abs() <= tol * 100.0 && (d1.hypot() - k).abs() <= tol * 100.0; + on.then_some((center, r, turn)) +} + +/// The line or arc at the end (`at_start`: the start) of the open subpath `sp`, or none for a +/// closed subpath, one of fewer than two points, or an end whose last segment is neither straight +/// nor a circular arc. +pub fn end_piece(sp: &SubPath, at_start: bool) -> Option { + if sp.closed { + return None; + } + last_piece(sp, at_start).map(|(piece, _)| piece) +} + +/// The line or arc that ends at the end (`at_start`: the start) of `sp`, with how many points back +/// from that end the point it leaves from is. It reads only the points of the piece. +fn last_piece(sp: &SubPath, at_start: bool) -> Option<(EndPiece, usize)> { + let at = |i: usize| from_end(sp, at_start, i); + let last = at(0)?; + let prev = at(1)?; + if straight(&prev, &last) { + let out = unit(last.p - prev.p)?; + return Some((EndPiece { shape: EndShape::Line, fixed: prev.p, end: last.p, out, length: prev.p.distance(last.p) }, 1)); + } + let (center, radius, mut sweep) = arc_of(&prev, &last)?; + let mut back = 1; + while let (Some(a), Some(b)) = (at(back + 1), at(back)) { + let Some((c, r, t)) = arc_of(&a, &b) else { break }; + let tol = ARC_TOL * radius.max(1.0); + if c.distance(center) > tol || (r - radius).abs() > tol || t.signum() != sweep.signum() || (sweep + t).abs() >= 2.0 * PI - 1e-9 { + break; + } + sweep += t; + back += 1; + } + let fixed = at(back)?.p; + let out = unit(last.p - last.h_in)?; + Some((EndPiece { shape: EndShape::Arc { center, radius, sweep }, fixed, end: last.p, out, length: sweep.abs() * radius }, back)) +} + +/// `sp` with the line or arc at the end (`at_start`: the start) made `length` long, or none when +/// that end is not a line or an arc ([`end_piece`]) or `length` is outside [`MIN_LENGTH`] to the +/// piece's [`EndPiece::max_length`]. A line keeps its other point and its direction, and its handles +/// scale with it. An arc keeps its other point, its circle and the way it turns, drawn again as +/// segments of at most 90° each; the point it leaves from keeps its kind and incoming handle. +pub fn with_length(sp: &SubPath, at_start: bool, length: f64) -> Option { + if sp.closed { + return None; + } + let (piece, back) = last_piece(sp, at_start)?; + if !(MIN_LENGTH..=piece.max_length()).contains(&length) { + return None; + } + let mut o = oriented(sp, at_start); + let n = o.anchors.len(); + let from = n.checked_sub(back + 1)?; + let last = *o.anchors.get(n - 1)?; + match piece.shape { + EndShape::Line => { + let ratio = length / piece.length; + let to = piece.fixed + piece.out * length; + let prev = o.anchors.get_mut(n - 2)?; + prev.h_out = prev.p + (prev.h_out - prev.p) * ratio; + let end = o.anchors.get_mut(n - 1)?; + *end = Anchor { p: to, h_in: to + (last.h_in - last.p) * ratio, h_out: to + (last.h_out - last.p), kind: last.kind }; + } + EndShape::Arc { center, radius, sweep } => { + let s = length / radius * sweep.signum(); + let start = *o.anchors.get(from)?; + let t0 = unit(start.h_out - start.p)?; + let segs = ((s.abs() / FRAC_PI_2) - 1e-9).ceil().max(1.0) as usize; + let step = s / segs as f64; + let k = 4.0 / 3.0 * (step.abs() / 4.0).tan() * radius; + o.anchors.truncate(from + 1); + if let Some(a) = o.anchors.last_mut() { + a.h_out = a.p + t0 * k; + } + let r0 = start.p - center; + for i in 1..=segs { + let turned = step * i as f64; + let q = center + rot(r0, turned); + let t = rot(t0, turned); + let mut an = Anchor::with_handles(q, q - t * k, q + t * k); + if i == segs { + an.h_out = q + rot(last.h_out - last.p, s - sweep); + an.kind = last.kind; + } + o.anchors.push(an); + } + } + } + if at_start { + o.reverse(); + } + Some(o) +} diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index f5ab9986d1..b43319860d 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -212,3 +212,108 @@ fn the_rubber_band_is_the_next_piece() { } } } + +/// A straight end is a line: at the end it keeps its other point and direction, at the start it +/// keeps the end; the points between stay. +#[test] +fn a_line_end_takes_a_new_length_along_its_direction() { + let sp = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line), piece(100.0, 50.0, Stroke::Line)], false); + let end = length::end_piece(&sp, false).unwrap(); + assert_eq!(end.shape, length::EndShape::Line); + assert_eq!((end.fixed, end.end, end.length), (pt(100.0, 0.0), pt(100.0, 50.0), 50.0)); + assert!((end.out - Vec2::new(0.0, 1.0)).hypot() < 1e-12); + let longer = length::with_length(&sp, false, 80.0).unwrap(); + let pts: Vec = longer.anchors.iter().map(|a| a.p).collect(); + assert_eq!(pts, [pt(0.0, 0.0), pt(100.0, 0.0), pt(100.0, 80.0)]); + let shorter = length::with_length(&sp, true, 40.0).unwrap(); + let pts: Vec = shorter.anchors.iter().map(|a| a.p).collect(); + assert_eq!(pts, [pt(60.0, 0.0), pt(100.0, 0.0), pt(100.0, 50.0)]); + assert_eq!(length::with_length(&sp, false, 0.0), None, "too short"); + assert_eq!(length::with_length(&sp, false, length::MAX_LINE_LENGTH * 2.0), None, "too long"); + // Dragged, the length is how far along the line the pointer is, at least the shortest. + assert_eq!(end.length_toward(pt(130.0, 70.0), 50.0), 70.0); + assert_eq!(end.length_toward(pt(100.0, -30.0), 50.0), length::MIN_LENGTH); +} + +/// A half circle drawn as two quarter segments is one arc: a longer one goes around the same circle +/// from the same start, in three segments for 270°, and a shorter one is one segment. +#[test] +fn an_arc_end_keeps_its_circle() { + let sp = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line), piece(200.0, 0.0, Stroke::SharpArc)], false); + let end = length::end_piece(&sp, false).unwrap(); + let length::EndShape::Arc { center, radius, sweep } = end.shape else { panic!("an arc: {end:?}") }; + assert!(center.distance(pt(150.0, 0.0)) < 1e-9 && (radius - 50.0).abs() < 1e-9); + assert!((sweep.abs() - PI).abs() < 1e-9); + assert_eq!(end.fixed, pt(100.0, 0.0), "the arc starts where the line ends"); + let three_quarters = length::with_length(&sp, false, 1.5 * PI * 50.0).unwrap(); + assert_eq!(three_quarters.anchors.len(), 5); + assert!(on_circle(&three_quarters, 1, pt(150.0, 0.0), 50.0)); + assert!(three_quarters.anchors.last().unwrap().p.distance(pt(150.0, 50.0)) < 1e-9, "a quarter more, below the center"); + assert_eq!(three_quarters.anchors.get(1).unwrap().p, pt(100.0, 0.0)); + let quarter = length::with_length(&sp, false, 0.5 * PI * 50.0).unwrap(); + assert_eq!(quarter.anchors.len(), 3); + assert!(quarter.anchors.last().unwrap().p.distance(pt(150.0, -50.0)) < 1e-9); + // Set back to its own length, the arc is the same. + let same = length::with_length(&sp, false, end.length).unwrap(); + assert!(same.anchors.iter().zip(sp.anchors.iter()).all(|(a, b)| a.p.distance(b.p) < 1e-9 && a.h_in.distance(b.h_in) < 1e-9)); + assert_eq!(length::with_length(&sp, false, 360.0_f64.to_radians() * 50.0), None, "past 359°"); + // 359° is the longest: set to it, the arc ends 1° short of where it starts. + let max = end.max_length(); + assert!((max - 359f64.to_radians() * 50.0).abs() < 1e-9); + let longest = length::with_length(&sp, false, max).unwrap(); + assert!(on_circle(&longest, 1, pt(150.0, 0.0), 50.0)); + let short_of_start = pt(150.0, 0.0) + rot(pt(100.0, 0.0) - pt(150.0, 0.0), 359f64.to_radians() * sweep.signum()); + assert!(longest.anchors.last().unwrap().p.distance(short_of_start) < 1e-6, "{:?}", longest.anchors.last()); + // Dragged around past the start of the half circle, the arc grows on instead of starting again. + let near = 1.5 * PI * 50.0; + let l = end.length_toward(pt(150.0, 80.0), near); + assert!((l - near).abs() < 1e-9, "{l}"); + // Dragged on past 359°, just past its start (above it, since the half circle bulges up), the arc + // stops there. + assert_eq!(end.length_toward(pt(100.0, -1.0), max - 0.01), max); +} + +/// On a small arc, a handle dragged a quarter turn around the circle takes the end a quarter turn +/// around too: the offset of the handle from the end turns with the pointer. +#[test] +fn a_small_arc_end_follows_its_handle_around_the_circle() { + let sp = build(&start(pt(0.0, 0.0)), &[piece(10.0, 0.0, Stroke::SharpArc)], false); + let end = length::end_piece(&sp, false).unwrap(); + let length::EndShape::Arc { center, radius, sweep } = end.shape else { panic!("an arc: {end:?}") }; + assert!((radius - 5.0).abs() < 1e-9); + let press = end.end + end.out * 20.0; + let quarter = end.length + FRAC_PI_2 * radius; + let turned = |p: Point, a: f64| center + rot(p - center, a); + let l = end.length_dragged(press, turned(press, FRAC_PI_2 * sweep.signum()), end.length); + assert!((l - quarter).abs() < 1e-9, "{l} against {quarter}"); + // A handle pressed where it stands and not moved leaves the length as it is. + assert!((end.length_dragged(press, press, end.length) - end.length).abs() < 1e-9); +} + +/// An end that is neither straight nor circular has no length to set, and neither does a closed path. +#[test] +fn other_ends_have_no_piece() { + let mut sp = start(pt(0.0, 0.0)); + sp.anchors.push(Anchor::with_handles(pt(100.0, 0.0), pt(90.0, 40.0), pt(100.0, 0.0))); + if let Some(a) = sp.anchors.first_mut() { + a.h_out = pt(10.0, 5.0); + } + assert_eq!(length::end_piece(&sp, false), None); + assert_eq!(length::with_length(&sp, false, 10.0), None); + // A cubic with a quarter circle's handles whose end is on that circle, but not a quarter turn + // around it, is not an arc. + let k = 4.0 / 3.0 * (FRAC_PI_2 / 4.0).tan() * 100.0; + let mut off = start(pt(0.0, 0.0)); + off.anchors.push(Anchor::with_handles(pt(-100.0, 100.0), pt(-100.0, 100.0 - k), pt(-100.0, 100.0))); + if let Some(a) = off.anchors.first_mut() { + a.h_out = pt(k, 0.0); + } + assert_eq!(length::end_piece(&off, false), None); + // An arc too small to be 0.001 pt long even at 359° has no length to set either. + let tiny = build(&start(pt(0.0, 0.0)), &[piece(0.0001, 0.0, Stroke::SharpArc)], false); + assert_eq!(tiny.anchors.len(), 3); + assert_eq!(length::end_piece(&tiny, false), None); + let mut closed = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line), piece(100.0, 100.0, Stroke::Line)], false); + closed.closed = true; + assert_eq!(length::end_piece(&closed, false), None); +} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 599988d3fc..aa8f774c35 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6944,6 +6944,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` ha de ser una llista d’un màxim de 10000 trams @msg give either `start` for a new path or `id`, not both indica `start` per a un traçat nou o bé `id`, però no tots dos @msg `subpath` and `keep` need `id` `subpath` i `keep` necessiten `id` +@msg the end is not a straight line or a circular arc l’extrem no és ni una línia recta ni un arc de circumferència @msg no such user library no existeix aquesta biblioteca d’usuari @msg no such view no existeix aquesta vista @msg no such width point no existeix aquest punt d’amplada diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index c0c143f893..4bd1c8f241 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5808,6 +5808,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` musí být seznam nejvýše 10000 dílů @msg give either `start` for a new path or `id`, not both zadejte buď `start` pro novou cestu, nebo `id`, ne obojí @msg `subpath` and `keep` need `id` `subpath` a `keep` vyžadují `id` +@msg the end is not a straight line or a circular arc konec není rovná čára ani kruhový oblouk @msg no such user library taková uživatelská knihovna neexistuje @msg no such view takové zobrazení neexistuje @msg no such width point takový bod šířky neexistuje diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 7e22ccf3d7..1f765157d7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7989,6 +7989,7 @@ imageTrace Outline Kontur @msg `pieces` must be a list of at most 10000 pieces `pieces` skal være en liste med højst 10000 stykker @msg give either `start` for a new path or `id`, not both angiv enten `start` til en ny sti eller `id`, ikke begge @msg `subpath` and `keep` need `id` `subpath` og `keep` kræver `id` +@msg the end is not a straight line or a circular arc enden er hverken en ret linje eller en cirkelbue @msg no such user library intet sådant brugerbibliotek @msg no such view ingen sådan visning @msg no such width point intet sådant breddepunkt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2060bc330b..22b1082113 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5385,6 +5385,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` muss eine Liste von höchstens 10000 Stücken sein @msg give either `start` for a new path or `id`, not both geben Sie entweder `start` für einen neuen Pfad oder `id` an, nicht beides @msg `subpath` and `keep` need `id` `subpath` und `keep` erfordern `id` +@msg the end is not a straight line or a circular arc das Ende ist weder eine gerade Linie noch ein Kreisbogen @msg no such user library keine solche Benutzerbibliothek @msg no such view keine solche Ansicht @msg no such width point kein solcher Breitenpunkt diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1223d2ed28..d2ed355874 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5443,6 +5443,7 @@ digits Malayalam Μαλαγιάλαμ @msg `pieces` must be a list of at most 10000 pieces το `pieces` πρέπει να είναι λίστα με έως 10000 τμήματα @msg give either `start` for a new path or `id`, not both δώστε είτε `start` για νέα διαδρομή είτε `id`, όχι και τα δύο @msg `subpath` and `keep` need `id` τα `subpath` και `keep` απαιτούν `id` +@msg the end is not a straight line or a circular arc το άκρο δεν είναι ούτε ευθεία γραμμή ούτε κυκλικό τόξο @msg no such user library δεν υπάρχει τέτοια βιβλιοθήκη χρήστη @msg no such view δεν υπάρχει τέτοια προβολή @msg no such width point δεν υπάρχει τέτοιο σημείο πλάτους diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9bccf48eb8..855f61079b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5496,6 +5496,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` debe ser una lista de como máximo 10000 tramos @msg give either `start` for a new path or `id`, not both indica `start` para un trazado nuevo o `id`, pero no ambos @msg `subpath` and `keep` need `id` `subpath` y `keep` necesitan `id` +@msg the end is not a straight line or a circular arc el extremo no es una línea recta ni un arco circular @msg no such user library no existe esa biblioteca de usuario @msg no such view no existe esa vista @msg no such width point no existe ese punto de anchura diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index f8110fcd97..ae1b2d1ab4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5727,6 +5727,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `pieces` must be a list of at most 10000 pieces `pieces`-arvon on oltava luettelo, jossa on enintään 10000 osaa @msg give either `start` for a new path or `id`, not both anna joko `start` uutta polkua varten tai `id`, ei molempia @msg `subpath` and `keep` need `id` `subpath` ja `keep` edellyttävät `id`-arvoa +@msg the end is not a straight line or a circular arc pää ei ole suora viiva eikä ympyränkaari @msg no such user library käyttäjäkirjastoa ei ole @msg no such view näkymää ei ole @msg no such width point leveyspistettä ei ole diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index d3208f8c6b..44df50ae4e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5455,6 +5455,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` doit être une liste d’au plus 10000 segments @msg give either `start` for a new path or `id`, not both indiquez soit `start` pour un nouveau tracé, soit `id`, mais pas les deux @msg `subpath` and `keep` need `id` `subpath` et `keep` nécessitent `id` +@msg the end is not a straight line or a circular arc l’extrémité n’est ni une ligne droite ni un arc de cercle @msg no such user library bibliothèque utilisateur inexistante @msg no such view vue inexistante @msg no such width point point de largeur inexistant diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index f10a0cae0e..737a67ed61 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8520,6 +8520,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` में अधिकतम 10000 टुकड़ों की लिस्ट होनी चाहिए @msg give either `start` for a new path or `id`, not both नए पाथ के लिए `start` या `id` में से एक दें, दोनों नहीं @msg `subpath` and `keep` need `id` `subpath` और `keep` के लिए `id` चाहिए +@msg the end is not a straight line or a circular arc सिरा न तो सीधी रेखा है और न ही वृत्ताकार चाप @msg no such user library ऐसी कोई उपयोगकर्ता लाइब्रेरी नहीं @msg no such view कोई ऐसा दृश्य नहीं @msg no such width point ऐसी कोई चौड़ाई बिंदु नहीं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 75abe00c39..40fa94ef25 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6192,6 +6192,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg `pieces` must be a list of at most 10000 pieces `pieces`: legfeljebb 10000 darabból álló lista kell @msg give either `start` for a new path or `id`, not both adja meg vagy a `start` értéket egy új útvonalhoz, vagy az `id` értéket, de ne mindkettőt @msg `subpath` and `keep` need `id` a `subpath` és a `keep` mellé `id` kell +@msg the end is not a straight line or a circular arc a végpont nem egyenes vonal és nem is körív @msg no such user library nincs ilyen felhasználói könyvtár @msg no such view nincs ilyen nézet @msg no such width point nincs ilyen szélességi pont diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 898f7b39ae..64113f0890 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7991,6 +7991,7 @@ anchor Points: Titik: @msg `id` is not a path `id` bukan jalur @msg the path has no open subpath jalur tidak punya subjalur terbuka @msg the subpath is closed subjalur sudah tertutup +@msg the end is not a straight line or a circular arc ujungnya bukan garis lurus maupun busur lingkaran @msg the subpath is closed or too short to close subjalur sudah tertutup atau terlalu pendek untuk ditutup @msg the path is too short to remove a point from jalur terlalu pendek untuk dihapus titiknya @msg the segment can't be bent that far segmen tidak dapat dibengkokkan sejauh itu diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 35cda40dea..8347d399fb 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5522,6 +5522,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` deve essere un elenco di al massimo 10000 tratti @msg give either `start` for a new path or `id`, not both indica `start` per un nuovo tracciato oppure `id`, non entrambi @msg `subpath` and `keep` need `id` `subpath` e `keep` richiedono `id` +@msg the end is not a straight line or a circular arc l'estremità non è né una linea retta né un arco di cerchio @msg no such user library libreria utente inesistente @msg no such view vista inesistente @msg no such width point punto di larghezza inesistente diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c3efef8887..42dc533b5b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5059,6 +5059,7 @@ variable-list-end {0}, {1} {0}、{1} @msg `pieces` must be a list of at most 10000 pieces `pieces` には最大 10000 個のピースのリストを指定してください @msg give either `start` for a new path or `id`, not both 新しいパスの `start` か `id` のどちらか一方だけを指定してください @msg `subpath` and `keep` need `id` `subpath` と `keep` には `id` が必要です +@msg the end is not a straight line or a circular arc 端は直線でも円弧でもありません @msg object {id} is not a path オブジェクト {id} はパスではありません @msg object {id} is not a selected top-level object オブジェクト {id} は選択されている最上位のオブジェクトではありません @msg nothing to redo やり直す操作がありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 6e3eefa54c..8ebcf50479 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7254,6 +7254,7 @@ font-technology Variable ცვლადი @msg `pieces` must be a list of at most 10000 pieces `pieces` უნდა იყოს არაუმეტეს 10000 ნაწილის სია @msg give either `start` for a new path or `id`, not both მიუთითეთ ან `start` ახალი ტრაექტორიისთვის, ან `id`, მაგრამ არა ორივე @msg `subpath` and `keep` need `id` `subpath`-სა და `keep`-ს სჭირდება `id` +@msg the end is not a straight line or a circular arc ბოლო არც სწორი ხაზია და არც წრიული რკალი @msg no such user library მომხმარებლის ასეთი ბიბლიოთეკა არ არის @msg no such view ასეთი ხედი არ არის @msg no such width point ასეთი სიგანის წერტილი არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 65cc2ef2a9..07eef68fc2 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4988,6 +4988,7 @@ variable-list-end {0}, {1} {0} 및 {1} @msg `pieces` must be a list of at most 10000 pieces `pieces`는 최대 10000개 조각의 목록이어야 합니다 @msg give either `start` for a new path or `id`, not both 새 패스의 `start`와 `id` 중 하나만 지정하세요 @msg `subpath` and `keep` need `id` `subpath`와 `keep`에는 `id`가 필요합니다 +@msg the end is not a straight line or a circular arc 끝이 직선도 원호도 아닙니다 @msg object {id} is not a path 개체 {id}은(는) 패스가 아닙니다 @msg object {id} is not a selected top-level object 개체 {id}은(는) 선택된 최상위 개체가 아닙니다 @msg nothing to redo 다시 실행할 항목이 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d0a2d9d8b9..35068b9db8 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5865,6 +5865,7 @@ imageTrace Outline Contour @msg `pieces` must be a list of at most 10000 pieces `pieces` moet een lijst van hoogstens 10000 stukken zijn @msg give either `start` for a new path or `id`, not both geef `start` voor een nieuw pad of `id`, niet beide @msg `subpath` and `keep` need `id` `subpath` en `keep` vereisen `id` +@msg the end is not a straight line or a circular arc het einde is geen rechte lijn en geen cirkelboog @msg no such user library gebruikersbibliotheek bestaat niet @msg no such view weergave bestaat niet @msg no such width point breedtepunt bestaat niet diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index b1c52b9c56..2ff35e6b27 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5626,6 +5626,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` musi być listą co najwyżej 10000 fragmentów @msg give either `start` for a new path or `id`, not both podaj `start` dla nowej ścieżki albo `id`, ale nie oba @msg `subpath` and `keep` need `id` `subpath` i `keep` wymagają `id` +@msg the end is not a straight line or a circular arc koniec nie jest ani linią prostą, ani łukiem okręgu @msg no such user library brak takiej biblioteki użytkownika @msg no such view brak takiego widoku @msg no such width point brak takiego punktu szerokości diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 076c81d90f..018e5389bb 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4763,6 +4763,7 @@ axis Both Ambos @msg `pieces` must be a list of at most 10000 pieces `pieces` deve ser uma lista de no máximo 10000 trechos @msg give either `start` for a new path or `id`, not both informe `start` para um novo caminho ou `id`, mas não ambos @msg `subpath` and `keep` need `id` `subpath` e `keep` exigem `id` +@msg the end is not a straight line or a circular arc a extremidade não é uma linha reta nem um arco circular @msg no such user library biblioteca do usuário inexistente @msg no such view vista inexistente @msg no such width point ponto de largura inexistente diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 51bbe502ba..9196cf739d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5518,6 +5518,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` должен быть списком не более чем из 10000 фрагментов @msg give either `start` for a new path or `id`, not both укажите либо `start` для нового контура, либо `id`, но не оба @msg `subpath` and `keep` need `id` для `subpath` и `keep` нужен `id` +@msg the end is not a straight line or a circular arc конец не является ни прямой линией, ни дугой окружности @msg no such user library такой пользовательской библиотеки нет @msg no such view такого вида нет @msg no such width point такой точки ширины нет diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index b9bc161542..2c2ae10bc1 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5381,6 +5381,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` måste vara en lista med högst 10000 delar @msg give either `start` for a new path or `id`, not both ange antingen `start` för en ny bana eller `id`, inte båda @msg `subpath` and `keep` need `id` `subpath` och `keep` kräver `id` +@msg the end is not a straight line or a circular arc änden är varken en rak linje eller en cirkelbåge @msg no such user library användarbiblioteket finns inte @msg no such view vyn finns inte @msg no such width point breddpunkten finns inte diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 978d520cee..3292a097f6 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5200,6 +5200,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` en fazla 10000 parçadan oluşan bir liste olmalıdır @msg give either `start` for a new path or `id`, not both yeni bir yol için `start` ya da `id` verin, ikisini birden değil @msg `subpath` and `keep` need `id` `subpath` ve `keep` için `id` gerekir +@msg the end is not a straight line or a circular arc uç ne düz bir çizgi ne de bir çember yayı @msg no such user library böyle bir kullanıcı kütüphanesi yok @msg no such view öyle bir görüş yok @msg no such width point böyle bir genişlik noktası yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4424e82292..ff6ee31337 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5506,6 +5506,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` має бути списком щонайбільше з 10000 фрагментів @msg give either `start` for a new path or `id`, not both вкажіть або `start` для нового контуру, або `id`, але не обидва @msg `subpath` and `keep` need `id` для `subpath` і `keep` потрібен `id` +@msg the end is not a straight line or a circular arc кінець не є ні прямою лінією, ні дугою кола @msg no such user library такої користувацької бібліотеки немає @msg no such view такого виду немає @msg no such width point такої точки ширини немає diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 36c4d88aa8..0310f7a4d6 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5888,6 +5888,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg `pieces` must be a list of at most 10000 pieces `pieces` phải là danh sách tối đa 10000 đoạn @msg give either `start` for a new path or `id`, not both hãy đưa `start` cho đường dẫn mới hoặc `id`, không đưa cả hai @msg `subpath` and `keep` need `id` `subpath` và `keep` cần có `id` +@msg the end is not a straight line or a circular arc đầu mút không phải là đường thẳng hay cung tròn @msg no such user library không có thư viện người dùng như vậy @msg no such view không có chế độ xem như vậy @msg no such width point không có điểm chiều rộng như vậy diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 7c3b8967c0..d9598081f8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4748,6 +4748,7 @@ imageTrace Outline 轮廓 @msg `pieces` must be a list of at most 10000 pieces `pieces` 必须是最多 10000 个片段的列表 @msg give either `start` for a new path or `id`, not both 请为新路径指定 `start`,或指定 `id`,不能同时指定 @msg `subpath` and `keep` need `id` `subpath` 和 `keep` 需要 `id` +@msg the end is not a straight line or a circular arc 端点既不是直线也不是圆弧 @msg object {id} is not a path 对象 {id} 不是路径 @msg object {id} is not a selected top-level object 对象 {id} 不是选中的顶层对象 @msg nothing to redo 没有可重做的操作 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 14c6b80d8e..ed73d07159 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2114,6 +2114,7 @@ file-filter Templates 範本 @msg `pieces` must be a list of at most 10000 pieces `pieces` 必須是最多 10000 個片段的清單 @msg give either `start` for a new path or `id`, not both 請為新路徑指定 `start`,或指定 `id`,不可同時指定 @msg `subpath` and `keep` need `id` `subpath` 與 `keep` 需要 `id` +@msg the end is not a straight line or a circular arc 端點既不是直線也不是圓弧 @msg object {id} is not a path 物件 {id} 不是路徑 @msg object {id} is not a selected top-level object 物件 {id} 不是已選取的最上層物件 @msg nothing to redo 沒有可重做的動作 diff --git a/docs/mcp.md b/docs/mcp.md index 9775c52b0b..9078391dad 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7137,9 +7137,35 @@ the path. The command returns an error and changes nothing when both or neither an unknown `action`, a `turn` outside 1 to 359, a `flip` or `closed` that is not true or false, a `keep` outside 1 to the subpath's points, and for a closed subpath, a locked or hidden path or an `id` that is not a path. +Dragging the handle at the start or end of the path makes the line or arc there longer or shorter, as +[Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) +describes. The tool shows a handle 20 screen points beyond each end of the path being drawn, along the direction the +path leaves that end, where the end is a straight line or a circular arc; with no path being drawn, it shows them on +each open subpath of the one editable path selected. A line keeps its other point and its direction. An arc keeps its +other point, its circle and the way it turns, and its sweep follows the pointer around the circle, up to 359°. The +dragged end stays on its line or circle and does not snap to Smart Guides, and a drag stops where the path would +reach past the canvas. Each drag is one undo step, Escape during +the drag takes it back, and the path being drawn goes on from the new end. The pieces of the path being drawn that the +drag does not change stay pieces: C and `[` `]` still change the last one. The last piece, dragged by its end, stays +that piece, and as an arc it keeps an arc size of at least 1°. A click on a handle that does not drag is an ordinary +click: it adds a point, closes the path or starts a new one. The handle's place, the 359° limit, the 1° minimum, +Escape during a drag, the handles on a selected path and the dragged end not snapping are VectorCraft's own rules. + +`path.quickPenLength {id, subpath?, end?, length}` does the same for scripts and agents: it makes the line or arc at +`end` (`"end"`, the default, or `"start"`) of the open subpath `subpath` (0 when left out) `length` points long, +selects the path, as one undo step, and answers `{id, kind, length}`, where `kind` is `"line"` or `"arc"`. The arc at an +end is the run of segments before it that lie on one circle and turn the same way, as the Quick Pen draws them. A +`length` the line or arc already has changes nothing and records no undo step. The command returns an error and +changes nothing when `id` or `length` is missing, when `length` is not a number, is under 0.001, or is over 1000000 +for a line or over 359° of its circle for an arc, for an `end` other than `"start"` or `"end"`, an end that is neither +a straight line nor a circular arc (`the end is not a straight line or a circular arc`), a result that would reach past +the canvas, a closed subpath, a locked or hidden path, and an `id` that is not a path. For an arc, the error gives the +359° limit in points, rounded down to the thousandth. + ```json {"name":"run_command","arguments":{"command":"path.quickPen","params":{"start":[100,100],"pieces":[{"x":200,"y":100},{"x":300,"y":200,"action":"continuousArc"},{"x":300,"y":300,"action":"sharpArc","turn":90,"flip":true}]}}} {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"quickPen","key":"action","value":"sharpArc"}}} +{"name":"run_command","arguments":{"command":"path.quickPenLength","params":{"id":12,"end":"start","length":40}}} ``` ## Registration and trim marks diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e883fb6b86..b369bddc8f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -631,6 +631,8 @@ since 2026-10-01. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps and the side an arc bulges to are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests` and `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action`. Score and hours unchanged. +- **Quick Pen length handles (#2660, in part):** the Quick Pen tool shows a handle beyond the start and the end of the path being drawn, or of the selected path, where the end is a straight line or a circular arc; dragging it makes the line longer or shorter along its direction, or the arc longer or shorter around its circle, as one undo step (`path.quickPenLength`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) describes. A click on a handle that does not drag is an ordinary click. The handle's place, the 359° limit, the 1° minimum for a dragged last arc, Escape during a drag, the handles on a selected path and the dragged end not snapping are VectorCraft's own rules. Tests: tools `quickpen::tests` (`a_line_end_takes_a_new_length_along_its_direction`, `an_arc_end_keeps_its_circle`, `a_small_arc_end_follows_its_handle_around_the_circle`, `other_ends_have_no_piece`), engine `tests::quickpen` (`dragging_the_end_handle_lengthens_the_last_line`, `a_dragged_last_arc_still_flips`, `a_dragged_last_arc_keeps_at_least_one_degree`, `the_end_handle_changes_the_last_arc_on_a_shared_circle`, `another_selected_path_shows_its_handles`, `the_start_handle_of_a_selected_path_shortens_its_arc`, `a_click_on_a_handle_adds_a_point`, `a_length_drag_shows_no_next_piece`, `a_length_drag_stays_on_the_canvas`, `the_start_handle_keeps_the_last_arc_a_piece`, `path_quick_pen_length_sets_an_end`). Score and hours unchanged. + - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3822702956..86e46fb248 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -201,7 +201,7 @@ tools, never checked side by side) isn't captured row by row. | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | -| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660). Not yet: the on-canvas toolbar with its More menu, dragging a path's ends to change a line's or arc's length, Ctrl+scroll for the arc size, and editing and deleting with the tool | +| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end, drag the handle at a path's start or end to make its line or arc longer or shorter ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the length handles in `quickpen/length.rs` and `path.quickPenLength`, on the path being drawn or the selected path (a line keeps its direction, an arc its circle, up to 359°). Not yet: the on-canvas toolbar with its More menu, Ctrl+scroll for the arc size, and editing and deleting with the tool | | Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | | Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | | Graphic Styles list fills a taller panel (#2992) | done | Docked, floating or in a resized flyout, the list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 220 pt; `the_list_fills_a_tall_panel_above_its_footer` | From bcc8bcf6cc9a9e3c05c5362162b7ecadf1134e5d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 15:37:10 -0800 Subject: [PATCH 15/78] Quick Pen: a length drag measures the curve against the canvas, not its handles A cubic earlier in the path whose handle lies past the canvas while the curve stays on it no longer blocks every length drag at the end of the path. --- crates/tools/src/quickpen.rs | 9 ++++++--- crates/tools/src/quickpen/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 2d33815648..38f8e3fca1 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -25,7 +25,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, MAX_COORD, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; +use vectorcraft_geom::{Anchor, AnchorKind, BezPath, PathData, Point, SubPath, Vec2}; use crate::draw2::FEEDBACK; use crate::guides::{DrawSnap, Leave}; @@ -363,9 +363,12 @@ fn selected_alone(cx: &ToolContext, id: NodeId) -> bool { sel == [id] || cx.doc.parent_of(id).is_some_and(|p| sel == [p] && cx.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) } -/// Whether every point and handle of `sp` lies on the canvas. +/// Whether `sp` lies on the canvas: every point and handle does, or else the curve itself (its +/// extrema, not its handles) does. fn on_canvas(sp: &SubPath) -> bool { - sp.anchors.iter().all(|a| [a.p, a.h_in, a.h_out].iter().all(|q| q.x.abs() <= MAX_COORD && q.y.abs() <= MAX_COORD)) + let within = |v: f64| v.abs() <= MAX_COORD; + sp.anchors.iter().all(|a| [a.p, a.h_in, a.h_out].iter().all(|q| within(q.x) && within(q.y))) + || PathData::new(vec![sp.clone()]).bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].into_iter().all(within)) } fn point_tol(cx: &ToolContext) -> f64 { diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index b43319860d..bab7a01dc5 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -317,3 +317,23 @@ fn other_ends_have_no_piece() { closed.closed = true; assert_eq!(length::end_piece(&closed, false), None); } + +/// A control point may lie past the canvas while the curve stays on it; a curve that reaches past +/// the canvas is refused. +#[test] +fn the_canvas_check_measures_the_curve_not_its_control_points() { + let m = MAX_COORD; + let cubic = |out_x: f64| { + let mut a = Anchor::corner(pt(m - 100.0, 0.0)); + a.h_out = pt(out_x, 0.0); + let mut b = Anchor::corner(pt(m - 100.0, 100.0)); + b.h_in = b.p; + SubPath::new(vec![a, b], false) + }; + assert!(on_canvas(&cubic(m - 100.0))); + assert!(on_canvas(&cubic(m + 100.0))); + assert!(!on_canvas(&cubic(m + 1000.0))); + let mut far = start(pt(m + 1.0, 0.0)); + far.anchors.push(Anchor::corner(pt(0.0, 0.0))); + assert!(!on_canvas(&far)); +} From ff5071c93def059aba6927ae8a753383217c7706 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 16:13:21 -0800 Subject: [PATCH 16/78] Color Wheel: Show Opacity edge cases in the opacity commands and the row - paint.setFill and paint.setStroke give a graph's series marks and axis lines the opacity they write even when the object already shows it, so another mark's kept opacity no longer comes back after the graph is drawn again. - The proxies answer no opacity whenever the Live Paint Bucket paints, which includes a Cmd+click and an Eyedropper pick armed for it. - A swatch that is not a name is an error with an opacity instead of an opacity alone. - Hiding the Show Opacity row, or the row turning gray, during a drag keeps the previewed opacity as one undo step and ends the interaction. - The help text and docs/mcp.md name the picked mesh points case, the grayscale image colorize exception and the New Art Has Basic Appearance off case. --- crates/engine/src/cmd/appearance.rs | 18 ++++++++ crates/engine/src/cmd/graph/tests.rs | 41 +++++++++++++++++++ crates/engine/src/cmd/paint.rs | 33 +++++++++++---- crates/engine/src/tests/paintopacity.rs | 34 +++++++++++++++ crates/ui-egui/src/panels/color_wheel.rs | 34 +++++++++++++-- .../src/panels/tests_color_wheel_opacity.rs | 38 +++++++++++++++++ docs/mcp.md | 9 ++-- 7 files changed, 193 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 3b23d62634..c2f7e623d5 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -1184,6 +1184,24 @@ pub(crate) fn capture_series_paint_writes( super::graph::capture_series_top_paints(d, &rows) } +/// Store on the graph the opacity and blend mode of each row an edit wrote (`written`: an object with the index of the +/// row) on the series marks among them, when that row is the topmost visible one of its kind, also when the mark +/// already showed that opacity: it replaces the opacity another mark of the series left on the graph. When the edit +/// reaches several marks of one series, the frontmost one sets what the graph stores. Returns whether the stored +/// opacity or blend mode changed. +pub(crate) fn capture_series_opacity_writes(d: &mut vectorcraft_doc::Document, written: &[(NodeId, usize)]) -> bool { + let ids: Vec = written.iter().map(|(id, _)| *id).collect(); + // A later mark's capture replaces an earlier one's: take them in paint order. + let rows: Vec<(NodeId, bool)> = series_children_in_paint_order(d, &ids) + .into_iter() + .flat_map(|id| { + let shown = written.iter().filter(move |(w, _)| *w == id).filter_map(|(_, at)| Some((id, top_row_kind(&d.node(id)?.appearance, *at)?))); + shown.collect::>() + }) + .collect(); + super::graph::capture_series_opacity(d, &rows) +} + /// The kind of the row at `at` (fill `true`, stroke `false`) when it is the topmost visible row of that kind in `ap`. fn top_row_kind(ap: &Appearance, at: usize) -> Option { let fill = ap.items.get(at)?.is_fill(); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 9ab74794cb..dea347878c 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -352,6 +352,47 @@ fn a_paint_opacity_on_a_series_mark_survives_regeneration() { assert!(opacities.iter().all(|o| *o == (0.4, 0.6)), "{opacities:?}"); } +/// `paint.setFill {opacity}` and `paint.setStroke {opacity}` with the opacity a mark already shows replace the opacity +/// another mark of the series left on the graph, as an explicit 100% does. +#[test] +fn a_paint_opacity_a_series_mark_already_shows_replaces_the_kept_opacity() { + let (mut s, id, _, marks) = column_marks(); + s.execute("paint.setFill", &json!({"ids": [marks[0].0], "opacity": 40})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [marks[0].0], "opacity": 60})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), Some(0.6))); + // The second mark is opaque already: its row comes out as it was. + s.execute("paint.setFill", &json!({"ids": [marks[1].0], "color": "#ff0000", "opacity": 100})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.stroke_opacity), (None, Some(0.6))); + s.execute("paint.setStroke", &json!({"ids": [marks[1].0], "opacity": 100})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.fill_opacity, kept.stroke_opacity), (None, None)); + s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let opacities: Vec<(f32, f32)> = + series(&n, 0).children().unwrap().iter().map(|m| (m.appearance.fill().unwrap().opacity, m.appearance.stroke().unwrap().opacity)).collect(); + assert!(opacities.iter().all(|o| *o == (1.0, 1.0)), "{opacities:?}"); +} + +/// The same for a graph's axis lines: a stroke opacity set on an opaque line replaces the one its kind keeps from another +/// line. +#[test] +fn a_stroke_opacity_an_axis_line_already_shows_replaces_the_kept_opacity() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "opacity": 40})).unwrap(); + let kept = |s: &Session| spec(s, id).label_styles.axis_rows.and_then(|r| r.paint.stroke_opacity); + assert_eq!(kept(&s), Some(0.4)); + s.execute("paint.setStroke", &json!({"ids": [lines[1].id.0], "opacity": 100})).unwrap(); + assert_eq!(kept(&s), None); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let opacities: Vec = line_nodes(&s, id).iter().map(|n| n.appearance.stroke().map_or(1.0, |st| st.opacity)).collect(); + assert!(opacities.iter().all(|o| *o == 1.0), "{opacities:?}"); +} + /// Clear Appearance and Reduce to Basic Appearance on a series mark take its fill and stroke opacity away, and the /// graph keeps none, so the series stays opaque when it is drawn again. #[test] diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 10561f0e47..1669694cdb 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors; the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -243,14 +243,15 @@ impl Session { /// first picked point's. The rows the command would edit are read in order (a group without an /// active Appearance row stands for its contents), and the first that exists answers. `None` /// with nothing selected, for an object selected in a symbol instance, while the Live Paint - /// Bucket is the active tool, while the Type tool has characters selected, and when only type + /// Bucket is the active tool (or another tool works for it, [`Session::bucket_paints`]), while + /// the Type tool has characters selected, and when only type /// characters, objects without that item or the art of graph designs in a graph series are /// selected. pub fn proxy_opacity(&self, stroke: bool) -> Option { let st = self.active()?; // The Live Paint Bucket takes a fill or stroke chosen as the color it paints with, and the // selection keeps its own (for_bucket). - if st.selection.symbol_part.is_some() || self.tool_id() == LIVE_PAINT_BUCKET { + if st.selection.symbol_part.is_some() || self.bucket_paints() { return None; } // The command would give the opacity to the characters, which have none of their own. @@ -604,7 +605,9 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result { check_keep_model(p, cmd)?; let opacity = opacity_param(p, cmd)?; let paint = paint_from(s, p)?; - if paint.is_none() && opacity.is_none() { + // A `swatch` that is no name gives no paint, and does not turn the request into an opacity alone. + let swatch_not_a_name = p.get("swatch").is_some_and(|v| !v.is_null() && !v.is_string()); + if paint.is_none() && (opacity.is_none() || swatch_not_a_name) { return Err(bad(cmd, "give color, none, swatch, gradient or opacity")); } // As `paint.editGradient`: a `dither` given applies to gradient fills only. A gradient swatch @@ -647,8 +650,10 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) /// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or /// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points' -/// own opacity for a fill, nothing on a target without that item. The opacity alone changes neither -/// the defaults for new art nor the remembered colors. An opacity that would go only to type +/// own opacity for a fill (with no paint or a solid color), nothing on a target without that item. +/// The opacity alone changes neither the defaults for new art nor the remembered colors; with New +/// Art Has Basic Appearance off, new art copies the first selected object's appearance after any +/// command, its opacity included. An opacity that would go only to type /// characters, to an object selected in a symbol instance, or to no target at all is an error. fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity: Option, fill: bool) -> Result { let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; @@ -781,6 +786,8 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity let characters = std::cell::RefCell::new(Vec::new()); // The targets that took the opacity, and whether one would have given it to its characters. let (took_opacity, characters_skipped) = (std::cell::RefCell::new(std::collections::BTreeSet::new()), std::cell::Cell::new(false)); + // The row each target took the opacity on, for what a graph keeps. + let opacity_written = std::cell::RefCell::new(Vec::new()); let paint_one = |n: &mut Node, index: Option, paint: &Paint| -> Result<()> { if index.is_none() && matches!(n.kind, NodeKind::Text(_)) { characters.borrow_mut().push(n.id); @@ -866,6 +873,8 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity if let Some(item) = item { *item = o; took_opacity.borrow_mut().insert(n.id); + let at = index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill)); + opacity_written.borrow_mut().extend(at.map(|at| (n.id, at))); } }; // The objects counted: with a design's art, those with a row equal to the art's. @@ -894,8 +903,16 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity } return Err(bad(cmd, "no target has that fill or stroke to take the opacity")); } - // A graph keeps the opacity of a series mark's topmost visible fill and stroke for the whole series. - let kept = opacity.is_some() && super::appearance::capture_series_changes(before, d, changed); + // A graph keeps the opacity of a series mark's topmost visible fill and stroke for the whole series, and of a + // graph line's, also when the object already showed it. + let kept = opacity.is_some() && { + let rows = opacity_written.borrow(); + let on = super::graph::RowWrites { opacity: true, ..super::graph::RowWrites::NONE }; + let (on_fill, on_stroke) = if fill { (on, super::graph::RowWrites::NONE) } else { (super::graph::RowWrites::NONE, on) }; + let marks = super::appearance::capture_series_changes(before, d, changed); + let written = super::appearance::capture_series_opacity_writes(d, &rows); + marks | written | super::graph::capture_line_row_writes(d, &rows, on_fill, on_stroke) + }; let Some(paint) = &paint else { return Ok(kept) }; let series = super::appearance::capture_series_paint_writes(before, d, changed, &written.borrow()); // A graph line keeps the paint written to it, also when it already showed it. diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index 8c21702196..c2e80f983a 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -449,3 +449,37 @@ fn the_live_paint_bucket_answers_no_opacity() { assert!(s.execute("paint.setFill", &json!({"opacity": 40})).is_err()); assert_eq!(*s.doc().unwrap().doc, *doc); } + +/// The Eyedropper armed to sample into the Live Paint Bucket's gradient works for the bucket, so +/// the proxies answer no opacity for the selection then too, as they show no paint of its own. +#[test] +fn the_eyedropper_armed_for_the_bucket_answers_no_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + s.select_tool("eyedropper", ViewInfo::default()).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the Eyedropper alone shows the selection's"); + s.set_tool_option("stop", &json!("livePaintBucket")); + assert!(s.bucket_paints()); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + assert_eq!(proxies(&mut s)["strokeOpacity"], Value::Null); +} + +/// A `swatch` that is no name does not turn a request into an opacity alone: it is an error and +/// leaves the document as it was. +#[test] +fn a_swatch_that_is_no_name_is_refused_with_an_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let doc = s.doc().unwrap().doc.clone(); + for cmd in ["paint.setFill", "paint.setStroke"] { + for swatch in [json!(5), json!(true), json!(["a"]), json!({})] { + assert!(s.execute(cmd, &json!({"swatch": swatch, "opacity": 40})).is_err(), "{cmd} {swatch}"); + } + // A null swatch names none, so the opacity goes alone. + s.execute(cmd, &json!({"swatch": null, "opacity": 40})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(*s.doc().unwrap().doc, *doc); +} diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 202935917a..7a51c26e2c 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -658,11 +658,13 @@ fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32, ga /// picks it), else that of the fill or stroke item /// ([`vectorcraft_engine::Session::proxy_opacity`]), which nothing selected and type characters /// do not have. A stop or point of a gradient on type characters belongs to the gradient, so the -/// row sets it. With nothing selected the stop or point belongs to the defaults for new art, which -/// the row leaves alone, and an object selected in a symbol instance has no opacity the row can set. +/// row sets it. With nothing selected, or while the Live Paint Bucket paints +/// ([`vectorcraft_engine::Session::bucket_paints`]), the stop or point belongs to the defaults for +/// new art, which the row leaves alone, and an object selected in a symbol instance has no opacity +/// the row can set. fn shown_opacity(app: &VectorcraftApp, tgt: &Target) -> (f32, bool) { let stroke = !app.session.fill_active; - let selected = app.session.active().is_some_and(|d| !d.selection.is_empty() && d.selection.symbol_part.is_none()); + let selected = !app.session.bucket_paints() && app.session.active().is_some_and(|d| !d.selection.is_empty() && d.selection.symbol_part.is_none()); let point = |index: usize| match super::active_paint(app) { Paint::Gradient(g) => super::gradient::shown_points(&g).points.get(index).map(|p| p.opacity), _ => None, @@ -700,6 +702,25 @@ fn apply_opacity(app: &mut VectorcraftApp, tgt: &Target, o: f32, phase: Live) { } } +/// Panel state: whether a drag of the Show Opacity row has previewed on an open interaction and not +/// been released. +const OPACITY_LIVE: &str = "color-wheel-opacity-live"; + +/// End the drag of the Show Opacity row when its row is hidden (`ui.colorWheel {opacity: false}`) or +/// turned gray before the release: the preview is kept as one undo step and the interaction ends. +fn end_opacity_drag(app: &mut VectorcraftApp, ui: &Ui) { + if !pstate::(ui.ctx(), OPACITY_LIVE) { + return; + } + if app.session.in_interaction() + && let Err(e) = app.session.commit_interaction() + { + app.status(e.to_string()); + } + app.sync_views(); + set_pstate(ui.ctx(), OPACITY_LIVE, false); +} + /// The Show Opacity row: the Transparency panel's icon, a slider whose track shows `color` from /// clear to solid, and a percent field. Gray when [`shown_opacity`] finds nothing to set. fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Color) { @@ -724,6 +745,11 @@ fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Colo }); if let Some((v, phase)) = edit.filter(|_| live) { apply_opacity(app, tgt, v, phase); + set_pstate(ui.ctx(), OPACITY_LIVE, phase == Live::Dragging); + } + // A drag whose row turned gray reports no release. + if !live { + end_opacity_drag(app, ui); } } @@ -1200,6 +1226,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { set_pstate(ui.ctx(), MEMORY, Some((now, rgb, hsb))); } } + } else { + end_opacity_drag(app, ui); } let (mut picked_lch, mut picked_hsl) = (None, None); match app.ui.color_wheel.sliders { diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index b794dc3c54..24ad5c81f7 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -137,6 +137,34 @@ fn the_slider_sets_the_fill_opacity_and_takes_the_arrow_keys() { assert_eq!((fill_opacity(h.state()) * 100.0).round(), before + 1.0); } +/// Hiding the row during a drag on its slider keeps the opacity the drag previewed as one undo step +/// and leaves no interaction open. +#[test] +fn hiding_the_row_during_a_drag_keeps_its_opacity_as_one_undo_step() { + let mut h = harness(app()); + let undo = undo_labels(h.state()).len(); + let r = slider_rect(&h); + let at = |f: f32| Pos2::new(r.left() + 4.0 + f * (r.width() - 8.0), r.top() + 7.0); + let press = |h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, pressed: bool| { + h.event(Event::PointerMoved(pos)); + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + }; + press(&mut h, at(0.5), true); + for _ in 0..2 { + h.event(Event::PointerMoved(at(0.25))); + h.run_steps(1); + } + assert!(h.state().session.in_interaction(), "the drag previews"); + let previewed = fill_opacity(h.state()); + assert!((previewed - 0.25).abs() < 0.05, "{previewed}"); + h.state_mut().run("ui.colorWheel", json!({"opacity": false})).unwrap(); + h.run_steps(2); + assert!(!h.state().session.in_interaction(), "the interaction ended"); + assert!((fill_opacity(h.state()) - previewed).abs() < 1e-6); + assert_eq!(undo_labels(h.state()).len(), undo + 1); +} + /// Screen readers get a slider named Opacity with its percentage and its range, and can step it and /// set it. #[test] @@ -322,6 +350,16 @@ fn the_row_is_gray_with_nothing_selected_and_on_type() { action(&mut h, Action::SetValue, Some(ActionData::NumericValue(25.0))); assert_eq!(h.state().session.paint.fill, defaults); + // The Live Paint Bucket painting a gradient with an object selected: the stop is the bucket's. + let mut app = self::app(); + app.session.select_tool("livePaintBucket", Default::default()).unwrap(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + let mut h = harness(app); + assert!(h.get_by_role_and_label(Role::Slider, "Opacity").accesskit_node().is_disabled()); + let defaults = h.state().session.paint.fill.clone(); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(25.0))); + assert_eq!(h.state().session.paint.fill, defaults); + // An object with a gradient fill selected in a dynamic symbol instance. let mut app = self::app(); app.run("paint.setFill", json!({"gradient": {}})).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 54dc55587e..5f6c845158 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -912,10 +912,13 @@ its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. `inspect_document` reports it as `paint.appearanceItem`. `paint.setFill` and `paint.setStroke` also take `opacity` (0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint -undone. Without a new paint, `objects` counts only the targets that took the opacity. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has +undone. A `swatch` that is not a name does not make the request an opacity alone: it is an error without a paint of +its own. A color for a grayscale or 1-bit image's drawing color creates no fill row, so an opacity given with it goes +to a fill row the image has. With New Art Has Basic Appearance off, the next shape copies the first selected object's +appearance after any command, its opacity included. Without a new paint, `objects` counts only the targets that took the opacity. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has that row (a selected path of a compound path answers with its compound path's row, which the commands edit, and a -selected Live Paint group answers with its faces' fills and its edges' strokes). It answers null with nothing selected, for an object selected in a symbol instance, while the Live Paint Bucket is the -active tool, while the Type tool has characters selected, and when only type characters (which have no opacity of their own) or objects without that +selected Live Paint group answers with its faces' fills and its edges' strokes). It answers null with nothing selected, for an object selected in a symbol instance, while the Live Paint Bucket paints (it is the active tool, or a Cmd+click or an Eyedropper pick works for it), +while the Type tool has characters selected, and when only type characters (which have no opacity of their own) or objects without that row are selected. Live effects take the same `item` to apply to one fill or stroke instead of the whole object: `run_command effect.apply {"effect": "path.offsetPath", "item": 0}`, and `effect.remove`, `effect.setParams` (`visible` toggles one) and `effect.duplicate` address that item's effects; From 88e3575a1ed368b35031a02e82d9aa029440faca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:22:09 -0800 Subject: [PATCH 17/78] Quick Pen: a length drag ends where the pointer is let go and ignores outside edits and piece keys The end handle's drag now applies the release position before it ends, so a press let go away from the handle without a drag event still changes the length. An edit made outside the tool during the press ends the drag, so a later preview does not overwrite it. C and [ ] do nothing until the drag ends. A selected compound path shows the length handles of the paths it holds, and path.quickPenLength checks its result against the same canvas rule as the drag. --- crates/engine/src/cmd/draw2/quickpen.rs | 2 +- crates/engine/src/tests/quickpen.rs | 119 +++++++++++++++ crates/tools/src/quickpen.rs | 189 ++++++++++++++++-------- docs/mcp.md | 3 +- 4 files changed, 250 insertions(+), 63 deletions(-) diff --git a/crates/engine/src/cmd/draw2/quickpen.rs b/crates/engine/src/cmd/draw2/quickpen.rs index fc826b9b42..c6549075df 100644 --- a/crates/engine/src/cmd/draw2/quickpen.rs +++ b/crates/engine/src/cmd/draw2/quickpen.rs @@ -133,7 +133,7 @@ pub(super) fn quick_pen_length(s: &mut Session, p: &Value) -> Result { return Err(bad(L, format!("`{key}` must be from {lo} to {hi}"))); } let out = qpl::with_length(sp, at_start, length).ok_or_else(|| bad(L, "the end is not a straight line or a circular arc"))?; - if !out.anchors.iter().all(|a| within_input_bound(a.p) && within_input_bound(a.h_in) && within_input_bound(a.h_out)) { + if !qp::on_canvas(&out) { return Err(bad(L, "result would exceed the canvas (coordinates out of range)")); } let kind = match piece.shape { diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 8ff8656a00..97591687af 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -762,6 +762,125 @@ fn a_length_drag_stays_on_the_canvas() { assert_eq!(only_path(&s).anchors.len(), 3, "the drawing went on"); } +/// The paths of a selected compound path show length handles, also after a drag selected the +/// compound again. +#[test] +fn a_compound_path_shows_the_length_handles_of_its_paths() { + let mut s = session(); + let a = s.execute("path.quickPen", &json!({"start": [100, 100], "pieces": [{"x": 200, "y": 100}]})).unwrap(); + let b = s.execute("path.quickPen", &json!({"start": [100, 300], "pieces": [{"x": 200, "y": 300}]})).unwrap(); + s.execute("select.set", &json!({"ids": [a["id"], b["id"]]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + quick_pen(&mut s); + press(&mut s, &[(220.0, 100.0), (250.0, 100.0), (280.0, 100.0)]); + press(&mut s, &[(220.0, 300.0), (250.0, 300.0), (270.0, 300.0)]); + let mut ends: Vec = paths(&s).iter().filter_map(|(_, pd)| pd.subpaths[0].anchors.last().map(|a| a.p)).collect(); + ends.sort_by(|p, q| p.y.total_cmp(&q.y)); + assert_eq!(ends, [pt(260.0, 100.0), pt(250.0, 300.0)]); +} + +/// An edit made outside the tool during a length press ends the press: a later drag does not +/// preview from the path as the press found it, and so does not undo the edit. +#[test] +fn an_outside_edit_during_a_length_press_is_kept() { + // The edit comes before the first drag event, or after the drag began. + for began in [false, true] { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + let id = paths(&s)[0].0.0; + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + if began { + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap(); + } + s.execute("path.quickPenLength", &json!({"id": id, "length": 40})).unwrap(); + let edited = only_path(&s); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s), edited, "began: {began}"); + } + // Escape after the edit takes the drag back without taking the edit back. + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + let id = paths(&s)[0].0.0; + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap(); + s.execute("path.quickPenLength", &json!({"id": id, "length": 40})).unwrap(); + let edited = only_path(&s); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s), edited, "escape"); +} + +/// C and `[` `]` wait for a length drag to end: they neither add an undo step of their own nor +/// change the arc the drag is changing. +#[test] +fn piece_keys_do_nothing_during_a_length_drag() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 320.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 400.0), v).unwrap(); + let during = only_path(&s); + for k in [ToolKey::Letter('c'), ToolKey::BracketRight, ToolKey::BracketLeft] { + assert!(s.tool_claims_key(k, view()), "{k:?} stays with the tool"); + key(&mut s, k); + assert_eq!(only_path(&s), during, "{k:?}"); + } + s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 400.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 400.0), v).unwrap(); + assert_eq!(undo_steps(&s), undo + 1); + assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); +} + +/// A length drag ends where the pointer is let go, also when no drag event came after the press. +#[test] +fn a_length_drag_ends_at_the_release_point() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(260.0, 100.0)); + assert_eq!(undo_steps(&s), undo + 1); + // A press let go away from the handle without a drag event drags too. + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(300.0, 100.0)); + assert_eq!(only_path(&s).anchors.len(), 2); + assert_eq!(undo_steps(&s), undo + 2); +} + +/// `path.quickPenLength` refuses a result past the canvas, not only one past the input limit. +#[test] +fn path_quick_pen_length_stays_on_the_canvas() { + let mut s = session(); + let x = vectorcraft_doc::MAX_COORD - 500_000.0; + let r = s.execute("path.quickPen", &json!({"start": [x, 0], "pieces": [{"x": x + 10.0, "y": 0}]})).unwrap(); + let id = r["id"].as_u64().unwrap(); + let before = only_path(&s); + let undo = undo_steps(&s); + let e = s.execute("path.quickPenLength", &json!({"id": id, "length": 1_000_000})).unwrap_err().to_string(); + assert!(e.contains("would exceed the canvas"), "{e}"); + assert_eq!(only_path(&s), before); + assert_eq!(undo_steps(&s), undo); + s.execute("path.quickPenLength", &json!({"id": id, "length": 400_000})).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(x + 400_000.0, 0.0)); +} + /// Dragged by the start handle while the path is being drawn, the first line changes and the last /// sharp-corner arc stays the last piece, so C still flips it. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 38f8e3fca1..7d50150be0 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -339,6 +339,12 @@ struct LengthDrag { /// The subpath as the press found it, and its last piece as that subpath held it. before: SubPath, tail: Option, + /// The document's revision ([`ToolContext::revision`]) after the drag's last edit. A press + /// previews from the path as it found it, so once the revision differs, an edit was made + /// outside the tool and the drag previews no more. + revision: (u64, u64), + /// An edit made outside the tool ended the drag. + stale: bool, } pub struct QuickPenTool { @@ -365,7 +371,7 @@ fn selected_alone(cx: &ToolContext, id: NodeId) -> bool { /// Whether `sp` lies on the canvas: every point and handle does, or else the curve itself (its /// extrema, not its handles) does. -fn on_canvas(sp: &SubPath) -> bool { +pub fn on_canvas(sp: &SubPath) -> bool { let within = |v: f64| v.abs() <= MAX_COORD; sp.anchors.iter().all(|a| [a.p, a.h_in, a.h_out].iter().all(|q| within(q.x) && within(q.y))) || PathData::new(vec![sp.clone()]).bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].into_iter().all(within)) @@ -497,7 +503,19 @@ impl QuickPenTool { if let Some(dr) = self.drawing.as_mut().filter(|dr| dr.id == Some(handle.id)) { dr.before_press = shared_node(cx.doc, handle.id).cloned(); } - self.length = Some(LengthDrag { handle, press: p, length: handle.piece.length, dragged: false, begun: false, last, before, tail }); + let drag = LengthDrag { + handle, + press: p, + length: handle.piece.length, + dragged: false, + begun: false, + last, + before, + tail, + revision: cx.revision, + stale: false, + }; + self.length = Some(drag); return vec![]; } self.click(cx, p) @@ -585,9 +603,20 @@ impl QuickPenTool { self.drawing.as_ref().map(|dr| (id, dr.si, sp)).into_iter().collect() } else if let [id] = cx.selection.objects.as_slice() && cx.doc.is_editable(*id) - && let Some(pd) = cx.doc.node(*id).and_then(|n| n.path_data()) + && let Some(node) = cx.doc.node(*id) { - pd.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed).map(|(si, sp)| (*id, si, sp)).collect() + // A compound path shows the handles of the paths it holds. + let members: Vec<&Node> = if matches!(node.kind, NodeKind::Compound { .. }) { + let editable = cx.doc.editable(); + node.editing_children().iter().map(|c| c.as_ref()).filter(|c| editable(c.id)).collect() + } else { + vec![node] + }; + members + .into_iter() + .filter_map(|n| Some((n.id, n.path_data()?))) + .flat_map(|(id, pd)| pd.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed).map(move |(si, sp)| (id, si, sp))) + .collect() } else { vec![] }; @@ -643,11 +672,86 @@ impl QuickPenTool { json!({"id": h.id.0, "subpath": h.si, "end": if h.at_start { "start" } else { "end" }, "length": drag.length}) } + /// Moves the end of the line or arc a length drag changes to follow the pointer at `p` and + /// previews it. An edit made outside the tool since the last preview ends the drag instead: the + /// press then commits the document as it is. + fn length_drag_to(&mut self, cx: &ToolContext, p: Point) -> Vec { + let Some(mut drag) = self.length.clone() else { return vec![] }; + if drag.stale { + return vec![]; + } + if drag.revision != cx.revision { + drag.stale = true; + self.length = Some(drag); + return vec![]; + } + if !drag.dragged && p.distance(drag.press) < cx.tol(DRAG_PX) { + return vec![]; + } + drag.dragged = true; + self.length = Some(drag.clone()); + // The end follows the pointer, as far behind it as the press was. + let piece = drag.handle.piece; + let mut length = piece.length_dragged(drag.press, p, drag.length); + // The last piece drawn goes on being a piece of the drawing, drawn again to its new + // end; an arc piece keeps an arc size of at least 1°. + let mut redrawn = None; + let changed = if let (Some(last), Some(tail)) = (drag.last, drag.tail.as_ref()) { + if let length::EndShape::Arc { radius, .. } = piece.shape { + length = length.max(MIN_TURN.to_radians() * radius); + } + let changed = length::with_length(tail, false, length); + redrawn = changed.as_ref().and_then(|sp| sp.anchors.last().map(|a| a.p)).map(|to| { + let turn = match piece.shape { + length::EndShape::Arc { radius, .. } => (length / radius).to_degrees().clamp(MIN_TURN, MAX_TURN), + length::EndShape::Line => last.turn, + }; + Piece { to, turn, ..last } + }); + changed + } else { + length::with_length(&drag.before, drag.handle.at_start, length) + }; + // A length that would take the path past the canvas is not taken: the end stays + // where the drag last put it. + if !changed.is_some_and(|sp| on_canvas(&sp)) { + return vec![]; + } + if drag.begun && (length - drag.length).abs() <= 1e-12 * length.max(1.0) { + return vec![]; + } + let mut out = vec![]; + if !drag.begun { + drag.begun = true; + out.push(Action::Begin("Quick Pen".into())); + } + drag.length = length; + match redrawn { + Some(pc) => { + if let Some(l) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { + *l = pc; + } + out.push(Action::Preview(COMMAND.into(), self.params(false))); + } + None => out.push(Action::Preview(LENGTH_COMMAND.into(), Self::length_params(&drag))), + } + // The drawing sees the path as the preview left it. + out.push(drawn()); + self.length = Some(drag); + out + } + /// A length drag let go: once it changed the path being drawn, the drawing goes on from the /// changed path, which `path.quickPenLength` made from the same points. A press on a handle let - /// go without dragging is a click there. + /// go without dragging is a click there. After an edit made outside the tool, the path being + /// drawn ends and the document stays as that edit left it. fn end_length_drag(&mut self, cx: &ToolContext) -> Vec { let Some(drag) = self.length.take() else { return vec![] }; + if drag.stale || drag.revision != cx.revision { + self.drawing = None; + self.snap.clear(); + return if drag.begun { vec![Action::Commit] } else { vec![] }; + } if !drag.dragged { let mut out = self.click(cx, drag.press); if self.press.take().is_some_and(|pr| pr.begun) { @@ -711,60 +815,7 @@ impl Tool for QuickPenTool { } self.press_down(cx, p) } - PointerKind::Drag if self.length.is_some() => { - let Some(mut drag) = self.length.clone() else { return vec![] }; - if !drag.dragged && p.distance(drag.press) < cx.tol(DRAG_PX) { - return vec![]; - } - drag.dragged = true; - self.length = Some(drag.clone()); - // The end follows the pointer, as far behind it as the press was. - let piece = drag.handle.piece; - let mut length = piece.length_dragged(drag.press, p, drag.length); - // The last piece drawn goes on being a piece of the drawing, drawn again to its new - // end; an arc piece keeps an arc size of at least 1°. - let mut redrawn = None; - let changed = if let (Some(last), Some(tail)) = (drag.last, drag.tail.as_ref()) { - if let length::EndShape::Arc { radius, .. } = piece.shape { - length = length.max(MIN_TURN.to_radians() * radius); - } - let changed = length::with_length(tail, false, length); - redrawn = changed.as_ref().and_then(|sp| sp.anchors.last().map(|a| a.p)).map(|to| { - let turn = match piece.shape { - length::EndShape::Arc { radius, .. } => (length / radius).to_degrees().clamp(MIN_TURN, MAX_TURN), - length::EndShape::Line => last.turn, - }; - Piece { to, turn, ..last } - }); - changed - } else { - length::with_length(&drag.before, drag.handle.at_start, length) - }; - // A length that would take the path past the canvas is not taken: the end stays - // where the drag last put it. - if !changed.is_some_and(|sp| on_canvas(&sp)) { - return vec![]; - } - let mut out = vec![]; - if !drag.begun { - drag.begun = true; - out.push(Action::Begin("Quick Pen".into())); - } - drag.length = length; - match redrawn { - Some(pc) => { - if let Some(l) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { - *l = pc; - } - out.push(Action::Preview(COMMAND.into(), self.params(false))); - } - None => out.push(Action::Preview(LENGTH_COMMAND.into(), Self::length_params(&drag))), - } - // The drawing sees the path as the preview left it. - out.push(drawn()); - self.length = Some(drag); - out - } + PointerKind::Drag if self.length.is_some() => self.length_drag_to(cx, p), PointerKind::Drag => { let Some(mut pr) = self.press else { return vec![] }; if !pr.dragged && p.distance(pr.at) < cx.tol(DRAG_PX) { @@ -780,7 +831,10 @@ impl Tool for QuickPenTool { PointerKind::Up => { if self.length.is_some() { self.snap.clear(); - return self.end_length_drag(cx); + // The end goes where the press is let go, also past the last drag. + let mut out = self.length_drag_to(cx, p); + out.extend(self.end_length_drag(cx)); + return out; } let out = match self.press { // The piece ends where the press is let go, also past the last drag. @@ -810,6 +864,11 @@ impl Tool for QuickPenTool { } fn notify(&mut self, cx: &ToolContext, what: &str) { + if what == DRAWN + && let Some(drag) = self.length.as_mut() + { + drag.revision = cx.revision; + } let Some(dr) = self.drawing.as_mut() else { return }; if what == "created" && let [id] = cx.selection.objects.as_slice() @@ -846,7 +905,7 @@ impl Tool for QuickPenTool { fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { match key { - ToolKey::Letter('c') => self.last_sharp_arc(cx).is_some(), + ToolKey::Letter('c') => self.length.is_some() || self.last_sharp_arc(cx).is_some(), ToolKey::BracketLeft | ToolKey::BracketRight | ToolKey::AltTap => true, ToolKey::Enter => self.active(cx).is_some(), _ => false, @@ -894,6 +953,12 @@ impl Tool for QuickPenTool { if !drag.begun { return vec![]; } + // An edit made outside the tool since the last preview stays: the cancel would + // take it back with the drag. + if drag.stale || drag.revision != cx.revision { + self.drawing = None; + return vec![Action::Commit]; + } self.restore_last_piece(&drag); // The drawing sees the path as the cancel leaves it. vec![Action::Cancel, drawn()] @@ -901,6 +966,8 @@ impl Tool for QuickPenTool { None => vec![], }, ToolKey::Enter if self.length.is_some() => vec![], + // C and [ ] change the last piece once the drag has ended. + ToolKey::Letter('c') | ToolKey::BracketLeft | ToolKey::BracketRight if self.length.is_some() => vec![], ToolKey::Escape | ToolKey::Enter => self.end(), ToolKey::Letter('c') => { if self.last_sharp_arc(cx).is_none() { diff --git a/docs/mcp.md b/docs/mcp.md index 684db1bf60..79ce0bfd6b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7358,7 +7358,8 @@ dragged end stays on its line or circle and does not snap to Smart Guides, and a reach past the canvas. Each drag is one undo step, Escape during the drag takes it back, and the path being drawn goes on from the new end. The pieces of the path being drawn that the drag does not change stay pieces: C and `[` `]` still change the last one. The last piece, dragged by its end, stays -that piece, and as an arc it keeps an arc size of at least 1°. A click on a handle that does not drag is an ordinary +that piece, and as an arc it keeps an arc size of at least 1°. C and `[` `]` do nothing until the drag ends, and the +end goes where the pointer is let go. A click on a handle that does not drag is an ordinary click: it adds a point, closes the path or starts a new one. The handle's place, the 359° limit, the 1° minimum, Escape during a drag, the handles on a selected path and the dragged end not snapping are VectorCraft's own rules. From 01f1ffa4cb0706c9c4a3e762b2780b316cda7b9a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 18:11:43 -0800 Subject: [PATCH 18/78] Quick Pen: choosing the tool again during a length drag keeps the drawing Choosing Quick Pen while a length drag was under way cleared the drawing, so the next preview of the drag carried no path. The drawing is now cleared only when neither a press nor a length drag is active. --- crates/engine/src/tests/quickpen.rs | 21 +++++++++++++++++++++ crates/tools/src/quickpen.rs | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 97591687af..ea01f255d9 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -842,6 +842,27 @@ fn piece_keys_do_nothing_during_a_length_drag() { assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); } +/// Choosing Quick Pen again during a length drag leaves the drawing alone: the drag goes on, ends +/// where the pointer is let go, and the next click goes on drawing the same path. +#[test] +fn choosing_the_tool_again_during_a_length_drag_keeps_the_drawing() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 130.0), v).unwrap(); + quick_pen(&mut s); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 140.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 140.0), v).unwrap(); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0)]); + click(&mut s, 260.0, 200.0); + assert_eq!(paths(&s).len(), 1, "the drawing went on"); + assert_eq!(only_path(&s).anchors.len(), 3); +} + /// A length drag ends where the pointer is let go, also when no drag event came after the press. #[test] fn a_length_drag_ends_at_the_release_point() { diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 7d50150be0..dc613b9946 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -1023,7 +1023,7 @@ impl Tool for QuickPenTool { } fn chosen_again(&mut self, _cx: &ToolContext) -> Vec { - if self.press.is_none() { + if self.press.is_none() && self.length.is_none() { self.drawing = None; } vec![] From 77f0cf29ff10c0c1a9a3ef5347cd5154d9218f69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:13:01 -0800 Subject: [PATCH 19/78] Docs: record Show Opacity in the color area row --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a153dc50e8..6739ef4bfc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -282,7 +282,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | From 018d6c87aa6345a74685764b65262a3f89d2c748 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 07:33:33 -0800 Subject: [PATCH 20/78] Command Palette: the grown-popup test puts the button just under the popup The test placed the toolbar 2 points under the popup, but the button sits lower inside the toolbar, so one more row did not reach it. With the path.quickPenLength command, "pen tool" lists 11 results and "pen" grows the list by one row only, and the test failed. The test now moves the toolbar so the button's top is 2 points under the popup, and checks that the popup does not cover it before the query changes. --- crates/ui-egui/src/palette.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index a3c5fed207..6f2cec11d4 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -5480,7 +5480,13 @@ mod tests { window.frame(vec![]); window.frame(vec![]); assert_eq!(window.highlighted(), "tool:pen"); + // The button goes 2 points below the popup, so one more row covers it. let (outlined, ..) = window.callout().expect("a callout below the popup"); + window.app.ui.custom_toolbars[0].pos[1] += small.bottom() + 2.0 - outlined.top(); + window.frame(vec![]); + window.frame(vec![]); + let (outlined, ..) = window.callout().expect("a callout below the popup"); + assert!(!window.popup().intersects(outlined), "{:?} {outlined:?}", window.popup()); window.app.ui.palette_query = "pen".into(); window.frame(vec![]); assert_eq!(window.highlighted(), "tool:pen"); From 05c8c7df9500964c2ddcdd915f5e6aca03840bc4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 07:55:55 -0800 Subject: [PATCH 21/78] Quick Pen: a length drag that keeps the length records no undo step A drag across a line's length handle leaves the line's length as it was. It started an interaction and previewed the path anyway, so letting go recorded an undo step for an unchanged path. The drag now previews nothing until the length changes. --- crates/engine/src/tests/quickpen.rs | 21 +++++++++++++++++++++ crates/tools/src/quickpen.rs | 4 +++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index ea01f255d9..2d6ba3009f 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -762,6 +762,27 @@ fn a_length_drag_stays_on_the_canvas() { assert_eq!(only_path(&s).anchors.len(), 3, "the drawing went on"); } +/// A length drag across a line, which leaves its length as it was, changes nothing and records no +/// undo step, on the path being drawn and on a selected path. +#[test] +fn a_length_drag_that_keeps_the_length_records_no_undo_step() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + let before = only_path(&s); + // The end handle is at (220, 100); the drag goes straight down from it. + press(&mut s, &[(220.0, 100.0), (220.0, 160.0)]); + assert_eq!(only_path(&s), before); + assert_eq!(undo_steps(&s), undo); + key(&mut s, ToolKey::Escape); + let undo = undo_steps(&s); + press(&mut s, &[(220.0, 100.0), (220.0, 160.0)]); + assert_eq!(only_path(&s), before); + assert_eq!(undo_steps(&s), undo); +} + /// The paths of a selected compound path show length handles, also after a drag selected the /// compound again. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index dc613b9946..109d064407 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -717,7 +717,9 @@ impl QuickPenTool { if !changed.is_some_and(|sp| on_canvas(&sp)) { return vec![]; } - if drag.begun && (length - drag.length).abs() <= 1e-12 * length.max(1.0) { + // A length the end already has changes nothing: no preview, and no undo step before the + // first change. + if (length - drag.length).abs() <= 1e-12 * length.max(1.0) { return vec![]; } let mut out = vec![]; From 5744a52e1e08cb1aca5c20b6e6ce5908109772f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:13:07 -0800 Subject: [PATCH 22/78] Control bar: the narrow-window test checks Crop Image's Apply and Cancel The wide-window case for the Crop Image tool now also expects Apply and Cancel, so the test fails if either button is left out of the Control bar in a wide window. --- crates/ui-egui/src/chrome/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..3a62cd2a23 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -4108,7 +4108,7 @@ fn the_control_bar_s_controls_stay_inside_the_bar_in_a_narrow_window() { wide(&mut app, "an embedded image", &["Unembed…", "Image Trace", "Mask", "Crop Image", "Remove Background"]); app.select_tool(vectorcraft_tools::cropimage::ID); check(&mut app, "Crop Image"); - wide(&mut app, "Crop Image", &["PPI", "X:", "Y:", "W:", "H:"]); + wide(&mut app, "Crop Image", &["PPI", "X:", "Y:", "W:", "H:", "Apply", "Cancel"]); app.select_tool("selection"); app.run("imageTrace.make", json!({"preset": "Default"})).unwrap(); let trace = selected(&app); From f50b903e4afc828bb3943ab09b154c7b2ba20f5a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:25:38 -0800 Subject: [PATCH 23/78] Plug-ins: the host refuses a function type past 32 results before validating code Plugin::load validates every function body with wasmparser before wasmi reads the module, and wasmi's EnforcedLimits::strict() limit of 32 parameters and 32 results per function type applied only after that. A module whose type has 1,000 results could make the validator hold 1,000 operand entries for each call to it. check_features now reads the type section first and refuses a function type with more than 32 parameters or results, with wasmi's message, before any function body is validated. --- crates/plugins/src/runtime.rs | 38 +++++++++++++++++++++++++++++++++-- crates/plugins/tests/abi.rs | 17 ++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 1a25e9e6b0..b4ef0fca25 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -4,7 +4,7 @@ use wasmi::{ Config, CustomFuelCosts, EnforcedLimits, Engine, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, Val, WasmParams, WasmResults, }; -use wasmparser::{Validator, WasmFeatures}; +use wasmparser::{CompositeInnerType, Parser, Payload, Validator, WasmFeatures}; use crate::host::{self, Bridge, Deadline, Host, Report, Run}; use crate::manifest::{MAX_MANIFEST_BYTES, Manifest}; @@ -42,12 +42,46 @@ const WASM_FEATURES: WasmFeatures = WasmFeatures::MUTABLE_GLOBAL .union(WasmFeatures::EXTENDED_CONST) .union(WasmFeatures::FLOATS); +/// The most parameters or results a function type may have: the limit `EnforcedLimits::strict()` +/// sets in wasmi 2.0.0. +const MAX_FUNC_TYPE_VALUES: usize = 32; + /// Validates `bytes` with only [`WASM_FEATURES`] on, before wasmi reads the module. A module that -/// uses any other proposal is refused with the validator's error, which names the proposal. +/// uses any other proposal is refused with the validator's error, which names the proposal. A +/// function type with more than [`MAX_FUNC_TYPE_VALUES`] parameters or results is refused before +/// any function body is validated. fn check_features(bytes: &[u8]) -> Result<()> { + check_func_types(bytes)?; Validator::new_with_features(WASM_FEATURES).validate_all(bytes).map(|_| ()).map_err(|e| Error::Module(e.to_string())) } +/// Refuses a function type in the type section with more than [`MAX_FUNC_TYPE_VALUES`] parameters +/// or results, with wasmi's message. Reading stops at the code section. A section that doesn't +/// parse is left to the validator, which reports it. +fn check_func_types(bytes: &[u8]) -> Result<()> { + for payload in Parser::new(0).parse_all(bytes) { + let types = match payload { + Ok(Payload::TypeSection(types)) => types, + Ok(Payload::CodeSectionStart { .. }) | Err(_) => return Ok(()), + Ok(_) => continue, + }; + for group in types { + let Ok(group) = group else { return Ok(()) }; + for ty in group.types() { + if let CompositeInnerType::Func(f) = &ty.composite_type.inner { + if f.params().len() > MAX_FUNC_TYPE_VALUES { + return Err(Error::Module(format!("a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters"))); + } + if f.results().len() > MAX_FUNC_TYPE_VALUES { + return Err(Error::Module(format!("a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results"))); + } + } + } + } + } + Ok(()) +} + /// Sets each WebAssembly proposal that wasmi's `Config` has a setter for in this build on or off, /// to match [`WASM_FEATURES`]. fn set_features(config: &mut Config) -> &mut Config { diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index ae99846c69..3d359b2a38 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -197,6 +197,23 @@ fn a_plugin_may_use_the_listed_webassembly_proposals_and_no_others() { } } +/// A function type with more than 32 parameters or results is refused before any function body is +/// validated: the module's extra function has an invalid body, and the error names the limit. A +/// type with 32 of each loads. +#[test] +fn a_function_type_past_32_values_is_refused_before_any_function_body_is_validated() { + let i32s = |n: usize| vec!["i32"; n].join(" "); + for (word, field) in [("parameters", "param"), ("results", "result")] { + let fits = module(MANIFEST, tpl::ECHO, &format!("(type (func ({field} {})))", i32s(32))); + assert!(Plugin::load(&fits, Limits::default()).is_ok(), "32 {word}"); + let past = module(MANIFEST, tpl::ECHO, &format!("(type (func ({field} {}))) (func (i32.add))", i32s(33))); + match Plugin::load(&past, Limits::default()) { + Err(Error::Module(m)) => assert_eq!(m, format!("a function type exceeds the limit of 32 {word}")), + other => panic!("33 {word}: {:?}", other.err()), + } + } +} + #[test] fn budgets_stop_runaway_plugins() { let spin = ok_module("(loop $l (br $l)) (i64.const 0)"); From d0689d1f685f1ea78b901604bc84ea1ffde0bcda Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:23:36 -0800 Subject: [PATCH 24/78] Document Info: frames that fetch nothing reuse the cached rows without copying them The panel's document.info cache was read by value on every call, so each frame of the panel deep-copied the whole JSON result even when nothing was fetched, a frame with its menu open copied it once more, and a refresh copied it again to store it. The cache is now an Arc: a frame whose key matches returns the stored result, and a refresh stores the new one without a copy. The key is unchanged (document, revision, Selection Only and, while the Artboard tool is current, its options), a category still filters the stored result, and a failed fetch leaves the stored result in place. Tests: frames_that_fetch_nothing_reuse_the_cached_rows checks that idle frames share one result with the same rows as the by-value read, and that each key change stores a new one; cached_rows_read_timing (ignored) times both reads. --- crates/ui-egui/src/panels/doc_info.rs | 182 ++++++++++++++++++++++++-- docs/target-app-parity.md | 1 + 2 files changed, 169 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index ed6bdcdaab..a71b096a6c 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -3,6 +3,8 @@ //! linked and embedded images, repeat objects), for the whole document or the selection only. The flyout picks one category (or all) //! and saves the text report (`docInfo.save`, the report File → Package writes too). +use std::sync::Arc; + use egui::Ui; use serde_json::{Value, json}; @@ -33,27 +35,30 @@ pub(crate) fn row(ui: &mut Ui, label: &str, value: String) { } /// `document.info` with its categories, fetched again only when the document, the scope or the -/// artboards the Artboard tool has selected change. -fn info(app: &mut VectorcraftApp, ctx: &egui::Context, sel_only: bool) -> Option { +/// artboards the Artboard tool has selected change. A frame that fetches nothing returns the stored +/// cache without copying it and stores nothing; a failed fetch leaves the stored cache as it was. +fn info(app: &mut VectorcraftApp, ctx: &egui::Context, sel_only: bool) -> Option> { let artboard_tool = if app.session.tool_id() == "artboard" { app.session.tool_options_of("artboard") } else { Value::Null }; let st = app.session.active()?; let key = Some((st.uid, st.revision, sel_only, artboard_tool)); - let mut c: Cache = pstate(ctx, "docinfo-cache"); - if c.key != key { - c.info = app.session.execute("document.info", &json!({ "selectionOnly": sel_only })).ok()?; - c.key = key; - set_pstate(ctx, "docinfo-cache", c.clone()); + let c: Arc = pstate(ctx, "docinfo-cache"); + if c.key == key { + return Some(c); } - Some(c.info) + let info = app.session.execute("document.info", &json!({ "selectionOnly": sel_only })).ok()?; + let c = Arc::new(Cache { key, info }); + set_pstate(ctx, "docinfo-cache", c.clone()); + Some(c) } pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let sel_only: bool = pstate(ui.ctx(), "docinfo-sel"); let category: String = pstate(ui.ctx(), "docinfo-category"); - let Some(i) = info(app, ui.ctx(), sel_only) else { + let Some(cache) = info(app, ui.ctx(), sel_only) else { widgets::dim_label(ui, tl!("No document")); return; }; + let i = &cache.info; egui::ScrollArea::vertical().max_height(420.0).show(ui, |ui| { let sections = i["sections"].as_array().map_or(&[][..], Vec::as_slice); let shown = sections.iter().filter(|s| category.is_empty() || s["id"] == category.as_str()); @@ -82,7 +87,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if value.is_empty() { widgets::dim_name(ui, super::label_or_name(label, !named.contains(&k))); } else { - let shown = shown_value(&i, id, k, (label, value), named.contains(&k)).unwrap_or_else(|| value.to_string()); + let shown = shown_value(i, id, k, (label, value), named.contains(&k)).unwrap_or_else(|| value.to_string()); row(ui, super::label_or_name(label, !named.contains(&k)), shown); } } @@ -319,8 +324,8 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("All Categories"), true, category.is_empty()) { set_pstate(ui.ctx(), "docinfo-category", String::new()); } - let info = info(app, ui.ctx(), sel).unwrap_or_default(); - for s in info["sections"].as_array().into_iter().flatten() { + let cache = info(app, ui.ctx(), sel); + for s in cache.as_ref().and_then(|c| c.info["sections"].as_array()).into_iter().flatten() { let (id, title) = (s["id"].as_str().unwrap_or_default(), s["title"].as_str().unwrap_or_default()); if menu_item(ui, title, true, category == id) { set_pstate(ui.ctx(), "docinfo-category", id.to_string()); @@ -661,8 +666,8 @@ mod tests { app.session.execute("artboard.setProps", &json!({"index": 1, "name": "Back"})).unwrap(); let ctx = egui::Context::default(); let document = |app: &mut VectorcraftApp| { - let info = info(app, &ctx, false).unwrap(); - shown_rows(&info, "document") + let cache = info(app, &ctx, false).unwrap(); + shown_rows(&cache.info, "document") }; let value = |rows: &[(String, String)], label: &str| rows.iter().find(|(l, _)| l == label).map(|(_, v)| v.clone()); let english = document(&mut app); @@ -702,6 +707,155 @@ mod tests { assert_eq!(custom.as_deref(), Some("#ff0000, #00ff00")); } + /// `document.info` read as the panel read it before its cache was shared: the stored cache + /// copied out by value on every call, under its own key so it does not touch the panel's. + fn copied_info(app: &mut VectorcraftApp, ctx: &egui::Context, sel_only: bool) -> Option { + let artboard_tool = if app.session.tool_id() == "artboard" { app.session.tool_options_of("artboard") } else { Value::Null }; + let st = app.session.active()?; + let key = Some((st.uid, st.revision, sel_only, artboard_tool)); + let mut c: Cache = pstate(ctx, "docinfo-cache-copied"); + if c.key != key { + c.info = app.session.execute("document.info", &json!({ "selectionOnly": sel_only })).ok()?; + c.key = key; + set_pstate(ctx, "docinfo-cache-copied", c.clone()); + } + Some(c.info) + } + + /// A frame that fetches nothing keeps the stored `document.info` result without a copy, for + /// the panel and its menu, and shows the same rows; another document (at the same revision), an + /// edit, Selection Only and the Artboard tool's options each store a new one, and a category + /// does not. With no document nothing is fetched and the stored result stays as it was. + #[test] + fn frames_that_fetch_nothing_reuse_the_cached_rows() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let old = egui::Context::default(); + let frame = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + show(app, ui); + menu(app, ui); + }); + out.textures_delta.clear(); + let cache: Arc = pstate(&ctx, "docinfo-cache"); + // The rows are the ones the by-value read gives for the same state. + let (sel, has_doc): (bool, bool) = (pstate(&ctx, "docinfo-sel"), app.session.active().is_some()); + assert_eq!(has_doc.then_some(&cache.info), copied_info(app, &old, sel).as_ref(), "the same rows as before"); + (cache, crate::tests_labels::shapes_text(&out)) + }; + let (first, text) = frame(&mut app); + assert!(text.contains("Color Mode") && text.contains("Artboard 1") && text.contains("Save…"), "{text}"); + let (same, again) = frame(&mut app); + assert!(Arc::ptr_eq(&first, &same), "a frame that fetches nothing stores no new cache"); + assert!(Arc::ptr_eq(&info(&mut app, &ctx, false).unwrap(), &same), "the stored result is returned without a copy"); + assert_eq!(text, again); + // Another document at the same revision. + let revision = |app: &VectorcraftApp| app.session.active().map(|st| st.revision); + let at = revision(&app); + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + assert_eq!(revision(&app), at, "both documents are at the same revision"); + let (other, _) = frame(&mut app); + assert!(!Arc::ptr_eq(&same, &other), "another document stores a new cache"); + assert_ne!(other.key.as_ref().map(|k| k.0), same.key.as_ref().map(|k| k.0)); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let (edited, _) = frame(&mut app); + assert!(!Arc::ptr_eq(&other, &edited), "an edit stores a new cache"); + assert!(shown_rows(&edited.info, "objects").contains(&("Paths".into(), "1".into())), "{:?}", shown_rows(&edited.info, "objects")); + set_pstate(&ctx, "docinfo-sel", true); + let (selection, text) = frame(&mut app); + assert!(!Arc::ptr_eq(&edited, &selection), "Selection Only stores a new cache"); + assert!(text.contains("(selection)"), "{text}"); + set_pstate(&ctx, "docinfo-sel", false); + set_pstate(&ctx, "docinfo-category", "objects".to_string()); + let (all, _) = frame(&mut app); + let (category, _) = frame(&mut app); + assert!(Arc::ptr_eq(&all, &category), "a category filters the stored result"); + set_pstate(&ctx, "docinfo-category", String::new()); + app.session.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + let (two, _) = frame(&mut app); + assert!(!Arc::ptr_eq(&category, &two), "a new artboard stores a new cache"); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([0])); + let (tool, _) = frame(&mut app); + assert!(!Arc::ptr_eq(&two, &tool), "the Artboard tool stores a new cache"); + let artboard_rows = |c: &Cache| shown_rows(&c.info, "document").iter().filter(|(l, _)| l == "Artboard").count(); + assert_eq!(artboard_rows(&tool), 1); + app.session.set_tool_option("selected", &json!([0, 1])); + let (picked, _) = frame(&mut app); + assert!(!Arc::ptr_eq(&tool, &picked), "the Artboard tool's options store a new cache"); + assert_eq!(artboard_rows(&picked), 2); + let (kept, _) = frame(&mut app); + assert!(Arc::ptr_eq(&picked, &kept)); + app.select_tool("selection"); + let (away, _) = frame(&mut app); + assert!(!Arc::ptr_eq(&kept, &away), "another tool stores a new cache"); + assert_eq!(away.key.as_ref().map(|k| &k.3), Some(&Value::Null)); + // With no document the panel shows its empty state and keeps the stored result. + app.session.execute("file.close", &json!({})).unwrap(); + app.session.execute("file.close", &json!({})).unwrap(); + let (closed, text) = frame(&mut app); + assert!(Arc::ptr_eq(&away, &closed), "nothing is fetched or stored without a document"); + assert!(text.contains("No document"), "{text}"); + } + + /// Time a frame's read of Document Info's result for a document with 5,000 objects painted + /// with a gradient (a row each): by the by-value read before the cache was shared + /// ([`copied_info`]) and by [`info`]. Per run each side reads 2,000 times; the two sides + /// alternate, and the median time per read of 7 runs is printed, as this thread's CPU time + /// where the system reports it (Linux), else wall-clock time. + /// Run with `cargo test --release -p vectorcraft-ui-egui --lib doc_info::tests::cached_rows_read_timing -- --ignored --nocapture`. + #[test] + #[ignore = "manual timing probe; performance depends on machine load"] + fn cached_rows_read_timing() { + const OBJECTS: usize = 5_000; + const READS: u32 = 2_000; + fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() + } + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 2000, "height": 2000})).unwrap(); + let mut ids = vec![]; + for i in 0..OBJECTS { + let r = json!({"x": i % 100 * 20, "y": i / 100 * 20, "width": 10, "height": 10}); + ids.push(app.session.execute("shape.rectangle", &r).unwrap()["id"].clone()); + } + let ramp = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + app.session.execute("paint.setFill", &json!({"ids": ids, "gradient": ramp})).unwrap(); + let (ctx, old) = (egui::Context::default(), egui::Context::default()); + let rows = info(&mut app, &ctx, false).unwrap().info["sections"] + .as_array() + .into_iter() + .flatten() + .map(|s| s["rows"].as_array().map_or(0, Vec::len)) + .sum::(); + assert_eq!(copied_info(&mut app, &old, false).as_ref(), Some(&info(&mut app, &ctx, false).unwrap().info)); + let mut time = |f: &mut dyn FnMut(&mut VectorcraftApp) -> usize| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + for _ in 0..READS { + assert!(f(&mut app) > 0); + } + let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); + ns as f64 / f64::from(READS) / 1000.0 + }; + let sections = |i: &Value| i["sections"].as_array().map_or(0, Vec::len); + let (mut copied, mut shared) = (vec![], vec![]); + for _ in 0..7 { + copied.push(time(&mut |app| copied_info(app, &old, false).map_or(0, |i| sections(&i)))); + shared.push(time(&mut |app| info(app, &ctx, false).map_or(0, |c| sections(&c.info)))); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; + eprintln!("{OBJECTS} objects, {rows} rows; {clock} per read, median of 7 runs"); + eprintln!("copied ({READS} reads a run): {:>10.3} us {copied:.3?}", median(&mut copied)); + eprintln!("shared ({READS} reads a run): {:>10.3} us {shared:.3?}", median(&mut shared)); + } + /// A Repeat object's counts take each language's plural forms, and a grid that draws fewer /// instances than its rows and columns give is followed by the number it draws. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5e8483f80a..d86c91c36a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2519,6 +2519,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The same 2,000-anchor limit counts each glyph of type as 4 anchors, each point of a gradient mesh as 1 and every 100 pixels of an image as 1, and a symbol instance or a placed document counts the objects and anchors of the art it shows. A placed document whose file has not been read yet, or a symbol nested more than 8 deep (one that holds an instance of itself, for example), gets its first thumbnail on the thumbnail thread, and so does a row whose art takes more than 20,000 steps to count (each object, subpath, text run and symbol looked at is one step). The first frame after the panel opens takes 2.4 ms instead of 19.8 ms with 5,000 glyphs of point type, 1.8 ms instead of 343 ms with one instance of a symbol of a 200,000-anchor path, 2.0 ms instead of 11.0 ms with a 100 × 100 mesh, and 2.1 ms instead of 274 ms with a placed document of a 200,000-anchor path (release build, median of three runs). When the Layers or Links panel shows another document's rows, the thumbnail thread drops the row thumbnails it has not started for the documents not shown, and it drops all of them when the Layers or Links panel is open after the last document closes. Those rows ask for their thumbnails again when their document shows again, and the thumbnails already made are kept. With 150 rows of 20,000-anchor paths waiting for another document, the 8 rows of such paths of the document shown get their thumbnails in 153 ms instead of 3,265 ms (debug test build, median of three runs). The Links panel keeps its `links.list` rows and Link Info in one shared cache, and a frame that fetches nothing new reads that cache without copying the rows. The cache is replaced when the document or its revision changes, the Show, Sort or Show DCS Transparency Interactions option changes, or the files are looked at again every 2 seconds, and, while an image is selected, when Link Info opens or closes or the first selected image changes. With 2,001 images a frame's cache step takes 0.2 µs instead of 1.79 ms, and with 10,001 images 0.2 µs instead of 12.2 ms (test build, median of 7 wall-clock runs of 1,000 frames, measured while other builds were running). + The Document Info panel and its menu keep the panel's `document.info` result in one shared cache, and a frame that fetches nothing new reads that cache without copying the rows. The cache is replaced when the document or its revision changes, Selection Only is turned on or off, or, while the Artboard tool is the current tool, its options change; choosing a category filters the stored result. In the web build, while a pan, zoom or rotation changes the view of a document whose last canvas render took more than 8 ms, the canvas draws the last frame moved with the view, and it renders the art again once the view has been still for 0.2 s. In the web build, an edit while that view moves (a tool drag held near an edge of the canvas, which scrolls the view, or a wheel scroll during a drag) draws only the part of the last frame that the edit changed, at the view that frame was rendered for, and the frame stays drawn moved with the view until the view has been still for 0.2 s (#8688). The part of the canvas a pan uncovers shows the pasteboard and the artboards' paper until then, as for a pan without an edit. Edits that go on after the view stops don't start that 0.2 s again: the whole canvas renders 0.2 s after the view stopped. An edit that changes more than half of the frame, or one while more than the view and the document change, renders the whole canvas at once as before. Tests: `canvas::tests::without_a_worker_a_heavy_canvas_is_reprojected_until_the_view_is_still`, `canvas::tests::without_a_worker_edits_while_the_view_is_still_do_not_hold_off_the_render`. An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429). From 153f6c07500de9d1f875645b6a6809e880d869e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:23:01 -0800 Subject: [PATCH 25/78] Scripts: script.grants reports an error when the grants file cannot be read script.grants listed no grants when Script Grants.json was there but could not be read, was larger than 4 MiB, did not parse, had another version or held no list of grants, or when its lock could not be taken. It now returns "the script file permissions could not be read: {e}" in those cases, as script.grants.revoke already fails on such a file. A missing grants file still lists none, and a grant in the file that is not well formed is still left out. The run-time grant lookup keeps reading such a file as holding no grants. The new message has a row in every complete-message catalog. The params text, docs/mcp.md and the Scripts line in docs/target-app-parity.md state the error. --- crates/engine/src/cmd/scripts.rs | 5 ++-- crates/engine/src/script/files.rs | 21 ++++++++----- crates/engine/src/tests/script_io.rs | 44 ++++++++++++++++++++++++++-- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 4 ++- docs/target-app-parity.md | 2 +- 31 files changed, 89 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index cf46d853d8..42138740d8 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "List Script File Permissions", [], None, - "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}", + "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}; a missing grants file lists none, and one that is there but cannot be read, is too large, is not a grants file of this version or holds no list of grants, or whose lock cannot be taken, is an error (a grant in it that is not well formed is left out)", always, grants ), @@ -369,7 +369,8 @@ fn grants(s: &mut Session, _: &Value) -> Result { let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) }; let file = dir.with_file_name(script::files::GRANTS_FILE); // A script or a granted path outside the automation read roots is named by its file name alone. - let mut grants = script::files::stored_grants(dir); + let mut grants = + script::files::stored_grants(dir).map_err(|e| EngineError::Other(format!("the script file permissions could not be read: {e}")))?; for g in &mut grants { for key in ["script", "path"] { if let Some(name) = g[key].as_str().and_then(hidden_name) { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index c0694bbd81..6e82572d6f 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -912,8 +912,15 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { /// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read /// between two changes, and none are read when the lock cannot be taken. fn read_store(store: &Path) -> Vec { - let Ok(_lock) = lock_store(store) else { return Vec::new() }; - load_store(store, false).unwrap_or_default() + list_store(store).unwrap_or_default() +} + +/// The grants [`read_store`] reads; none when the grants file is missing, and `Err` when the lock +/// cannot be taken or the file is there but cannot be read, is too large, is not a grants file of +/// this version or holds no list of grants. +fn list_store(store: &Path) -> std::io::Result> { + let _lock = lock_store(store)?; + load_store(store, false) } /// The grants the grants file at `store` holds, to change and write back; none when it is missing, @@ -947,14 +954,14 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result MAX_STORED_GRANTS || !grants.iter().all(valid) { return Err(std::io::Error::other("the grants file holds a grant that cannot be read")); } return Ok(grants.clone()); } - Ok(v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default()) + Ok(grants.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()) } /// The number in the name of the next file [`write_store`] writes before it takes the grants file's @@ -1054,9 +1061,9 @@ fn lock_store(_: &Path) -> std::io::Result { } /// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of -/// its text, the path and whether it may be written (`script.grants`). -pub(crate) fn stored_grants(data_dir: &Path) -> Vec { - read_store(&data_dir.with_file_name(GRANTS_FILE)) +/// its text, the path and whether it may be written (`script.grants`); as [`list_store`] reads them. +pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result> { + list_store(&data_dir.with_file_name(GRANTS_FILE)) } /// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 7653dc083d..6fb3d5a4aa 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -635,7 +635,7 @@ fn a_grants_change_without_its_lock_changes_nothing() { } /// Reading and changing the grants file wait for a lock another handle holds only for a bounded -/// number of tries: then a read gives no grants and a change fails with the file unchanged. A lock +/// number of tries: then a listing and a change fail, with the file unchanged. A lock /// released while it waits is taken. #[test] fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { @@ -650,7 +650,8 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { let waits = std::rc::Rc::new(std::cell::Cell::new(0)); let counted = waits.clone(); WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1)))); - assert_eq!(stored_grants(&data), Vec::::new(), "grants are not read without the lock"); + let listed = stored_grants(&data); + assert_eq!(listed.map_err(|e| e.kind()), Err(std::io::ErrorKind::TimedOut), "grants are not listed without the lock"); assert_eq!(waits.get(), LOCK_TRIES - 1); waits.set(0); let refused = revoke_grants(&data, None, None); @@ -1057,6 +1058,45 @@ fn script_file_grants_file_that_cannot_be_read_is_left_as_it_is() { } } +/// `script.grants` fails on a grants file that is there but cannot be read (another version, not +/// JSON, no list of grants, over the size limit or not a file), lists none when it is missing, and +/// lists the well-formed grants of one that holds a grant that is not. +#[test] +fn script_grants_fails_on_a_grants_file_that_cannot_be_read() { + let mut big = b"{\"version\": 1, \"grants\": []}".to_vec(); + big.resize((4 << 20) + 1, b' '); + let cases = [ + ("list-newer", br#"{"version": 2, "grants": []}"#.to_vec()), + ("list-broken", b"{ not json".to_vec()), + ("list-nolist", br#"{"version": 1, "grants": {}}"#.to_vec()), + ("list-big", big), + ]; + for (name, held) in cases { + let base = folder(name); + write(&base.join("settings/Script Grants.json"), &held); + let mut s = with_data(&base); + let e = s.execute("script.grants", &json!({})).unwrap_err().to_string(); + assert!(e.contains("the script file permissions could not be read"), "{name}: {e}"); + let _ = std::fs::remove_dir_all(base); + } + let base = folder("list-folder"); + std::fs::create_dir_all(base.join("settings/Script Grants.json")).unwrap(); + let mut s = with_data(&base); + assert!(s.execute("script.grants", &json!({})).is_err(), "a folder in the grants file's place"); + let _ = std::fs::remove_dir_all(base); + let base = folder("list-missing"); + let mut s = with_data(&base); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([]), "a missing grants file lists none"); + let _ = std::fs::remove_dir_all(base); + let base = folder("list-mixed"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + let text = json!({"version": 1, "grants": [grant, {"script": "x"}]}).to_string(); + write(&base.join("settings/Script Grants.json"), text.as_bytes()); + let mut s = with_data(&base); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1); + let _ = std::fs::remove_dir_all(base); +} + /// `copy` of a file over 8 MiB is refused, as opening one is. #[test] fn script_file_copy_is_held_to_the_file_limit() { diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..3629cb4b54 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6619,6 +6619,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per al diàleg de fitxers d’un script ha de ser un d’aquests: once, always, deny, stop @msg choose a file or folder first, or deny trieu primer un fitxer o una carpeta, o denegueu @msg the script file permissions could not be saved: {e} no s’han pogut desar els permisos de fitxers dels scripts: {e} +@msg the script file permissions could not be read: {e} no s’han pogut llegir els permisos de fitxers dels scripts: {e} @msg this script's file access can be allowed only once l’accés als fitxers d’aquest script només es pot permetre una vegada @msg Only the person at the keyboard can allow a script's file access Només la persona al teclat pot permetre l’accés als fitxers d’un script @msg A script is given at most 2,048 files: the files picked after them were left out Un script rep com a màxim 2.048 fitxers: els fitxers triats després d’aquests s’han deixat fora diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..ef1096f78e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5404,6 +5404,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pro dialog souboru skriptu musí být jedna z hodnot: once, always, deny, stop @msg choose a file or folder first, or deny nejprve vyberte soubor nebo složku, nebo odmítněte @msg the script file permissions could not be saved: {e} oprávnění skriptů k souborům nelze uložit: {e} +@msg the script file permissions could not be read: {e} oprávnění skriptů k souborům nelze načíst: {e} @msg this script's file access can be allowed only once přístup tohoto skriptu k souborům lze povolit jen jednou @msg Only the person at the keyboard can allow a script's file access Přístup skriptu k souborům může povolit jen člověk u klávesnice @msg A script is given at most 2,048 files: the files picked after them were left out Skript dostane nejvýše 2 048 souborů: soubory vybrané po nich byly vynechány diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..f099f75817 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -99,6 +99,7 @@ @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` for et scripts fildialog skal være en af: once, always, deny, stop @msg choose a file or folder first, or deny vælg først en fil eller mappe, eller afvis @msg the script file permissions could not be saved: {e} scriptets filtilladelser kunne ikke gemmes: {e} +@msg the script file permissions could not be read: {e} scriptets filtilladelser kunne ikke læses: {e} @msg this script's file access can be allowed only once dette scripts filadgang kan kun tillades én gang @msg Only the person at the keyboard can allow a script's file access Kun personen ved tastaturet kan tillade et scripts filadgang @msg A script is given at most 2,048 files: the files picked after them were left out Et script får højst 2.048 filer: de filer, der blev valgt derefter, blev udeladt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..6aca3b40a7 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4980,6 +4980,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` für den Dateidialog eines Skripts muss einer der folgenden Werte sein: once, always, deny, stop @msg choose a file or folder first, or deny wählen Sie zuerst eine Datei oder einen Ordner aus oder lehnen Sie ab @msg the script file permissions could not be saved: {e} die Dateiberechtigungen der Skripte konnten nicht gespeichert werden: {e} +@msg the script file permissions could not be read: {e} die Dateiberechtigungen der Skripte konnten nicht gelesen werden: {e} @msg this script's file access can be allowed only once der Dateizugriff dieses Skripts kann nur einmal erlaubt werden @msg Only the person at the keyboard can allow a script's file access Nur die Person an der Tastatur kann den Dateizugriff eines Skripts erlauben @msg A script is given at most 2,048 files: the files picked after them were left out Ein Skript erhält höchstens 2.048 Dateien: Die danach ausgewählten Dateien wurden weggelassen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..f19d07b16e 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2817,6 +2817,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop το `answer` για το παράθυρο διαλόγου αρχείων ενός σεναρίου πρέπει να είναι ένα από: once, always, deny, stop @msg choose a file or folder first, or deny επιλέξτε πρώτα ένα αρχείο ή έναν φάκελο, ή απορρίψτε @msg the script file permissions could not be saved: {e} δεν ήταν δυνατή η αποθήκευση των αδειών αρχείων των σεναρίων: {e} +@msg the script file permissions could not be read: {e} δεν ήταν δυνατή η ανάγνωση των αδειών αρχείων των σεναρίων: {e} @msg this script's file access can be allowed only once η πρόσβαση αυτού του σεναρίου σε αρχεία μπορεί να επιτραπεί μόνο μία φορά @msg Only the person at the keyboard can allow a script's file access Μόνο το άτομο στο πληκτρολόγιο μπορεί να επιτρέψει την πρόσβαση ενός σεναρίου σε αρχεία @msg A script is given at most 2,048 files: the files picked after them were left out Ένα σενάριο λαμβάνει το πολύ 2.048 αρχεία: τα αρχεία που επιλέχθηκαν μετά από αυτά παραλείφθηκαν diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..47d315067c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5091,6 +5091,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para el cuadro de diálogo de archivo de un script debe ser uno de: once, always, deny, stop @msg choose a file or folder first, or deny elija primero un archivo o una carpeta, o deniegue @msg the script file permissions could not be saved: {e} no se pudieron guardar los permisos de archivos de los scripts: {e} +@msg the script file permissions could not be read: {e} no se pudieron leer los permisos de archivos de los scripts: {e} @msg this script's file access can be allowed only once el acceso a archivos de este script solo se puede permitir una vez @msg Only the person at the keyboard can allow a script's file access Solo la persona que está en el teclado puede permitir el acceso a archivos de un script @msg A script is given at most 2,048 files: the files picked after them were left out Un script recibe como máximo 2.048 archivos: los archivos elegidos después de ellos se omitieron diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..d440077877 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5332,6 +5332,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop komentosarjan tiedostovalintaikkunan `answer`-arvon on oltava jokin seuraavista: once, always, deny, stop @msg choose a file or folder first, or deny valitse ensin tiedosto tai kansio tai estä @msg the script file permissions could not be saved: {e} komentosarjojen tiedostolupia ei voitu tallentaa: {e} +@msg the script file permissions could not be read: {e} komentosarjojen tiedostolupia ei voitu lukea: {e} @msg this script's file access can be allowed only once tämän komentosarjan tiedostojen käytön voi sallia vain kerran @msg Only the person at the keyboard can allow a script's file access Vain näppäimistön ääressä oleva ihminen voi sallia komentosarjan tiedostojen käytön @msg A script is given at most 2,048 files: the files picked after them were left out Komentosarja saa enintään 2 048 tiedostoa: niiden jälkeen valitut tiedostot jätettiin pois diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..37f5450b93 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5050,6 +5050,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pour la boîte de dialogue de fichiers d’un script doit être l’une des valeurs : once, always, deny, stop @msg choose a file or folder first, or deny choisissez d’abord un fichier ou un dossier, ou refusez @msg the script file permissions could not be saved: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être enregistrées : {e} +@msg the script file permissions could not be read: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être lues : {e} @msg this script's file access can be allowed only once l’accès aux fichiers de ce script ne peut être autorisé qu’une fois @msg Only the person at the keyboard can allow a script's file access Seule la personne au clavier peut autoriser l’accès aux fichiers d’un script @msg A script is given at most 2,048 files: the files picked after them were left out Un script reçoit au plus 2 048 fichiers : les fichiers choisis après eux ont été laissés de côté diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..b1dc50c8ec 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7766,6 +7766,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop स्क्रिप्ट के फ़ाइल डायलॉग के लिए `answer` इनमें से एक होना चाहिए: once, always, deny, stop @msg choose a file or folder first, or deny पहले कोई फ़ाइल या फ़ोल्डर चुनें, या अस्वीकार करें @msg the script file permissions could not be saved: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ सेव नहीं की जा सकीं: {e} +@msg the script file permissions could not be read: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ पढ़ी नहीं जा सकीं: {e} @msg this script's file access can be allowed only once इस स्क्रिप्ट की फ़ाइल पहुँच केवल एक बार दी जा सकती है @msg Only the person at the keyboard can allow a script's file access किसी स्क्रिप्ट को फ़ाइल पहुँच केवल कीबोर्ड पर मौजूद व्यक्ति दे सकता है @msg A script is given at most 2,048 files: the files picked after them were left out किसी स्क्रिप्ट को अधिकतम 2,048 फ़ाइलें दी जाती हैं: उनके बाद चुनी गई फ़ाइलें छोड़ दी गईं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..c79efb7e00 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5922,6 +5922,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop a parancsfájl fájlpárbeszédpaneléhez tartozó `answer` értéke a következők egyike kell legyen: once, always, deny, stop @msg choose a file or folder first, or deny először válasszon fájlt vagy mappát, vagy utasítsa el @msg the script file permissions could not be saved: {e} a parancsfájlok fájlengedélyeit nem sikerült menteni: {e} +@msg the script file permissions could not be read: {e} a parancsfájlok fájlengedélyeit nem sikerült beolvasni: {e} @msg this script's file access can be allowed only once ennek a parancsfájlnak a fájlhozzáférése csak egyszer engedélyezhető @msg Only the person at the keyboard can allow a script's file access Parancsfájl fájlhozzáférését csak a billentyűzetnél ülő személy engedélyezheti @msg A script is given at most 2,048 files: the files picked after them were left out Egy parancsfájl legfeljebb 2 048 fájlt kap: az ezek után kiválasztott fájlok kimaradtak diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..9fe4b786a2 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8760,6 +8760,7 @@ breakText Glyphs Glif @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` untuk dialog file skrip harus salah satu dari: once, always, deny, stop @msg choose a file or folder first, or deny pilih file atau folder terlebih dahulu, atau tolak @msg the script file permissions could not be saved: {e} izin file skrip tidak dapat disimpan: {e} +@msg the script file permissions could not be read: {e} izin file skrip tidak dapat dibaca: {e} @msg this script's file access can be allowed only once akses file skrip ini hanya dapat diizinkan sekali @msg Only the person at the keyboard can allow a script's file access Hanya orang yang berada di depan keyboard yang dapat mengizinkan akses file skrip @msg A script is given at most 2,048 files: the files picked after them were left out Skrip diberi paling banyak 2.048 file: file yang dipilih sesudahnya dihilangkan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..f2c0f969ae 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5118,6 +5118,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per la finestra di dialogo dei file di uno script deve essere uno tra: once, always, deny, stop @msg choose a file or folder first, or deny scegli prima un file o una cartella, oppure nega @msg the script file permissions could not be saved: {e} impossibile salvare i permessi sui file degli script: {e} +@msg the script file permissions could not be read: {e} impossibile leggere i permessi sui file degli script: {e} @msg this script's file access can be allowed only once l'accesso ai file di questo script può essere consentito solo una volta @msg Only the person at the keyboard can allow a script's file access Solo la persona alla tastiera può consentire l’accesso ai file di uno script @msg A script is given at most 2,048 files: the files picked after them were left out Uno script riceve al massimo 2.048 file: i file scelti dopo questi sono stati esclusi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..69ad3e60a9 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5953,6 +5953,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop スクリプトのファイルダイアログの `answer` は once、always、deny、stop のいずれかにしてください @msg choose a file or folder first, or deny 先にファイルまたはフォルダーを選択するか、拒否してください @msg the script file permissions could not be saved: {e} スクリプトのファイル許可を保存できませんでした: {e} +@msg the script file permissions could not be read: {e} スクリプトのファイル許可を読み込めませんでした: {e} @msg this script's file access can be allowed only once このスクリプトのファイルアクセスは 1 回だけ許可できます @msg Only the person at the keyboard can allow a script's file access スクリプトのファイルアクセスを許可できるのはキーボードの前にいる人だけです @msg A script is given at most 2,048 files: the files picked after them were left out スクリプトに渡せるファイルは 2,048 個までのため、それ以降に選んだファイルは除外されました diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..9e95b57d82 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8614,6 +8614,7 @@ liquify-list-end {0}, {1} {0} და {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop სკრიპტის ფაილის დიალოგისთვის `answer` უნდა იყოს ერთ-ერთი: once, always, deny, stop @msg choose a file or folder first, or deny ჯერ აირჩიეთ ფაილი ან საქაღალდე, ან უარყავით @msg the script file permissions could not be saved: {e} სკრიპტების ფაილების ნებართვების შენახვა ვერ მოხერხდა: {e} +@msg the script file permissions could not be read: {e} სკრიპტების ფაილების ნებართვების წაკითხვა ვერ მოხერხდა: {e} @msg this script's file access can be allowed only once ამ სკრიპტის წვდომა ფაილებზე მხოლოდ ერთხელ შეიძლება დაიშვას @msg Only the person at the keyboard can allow a script's file access სკრიპტის წვდომას ფაილებზე მხოლოდ კლავიატურასთან მყოფი ადამიანი უშვებს @msg A script is given at most 2,048 files: the files picked after them were left out სკრიპტი იღებს მაქსიმუმ 2 048 ფაილს: მათ შემდეგ არჩეული ფაილები გამოტოვებულია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..2bbbda7624 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5882,6 +5882,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop 스크립트 파일 대화 상자의 `answer`는 once, always, deny, stop 중 하나여야 합니다 @msg choose a file or folder first, or deny 먼저 파일이나 폴더를 선택하거나 거부하세요 @msg the script file permissions could not be saved: {e} 스크립트 파일 권한을 저장할 수 없습니다: {e} +@msg the script file permissions could not be read: {e} 스크립트 파일 권한을 읽을 수 없습니다: {e} @msg this script's file access can be allowed only once 이 스크립트의 파일 접근은 한 번만 허용할 수 있습니다 @msg Only the person at the keyboard can allow a script's file access 스크립트의 파일 접근은 키보드 앞에 있는 사람만 허용할 수 있습니다 @msg A script is given at most 2,048 files: the files picked after them were left out 스크립트에는 파일이 최대 2,048개까지 전달됩니다: 그 뒤에 고른 파일은 제외되었습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..6b2a68c565 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -101,6 +101,7 @@ @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` voor het bestandsdialoogvenster van een script moet een van deze waarden zijn: once, always, deny, stop @msg choose a file or folder first, or deny kies eerst een bestand of map, of weiger @msg the script file permissions could not be saved: {e} de toestemmingen voor scriptbestanden konden niet worden opgeslagen: {e} +@msg the script file permissions could not be read: {e} de toestemmingen voor scriptbestanden konden niet worden gelezen: {e} @msg this script's file access can be allowed only once de bestandstoegang van dit script kan maar één keer worden toegestaan @msg Only the person at the keyboard can allow a script's file access Alleen de persoon aan het toetsenbord kan de bestandstoegang van een script toestaan @msg A script is given at most 2,048 files: the files picked after them were left out Een script krijgt maximaal 2.048 bestanden: de bestanden die daarna zijn gekozen, zijn weggelaten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..c1856a9970 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5223,6 +5223,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` dla okna dialogowego plików skryptu musi być jedną z wartości: once, always, deny, stop @msg choose a file or folder first, or deny najpierw wybierz plik lub folder albo odmów @msg the script file permissions could not be saved: {e} nie można zapisać uprawnień skryptów do plików: {e} +@msg the script file permissions could not be read: {e} nie można odczytać uprawnień skryptów do plików: {e} @msg this script's file access can be allowed only once na dostęp tego skryptu do plików można zezwolić tylko raz @msg Only the person at the keyboard can allow a script's file access Na dostęp skryptu do plików może zezwolić tylko osoba przy klawiaturze @msg A script is given at most 2,048 files: the files picked after them were left out Skrypt otrzymuje najwyżej 2 048 plików: pliki wybrane po nich zostały pominięte diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..443d5a08a3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6262,6 +6262,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para a caixa de diálogo de arquivo de um script deve ser um destes: once, always, deny, stop @msg choose a file or folder first, or deny escolha primeiro um arquivo ou uma pasta, ou negue @msg the script file permissions could not be saved: {e} não foi possível salvar as permissões de arquivos dos scripts: {e} +@msg the script file permissions could not be read: {e} não foi possível ler as permissões de arquivos dos scripts: {e} @msg this script's file access can be allowed only once o acesso a arquivos deste script só pode ser permitido uma vez @msg Only the person at the keyboard can allow a script's file access Somente a pessoa ao teclado pode permitir o acesso a arquivos de um script @msg A script is given at most 2,048 files: the files picked after them were left out Um script recebe no máximo 2.048 arquivos: os arquivos escolhidos depois deles foram deixados de fora diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..c443cc2abc 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5113,6 +5113,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового диалога скрипта должен быть одним из: once, always, deny, stop @msg choose a file or folder first, or deny сначала выберите файл или папку либо откажите @msg the script file permissions could not be saved: {e} не удалось сохранить разрешения скриптов на файлы: {e} +@msg the script file permissions could not be read: {e} не удалось прочитать разрешения скриптов на файлы: {e} @msg this script's file access can be allowed only once доступ этого скрипта к файлам можно разрешить только один раз @msg Only the person at the keyboard can allow a script's file access Разрешить скрипту доступ к файлам может только человек за клавиатурой @msg A script is given at most 2,048 files: the files picked after them were left out Скрипт получает не больше 2 048 файлов: файлы, выбранные после них, пропущены diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..6f4d43610b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4989,6 +4989,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` för ett skripts fildialog måste vara ett av: once, always, deny, stop @msg choose a file or folder first, or deny välj först en fil eller mapp, eller neka @msg the script file permissions could not be saved: {e} skriptens filbehörigheter kunde inte sparas: {e} +@msg the script file permissions could not be read: {e} skriptens filbehörigheter kunde inte läsas: {e} @msg this script's file access can be allowed only once det här skriptets filåtkomst kan bara tillåtas en gång @msg Only the person at the keyboard can allow a script's file access Bara personen vid tangentbordet kan tillåta ett skripts filåtkomst @msg A script is given at most 2,048 files: the files picked after them were left out Ett skript får högst 2 048 filer: filerna som valdes efter dem utelämnades diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..43ff3c1060 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2998,6 +2998,7 @@ fn script_file_messages_translate_in_every_complete_message_language() { "`answer` for a script's file dialog must be one of: once, always, deny, stop", "choose a file or folder first, or deny", "the script file permissions could not be saved: {e}", + "the script file permissions could not be read: {e}", "this script's file access can be allowed only once", "Only the person at the keyboard can allow a script's file access", ]; diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..791d0315c9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4825,6 +4825,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop bir betiğin dosya iletişim kutusu için `answer` şunlardan biri olmalıdır: once, always, deny, stop @msg choose a file or folder first, or deny önce bir dosya veya klasör seçin ya da reddedin @msg the script file permissions could not be saved: {e} betiklerin dosya izinleri kaydedilemedi: {e} +@msg the script file permissions could not be read: {e} betiklerin dosya izinleri okunamadı: {e} @msg this script's file access can be allowed only once bu betiğin dosya erişimine yalnızca bir kez izin verilebilir @msg Only the person at the keyboard can allow a script's file access Bir betiğin dosya erişimine yalnızca klavye başındaki kişi izin verebilir @msg A script is given at most 2,048 files: the files picked after them were left out Bir betiğe en fazla 2.048 dosya verilir: bunlardan sonra seçilen dosyalar dışarıda bırakıldı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..82716438da 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5102,6 +5102,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового діалогу скрипту має бути одним із: once, always, deny, stop @msg choose a file or folder first, or deny спершу виберіть файл або папку чи відмовте @msg the script file permissions could not be saved: {e} не вдалося зберегти дозволи скриптів на файли: {e} +@msg the script file permissions could not be read: {e} не вдалося прочитати дозволи скриптів на файли: {e} @msg this script's file access can be allowed only once доступ цього скрипту до файлів можна дозволити лише один раз @msg Only the person at the keyboard can allow a script's file access Дозволити скрипту доступ до файлів може лише людина за клавіатурою @msg A script is given at most 2,048 files: the files picked after them were left out Скрипт отримує щонайбільше 2 048 файлів: файли, вибрані після них, пропущено diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..b8febfab67 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5612,6 +5612,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` cho hộp thoại tệp của tập lệnh phải là một trong: once, always, deny, stop @msg choose a file or folder first, or deny hãy chọn một tệp hoặc thư mục trước, hoặc từ chối @msg the script file permissions could not be saved: {e} không thể lưu quyền truy cập tệp của các tập lệnh: {e} +@msg the script file permissions could not be read: {e} không thể đọc quyền truy cập tệp của các tập lệnh: {e} @msg this script's file access can be allowed only once quyền truy cập tệp của tập lệnh này chỉ có thể được cho phép một lần @msg Only the person at the keyboard can allow a script's file access Chỉ người ngồi tại bàn phím mới có thể cho phép tập lệnh truy cập tệp @msg A script is given at most 2,048 files: the files picked after them were left out Một tập lệnh nhận tối đa 2.048 tệp: các tệp được chọn sau đó đã bị bỏ qua diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..cb29c519aa 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5609,6 +5609,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop 脚本文件对话框的 `answer` 必须是以下之一:once、always、deny、stop @msg choose a file or folder first, or deny 请先选择文件或文件夹,或拒绝 @msg the script file permissions could not be saved: {e} 无法保存脚本的文件权限:{e} +@msg the script file permissions could not be read: {e} 无法读取脚本的文件权限:{e} @msg this script's file access can be allowed only once 此脚本的文件访问只能允许一次 @msg Only the person at the keyboard can allow a script's file access 只有键盘前的人才能允许脚本访问文件 @msg A script is given at most 2,048 files: the files picked after them were left out 脚本最多获得 2,048 个文件:之后选择的文件已被略去 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..57aae8f6ad 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2964,6 +2964,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg `answer` for a script's file dialog must be one of: once, always, deny, stop 指令碼檔案對話框的 `answer` 必須是下列之一:once、always、deny、stop @msg choose a file or folder first, or deny 請先選擇檔案或資料夾,或拒絕 @msg the script file permissions could not be saved: {e} 無法儲存指令碼的檔案權限:{e} +@msg the script file permissions could not be read: {e} 無法讀取指令碼的檔案權限:{e} @msg this script's file access can be allowed only once 此指令碼的檔案存取只能允許一次 @msg Only the person at the keyboard can allow a script's file access 只有鍵盤前的人才能允許指令碼存取檔案 @msg A script is given at most 2,048 files: the files picked after them were left out 指令碼最多取得 2,048 個檔案:之後選擇的檔案已略去 diff --git a/docs/mcp.md b/docs/mcp.md index bdaad51e11..dd459e292d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3034,7 +3034,9 @@ is given as its file name alone. `script.grants.revoke {script?, path?, all?}` r a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but -cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. A script +cannot be read is left as it is: `script.grants` and `script.grants.revoke` fail, and a grant picked with Always is +not kept. A missing grants file lists no grants, and `script.grants` leaves out a grant in the file that is not well +formed. A script cannot run either command. ```json diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5b85e0c926..87bc7b9e06 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1039,7 +1039,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. + - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants (it fails when the grants file is there but cannot be read) and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From 9145bd3203551c04dc50d840df1f38d54623133b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:29:07 -0800 Subject: [PATCH 26/78] i18n: translate the function type limit messages The plug-in host's two new messages for a function type past 32 parameters or results get @msg rows in every complete-message catalog. --- crates/ui-egui/src/i18n/ca.tsv | 2 ++ crates/ui-egui/src/i18n/cs.tsv | 2 ++ crates/ui-egui/src/i18n/da.tsv | 2 ++ crates/ui-egui/src/i18n/de.tsv | 2 ++ crates/ui-egui/src/i18n/el.tsv | 2 ++ crates/ui-egui/src/i18n/es.tsv | 2 ++ crates/ui-egui/src/i18n/fi.tsv | 2 ++ crates/ui-egui/src/i18n/fr.tsv | 2 ++ crates/ui-egui/src/i18n/hi.tsv | 2 ++ crates/ui-egui/src/i18n/hu.tsv | 2 ++ crates/ui-egui/src/i18n/id.tsv | 2 ++ crates/ui-egui/src/i18n/it.tsv | 2 ++ crates/ui-egui/src/i18n/ja.tsv | 2 ++ crates/ui-egui/src/i18n/ka.tsv | 2 ++ crates/ui-egui/src/i18n/ko.tsv | 2 ++ crates/ui-egui/src/i18n/nl.tsv | 2 ++ crates/ui-egui/src/i18n/pl.tsv | 2 ++ crates/ui-egui/src/i18n/pt-br.tsv | 2 ++ crates/ui-egui/src/i18n/ru.tsv | 2 ++ crates/ui-egui/src/i18n/sv.tsv | 2 ++ crates/ui-egui/src/i18n/tr.tsv | 2 ++ crates/ui-egui/src/i18n/uk.tsv | 2 ++ crates/ui-egui/src/i18n/vi.tsv | 2 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 2 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 2 ++ 25 files changed, 50 insertions(+) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..7c6e483c5e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7712,6 +7712,8 @@ variable-list-end {0}, {1} {0} i {1} @msg needs approval: it asks for {0}, which the user grants when installing it on its own cal aprovació: demana {0}, que l’usuari concedeix en instal·lar-lo per separat @msg not JSON: {e} no és JSON: {e} @msg not a WebAssembly binary (missing \0asm header) no és un binari WebAssembly (falta la capçalera \0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters un tipus de funció supera el límit de {MAX_FUNC_TYPE_VALUES} paràmetres +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results un tipus de funció supera el límit de {MAX_FUNC_TYPE_VALUES} resultats @msg parameter `{k}`: {what} paràmetre `{k}`: {what} @msg parameter `{name}`: {what} paràmetre `{name}`: {what} @msg plug-in parameters must be a JSON object els paràmetres del complement han de ser un objecte JSON diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..d2a40c970a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7323,6 +7323,8 @@ axis Y Axis osa Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own vyžaduje schválení: žádá o {0}, což uživatel povolí, když ho instaluje samostatně @msg not JSON: {e} není JSON: {e} @msg not a WebAssembly binary (missing \0asm header) není binární soubor WebAssembly (chybí hlavička \0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters typ funkce má více parametrů, než dovoluje limit ({MAX_FUNC_TYPE_VALUES}) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results typ funkce má více výsledků, než dovoluje limit ({MAX_FUNC_TYPE_VALUES}) @msg parameter `{k}`: {what} parametr `{k}`: {what} @msg parameter `{name}`: {what} parametr `{name}`: {what} @msg plug-in parameters must be a JSON object parametry zásuvného modulu musí být objekt JSON diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..b6586d9ae4 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -553,6 +553,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg needs approval: it asks for {0}, which the user grants when installing it on its own kræver godkendelse: det beder om {0}, som brugeren tildeler, når det installeres for sig selv @msg not JSON: {e} ikke JSON: {e} @msg not a WebAssembly binary (missing \0asm header) ikke en WebAssembly-binærfil (headeren \0asm mangler) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters en funktionstype overskrider grænsen på {MAX_FUNC_TYPE_VALUES} parametre +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results en funktionstype overskrider grænsen på {MAX_FUNC_TYPE_VALUES} resultater @msg parameter `{k}`: {what} parameteren `{k}`: {what} @msg parameter `{name}`: {what} parameteren `{name}`: {what} @msg plug-in parameters must be a JSON object plug-in-parametrene skal være et JSON-objekt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..09806eac66 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6906,6 +6906,8 @@ axis Y Axis Y-Achse @msg needs approval: it asks for {0}, which the user grants when installing it on its own muss genehmigt werden: Es verlangt {0}, was der Benutzer gewährt, wenn er es einzeln installiert @msg not JSON: {e} kein JSON: {e} @msg not a WebAssembly binary (missing \0asm header) keine WebAssembly-Binärdatei (der Header \0asm fehlt) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters ein Funktionstyp überschreitet die Grenze von {MAX_FUNC_TYPE_VALUES} Parametern +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results ein Funktionstyp überschreitet die Grenze von {MAX_FUNC_TYPE_VALUES} Ergebnissen @msg parameter `{k}`: {what} Parameter `{k}`: {what} @msg parameter `{name}`: {what} Parameter `{name}`: {what} @msg plug-in parameters must be a JSON object die Plug-in-Parameter müssen ein JSON-Objekt sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..4929d6e70b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7312,6 +7312,8 @@ axis Y Axis Άξονας Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own χρειάζεται έγκριση: ζητά {0}, που ο χρήστης παραχωρεί όταν το εγκαθιστά μόνο του @msg not JSON: {e} δεν είναι JSON: {e} @msg not a WebAssembly binary (missing \0asm header) δεν είναι δυαδικό αρχείο WebAssembly (λείπει η κεφαλίδα \0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters ένας τύπος συνάρτησης υπερβαίνει το όριο των {MAX_FUNC_TYPE_VALUES} παραμέτρων +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results ένας τύπος συνάρτησης υπερβαίνει το όριο των {MAX_FUNC_TYPE_VALUES} αποτελεσμάτων @msg parameter `{k}`: {what} παράμετρος `{k}`: {what} @msg parameter `{name}`: {what} παράμετρος `{name}`: {what} @msg plug-in parameters must be a JSON object οι παράμετροι του προσθέτου πρέπει να είναι αντικείμενο JSON diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..66cf6b4501 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7298,6 +7298,8 @@ axis Y Axis Eje Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own requiere aprobación: pide {0}, que el usuario concede al instalarlo por separado @msg not JSON: {e} no es JSON: {e} @msg not a WebAssembly binary (missing \0asm header) no es un binario WebAssembly (falta el encabezado \0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters un tipo de función supera el límite de {MAX_FUNC_TYPE_VALUES} parámetros +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results un tipo de función supera el límite de {MAX_FUNC_TYPE_VALUES} resultados @msg parameter `{k}`: {what} parámetro `{k}`: {what} @msg parameter `{name}`: {what} parámetro `{name}`: {what} @msg plug-in parameters must be a JSON object los parámetros del plugin deben ser un objeto JSON diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..d8b93cb3d7 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7389,6 +7389,8 @@ axis Y Axis Y-akseli @msg needs approval: it asks for {0}, which the user grants when installing it on its own vaatii hyväksynnän: se pyytää {0}, jotka käyttäjä myöntää asentaessaan sen erikseen @msg not JSON: {e} ei JSON-muotoa: {e} @msg not a WebAssembly binary (missing \0asm header) ei WebAssembly-binääri (\0asm-otsake puuttuu) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters funktiotyyppi ylittää {MAX_FUNC_TYPE_VALUES} parametrin rajan +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results funktiotyyppi ylittää {MAX_FUNC_TYPE_VALUES} tuloksen rajan @msg parameter `{k}`: {what} parametri `{k}`: {what} @msg parameter `{name}`: {what} parametri `{name}`: {what} @msg plug-in parameters must be a JSON object laajennuksen parametrien on oltava JSON-objekti diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..d4a7c957fe 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7319,6 +7319,8 @@ axis Y Axis Axe Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own approbation requise : il demande {0}, que l’utilisateur accorde en l’installant seul @msg not JSON: {e} pas du JSON : {e} @msg not a WebAssembly binary (missing \0asm header) pas un binaire WebAssembly (en-tête \0asm absent) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters un type de fonction dépasse la limite de {MAX_FUNC_TYPE_VALUES} paramètres +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results un type de fonction dépasse la limite de {MAX_FUNC_TYPE_VALUES} résultats @msg parameter `{k}`: {what} paramètre `{k}` : {what} @msg parameter `{name}`: {what} paramètre `{name}` : {what} @msg plug-in parameters must be a JSON object les paramètres du plug-in doivent être un objet JSON diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..551485671f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8627,6 +8627,8 @@ liquify-list-end {0}, {1} {0} और {1} @msg not a VectorCraft file: {0} एक वेक्टर क्रेफ्ट फ़ाइल नहीं: {0} @msg not a VectorCraft shortcut set (missing `overrides`) एक VectorCraft शॉर्टकट सेट नहीं है ( `overrides`) @msg not a WebAssembly binary (missing \0asm header) WebAssembly बाइनरी नहीं है (\0asm हेडर नहीं है) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters एक फ़ंक्शन टाइप में {MAX_FUNC_TYPE_VALUES} पैरामीटर की सीमा से अधिक पैरामीटर हैं +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results एक फ़ंक्शन टाइप में {MAX_FUNC_TYPE_VALUES} परिणामों की सीमा से अधिक परिणाम हैं @msg not a Word document: its compound file has no WordDocument stream एक वर्ड डॉक्यूमेंट नहीं: इसकी यौगिक फ़ाइल में WordDocument स्ट्रीम नहीं है @msg not a Word document: its main part is not a WordprocessingML document वर्ड डॉक्यूमेंट नहीं: इसका मुख्य हिस्सा वर्डप्रोसेसिंगएमएल डॉक्यूमेंट नहीं है @msg not a Word document: its package has no main document part नहीं एक वर्ड डॉक्यूमेंट: इसके पैकेज में कोई मुख्य डॉक्यूमेंट हिस्सा नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..0f3dee608d 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7308,6 +7308,8 @@ axis Y Axis Y tengely @msg needs approval: it asks for {0}, which the user grants when installing it on its own jóváhagyás szükséges: ezt kéri: {0}, amit a felhasználó a külön telepítéskor ad meg @msg not JSON: {e} nem JSON: {e} @msg not a WebAssembly binary (missing \0asm header) nem WebAssembly bináris (hiányzik a \0asm fejléc) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters egy függvénytípus paramétereinek száma meghaladja a korlátot ({MAX_FUNC_TYPE_VALUES}) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results egy függvénytípus eredményeinek száma meghaladja a korlátot ({MAX_FUNC_TYPE_VALUES}) @msg parameter `{k}`: {what} `{k}` paraméter: {what} @msg parameter `{name}`: {what} `{name}` paraméter: {what} @msg plug-in parameters must be a JSON object a bővítmény paraméterei JSON-objektumot alkossanak diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..08a01d40ea 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -436,6 +436,8 @@ @msg needs approval: it asks for {0}, which the user grants when installing it on its own memerlukan persetujuan: plug-in meminta {0}, yang diberikan pengguna saat memasangnya sendiri @msg not JSON: {e} bukan JSON: {e} @msg not a WebAssembly binary (missing \0asm header) bukan biner WebAssembly (header \0asm tidak ada) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters sebuah tipe fungsi melampaui batas {MAX_FUNC_TYPE_VALUES} parameter +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results sebuah tipe fungsi melampaui batas {MAX_FUNC_TYPE_VALUES} hasil @msg parameter `{k}`: {what} parameter `{k}`: {what} @msg parameter `{name}`: {what} parameter `{name}`: {what} @msg plug-in parameters must be a JSON object parameter plug-in harus berupa objek JSON diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..cc18d25069 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6945,6 +6945,8 @@ axis Y Axis Asse Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own richiede approvazione: chiede {0}, che l’utente concede installandolo da solo @msg not JSON: {e} non è JSON: {e} @msg not a WebAssembly binary (missing \0asm header) non è un binario WebAssembly (manca l’intestazione \0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters un tipo di funzione supera il limite di {MAX_FUNC_TYPE_VALUES} parametri +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results un tipo di funzione supera il limite di {MAX_FUNC_TYPE_VALUES} risultati @msg parameter `{k}`: {what} parametro `{k}`: {what} @msg parameter `{name}`: {what} parametro `{name}`: {what} @msg plug-in parameters must be a JSON object i parametri del plug-in devono essere un oggetto JSON diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..375ce34283 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7020,6 +7020,8 @@ axis Y Axis Y 軸 @msg needs approval: it asks for {0}, which the user grants when installing it on its own 承認が必要です: {0} を要求しています。これはユーザーが単独でインストールするときに許可します @msg not JSON: {e} JSON ではありません: {e} @msg not a WebAssembly binary (missing \0asm header) WebAssembly バイナリではありません (\0asm ヘッダーがありません) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters 関数型のパラメーター数が上限の {MAX_FUNC_TYPE_VALUES} 個を超えています +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results 関数型の結果の数が上限の {MAX_FUNC_TYPE_VALUES} 個を超えています @msg parameter `{k}`: {what} パラメーター `{k}`: {what} @msg parameter `{name}`: {what} パラメーター `{name}`: {what} @msg plug-in parameters must be a JSON object プラグインのパラメーターは JSON オブジェクトにしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..6fe5a59035 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9425,6 +9425,8 @@ axis Y Axis Y ღერძი @msg needs approval: it asks for {0}, which the user grants when installing it on its own საჭიროებს დამტკიცებას: ითხოვს {0}-ს, რასაც მომხმარებელი მისი ცალკე დაყენებისას აძლევს @msg not JSON: {e} არ არის JSON: {e} @msg not a WebAssembly binary (missing \0asm header) არ არის WebAssembly-ის ბინარული ფაილი (აკლია \0asm სათაური) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters ფუნქციის ტიპი აჭარბებს {MAX_FUNC_TYPE_VALUES} პარამეტრის ლიმიტს +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results ფუნქციის ტიპი აჭარბებს {MAX_FUNC_TYPE_VALUES} შედეგის ლიმიტს @msg parameter `{k}`: {what} პარამეტრი `{k}`: {what} @msg parameter `{name}`: {what} პარამეტრი `{name}`: {what} @msg plug-in parameters must be a JSON object პლაგინის პარამეტრები JSON ობიექტი უნდა იყოს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..2dcdb8ea71 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6917,6 +6917,8 @@ axis Y Axis Y축 @msg needs approval: it asks for {0}, which the user grants when installing it on its own 승인이 필요합니다. {0}을(를) 요청하며, 사용자가 따로 설치할 때 허용합니다 @msg not JSON: {e} JSON이 아닙니다: {e} @msg not a WebAssembly binary (missing \0asm header) WebAssembly 바이너리가 아닙니다(\0asm 헤더 없음) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters 함수 형식의 매개변수가 한도인 {MAX_FUNC_TYPE_VALUES}개를 초과합니다 +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results 함수 형식의 결과가 한도인 {MAX_FUNC_TYPE_VALUES}개를 초과합니다 @msg parameter `{k}`: {what} 매개변수 `{k}`: {what} @msg parameter `{name}`: {what} 매개변수 `{name}`: {what} @msg plug-in parameters must be a JSON object 플러그인 매개변수는 JSON 개체여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..5fafbeae05 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -400,6 +400,8 @@ liquify-list-end {0}, {1} {0} en {1} @msg needs approval: it asks for {0}, which the user grants when installing it on its own goedkeuring nodig: de plug-in vraagt om {0}, wat de gebruiker toestaat wanneer hij die afzonderlijk installeert @msg not JSON: {e} geen JSON: {e} @msg not a WebAssembly binary (missing \0asm header) geen WebAssembly-binair bestand (de header \0asm ontbreekt) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters een functietype overschrijdt de limiet van {MAX_FUNC_TYPE_VALUES} parameters +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results een functietype overschrijdt de limiet van {MAX_FUNC_TYPE_VALUES} resultaten @msg parameter `{k}`: {what} parameter `{k}`: {what} @msg parameter `{name}`: {what} parameter `{name}`: {what} @msg plug-in parameters must be a JSON object plug-in-parameters moeten een JSON-object zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..d24e8cc661 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7178,6 +7178,8 @@ axis Y Axis Oś Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own wymaga zatwierdzenia: prosi o {0}, na co użytkownik zezwala, instalując ją osobno @msg not JSON: {e} to nie jest JSON: {e} @msg not a WebAssembly binary (missing \0asm header) to nie jest plik binarny WebAssembly (brak nagłówka \0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters typ funkcji ma więcej parametrów, niż pozwala limit ({MAX_FUNC_TYPE_VALUES}) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results typ funkcji ma więcej wyników, niż pozwala limit ({MAX_FUNC_TYPE_VALUES}) @msg parameter `{k}`: {what} parametr `{k}`: {what} @msg parameter `{name}`: {what} parametr `{name}`: {what} @msg plug-in parameters must be a JSON object parametry wtyczki muszą być obiektem JSON diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..72534e65e3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7222,6 +7222,8 @@ axis Y Axis Eixo Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own precisa de aprovação: pede {0}, que o usuário concede ao instalá-lo separadamente @msg not JSON: {e} não é JSON: {e} @msg not a WebAssembly binary (missing \0asm header) não é um binário WebAssembly (falta o cabeçalho \0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters um tipo de função excede o limite de {MAX_FUNC_TYPE_VALUES} parâmetros +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results um tipo de função excede o limite de {MAX_FUNC_TYPE_VALUES} resultados @msg parameter `{k}`: {what} parâmetro `{k}`: {what} @msg parameter `{name}`: {what} parâmetro `{name}`: {what} @msg plug-in parameters must be a JSON object os parâmetros do plug-in devem ser um objeto JSON diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..c402c3e823 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6944,6 +6944,8 @@ axis Y Axis Ось Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own требуется одобрение: он запрашивает {0}, что пользователь разрешает при отдельной установке @msg not JSON: {e} не JSON: {e} @msg not a WebAssembly binary (missing \0asm header) не двоичный файл WebAssembly (нет заголовка \0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters у типа функции больше параметров, чем допускает предел ({MAX_FUNC_TYPE_VALUES}) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results у типа функции больше результатов, чем допускает предел ({MAX_FUNC_TYPE_VALUES}) @msg parameter `{k}`: {what} параметр `{k}`: {what} @msg parameter `{name}`: {what} параметр `{name}`: {what} @msg plug-in parameters must be a JSON object параметры модуля должны быть объектом JSON diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..f57c9afa61 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9617,6 +9617,8 @@ digits Hindi Hindi @msg not a stored or deflated central record inte en central katalogpost av typen stored eller deflated @msg not a valid SVGZ file: {e} inte en giltig SVGZ-fil: {e} @msg not a WebAssembly binary (missing \0asm header) inte en WebAssembly-binärfil (huvudet \0asm saknas) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters en funktionstyp överskrider gränsen på {MAX_FUNC_TYPE_VALUES} parametrar +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results en funktionstyp överskrider gränsen på {MAX_FUNC_TYPE_VALUES} resultat @msg not a Word document: its compound file has no WordDocument stream inte ett Word-dokument: dess sammansatta fil saknar WordDocument-ström @msg not a Word document: its main part is not a WordprocessingML document inte ett Word-dokument: dess huvuddel är inte ett WordprocessingML-dokument @msg not a Word document: its package has no main document part inte ett Word-dokument: dess paket saknar huvuddokumentdel diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..fb653fdc7d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7395,6 +7395,8 @@ axis Y Axis Y ekseni @msg needs approval: it asks for {0}, which the user grants when installing it on its own onay gerekiyor: {0} istiyor; kullanıcı bunu eklentiyi tek başına yüklerken verir @msg not JSON: {e} JSON değil: {e} @msg not a WebAssembly binary (missing \0asm header) WebAssembly ikili dosyası değil (\0asm üst bilgisi eksik) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters bir işlev türü {MAX_FUNC_TYPE_VALUES} parametre sınırını aşıyor +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results bir işlev türü {MAX_FUNC_TYPE_VALUES} sonuç sınırını aşıyor @msg parameter `{k}`: {what} `{k}` parametresi: {what} @msg parameter `{name}`: {what} `{name}` parametresi: {what} @msg plug-in parameters must be a JSON object eklenti parametreleri bir JSON nesnesi olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..fc20d3c298 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6927,6 +6927,8 @@ axis Y Axis Вісь Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own потрібне схвалення: він запитує {0}, що користувач дозволяє під час окремого встановлення @msg not JSON: {e} не JSON: {e} @msg not a WebAssembly binary (missing \0asm header) не двійковий файл WebAssembly (немає заголовка \0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters тип функції має більше параметрів, ніж дозволяє межа ({MAX_FUNC_TYPE_VALUES}) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results тип функції має більше результатів, ніж дозволяє межа ({MAX_FUNC_TYPE_VALUES}) @msg parameter `{k}`: {what} параметр `{k}`: {what} @msg parameter `{name}`: {what} параметр `{name}`: {what} @msg plug-in parameters must be a JSON object параметри модуля мають бути об’єктом JSON diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..6fdbc3cd15 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6973,6 +6973,8 @@ axis Y Axis Trục Y @msg needs approval: it asks for {0}, which the user grants when installing it on its own cần phê duyệt: plug-in yêu cầu {0}, quyền mà người dùng cấp khi cài đặt riêng plug-in đó @msg not JSON: {e} không phải JSON: {e} @msg not a WebAssembly binary (missing \0asm header) không phải tệp nhị phân WebAssembly (thiếu phần đầu \0asm) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters một kiểu hàm vượt quá giới hạn {MAX_FUNC_TYPE_VALUES} tham số +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results một kiểu hàm vượt quá giới hạn {MAX_FUNC_TYPE_VALUES} kết quả @msg parameter `{k}`: {what} tham số `{k}`: {what} @msg parameter `{name}`: {what} tham số `{name}`: {what} @msg plug-in parameters must be a JSON object tham số plug-in phải là một đối tượng JSON diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..19a065a127 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7155,6 +7155,8 @@ axis Y Axis Y 轴 @msg needs approval: it asks for {0}, which the user grants when installing it on its own 需要批准:它请求 {0},用户单独安装它时授予这些权限 @msg not JSON: {e} 不是 JSON:{e} @msg not a WebAssembly binary (missing \0asm header) 不是 WebAssembly 二进制文件(缺少 \0asm 头) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters 函数类型的参数数目超过上限({MAX_FUNC_TYPE_VALUES} 个) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results 函数类型的结果数目超过上限({MAX_FUNC_TYPE_VALUES} 个) @msg parameter `{k}`: {what} 参数 `{k}`:{what} @msg parameter `{name}`: {what} 参数 `{name}`:{what} @msg plug-in parameters must be a JSON object 增效工具参数必须是 JSON 对象 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..11e085c7c4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6976,6 +6976,8 @@ axis Y Axis Y 軸 @msg needs approval: it asks for {0}, which the user grants when installing it on its own 需要核准:它要求 {0},使用者單獨安裝它時授予這些權限 @msg not JSON: {e} 不是 JSON:{e} @msg not a WebAssembly binary (missing \0asm header) 不是 WebAssembly 二進位檔(沒有 \0asm 標頭) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters 函式型別的參數數目超過上限({MAX_FUNC_TYPE_VALUES} 個) +@msg a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results 函式型別的結果數目超過上限({MAX_FUNC_TYPE_VALUES} 個) @msg parameter `{k}`: {what} 參數 `{k}`:{what} @msg parameter `{name}`: {what} 參數 `{name}`:{what} @msg plug-in parameters must be a JSON object 增效模組參數必須是 JSON 物件 From 3785bc8b76d0437d6f2435f231e6441bb7668f46 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:39:23 -0800 Subject: [PATCH 27/78] Place: an empty password keeps a placed PDF linked with PDF Text at Outlines file.place reads an empty or null password as no password, but the app counted any password key as given. A PDF placed from a path with Link on and an empty password then took the PDF Text preference's Outlines and was embedded instead of linked. With Show Import Options off, an encrypted PDF placed with an empty password skipped the password prompt and went to file.place without a password. Both checks now read the password the way file.place does. --- crates/ui-egui/src/dialogs/import_pdf.rs | 18 +++++--- .../ui-egui/src/dialogs/tests_import_pdf.rs | 44 +++++++++++++++++++ docs/mcp.md | 4 +- 3 files changed, 59 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index b14cba49cd..c9ef6d6a67 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -189,12 +189,19 @@ pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool { offer(app, &name, &bytes, path, Some(p)) } +/// Whether the `file.place` params `p` give a password. `file.place` reads an empty or null +/// `password` as none; a value that isn't text counts as given, for `file.place` to refuse. +fn gives_password(p: &Value) -> bool { + p.get("password").is_some_and(|v| !v.is_null() && v.as_str() != Some("")) +} + /// [`offer_place`] when Show Import Options is off: asks (true) only for the password of an -/// encrypted PDF given no `password`, which nothing else opens, and places its first page (or -/// `page`) and crop box once it is unlocked; any other PDF is placed that way without asking. +/// encrypted PDF given no password (see [`gives_password`]), which nothing else opens, and places +/// its first page (or `page`) and crop box once it is unlocked; any other PDF is placed that way +/// without asking. pub fn offer_place_password(app: &mut VectorcraftApp, p: &Value) -> bool { // A `page` that isn't a page number is left for `file.place` to refuse. - if p.get("password").is_some() || p.get("page").is_some_and(|v| v.as_u64().is_none_or(|n| n == 0)) { + if gives_password(p) || p.get("page").is_some_and(|v| v.as_u64().is_none_or(|n| n == 0)) { return false; } let Some((name, bytes, path)) = place_source(app, p, |ext| matches!(ext, "pdf" | "ai" | "ait")) else { return false }; @@ -267,12 +274,13 @@ pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[ /// The `file.place` params `p` of a PDF the user places embedded (Link off, from bytes or with a /// password) get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no /// `textAs`. A linked page shows the file's own text, and a `.ai` or `.ait` file is placed as it -/// says. +/// says. An empty `password` is none, so a place from a path with Link on and an empty +/// `password` stays linked. pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) { let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); let path = p.get("path").and_then(Value::as_str); let name = path.or_else(|| p.get("name").and_then(Value::as_str)).unwrap_or_default(); - let linked = path.is_some() && p.get("link").and_then(Value::as_bool) != Some(false) && !given("password"); + let linked = path.is_some() && p.get("link").and_then(Value::as_bool) != Some(false) && !gives_password(p); if given("textAs") || linked || preferred_text_as(app) == TextAs::Text || fileio::extension(name) != "pdf" { return; } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 06bdf5e1b7..0f0cb30a1e 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -491,3 +491,47 @@ fn the_text_choice_applies_to_embedded_places_only() { assert!(!matches!(placed.kind, NodeKind::PlacedDocument(_)), "embedded: {:?}", placed.kind); assert_eq!(type_objects(&app), before, "placed as outlines"); } + +/// `file.place` reads an empty or null `password` as none: a place from a path with Link on stays +/// linked with the PDF Text preference at Outlines, and only a password that is given embeds it. +#[test] +fn an_empty_password_keeps_a_place_linked() { + let mut app = app(); + set_pdf_text(&mut app, "outlines"); + let dir = vectorcraft_testkit::TempDir::new("import-pdf-empty-password"); + let path = dir.join("one.pdf").to_string_lossy().into_owned(); + std::fs::write(&path, text_pages(1)).unwrap(); + for password in [json!(""), json!(null)] { + let mut p = json!({"path": path, "password": password}); + import_pdf::place_with_preferred_text_as(&app, &mut p); + assert_eq!(p, json!({"path": path, "password": password}), "no textAs with password {password}"); + } + let mut p = json!({"path": path, "password": "pw"}); + import_pdf::place_with_preferred_text_as(&app, &mut p); + assert_eq!(p["textAs"], "outlines", "a password embeds the page"); + + crate::place::run_for_user(&mut app, &json!({"path": path, "password": ""})).unwrap(); + opened(&mut app); + let st = app.session.active().unwrap(); + let placed = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(matches!(placed.kind, NodeKind::PlacedDocument(_)), "linked: {:?}", placed.kind); +} + +/// With Show Import Options off, an encrypted PDF placed with an empty `password` asks for its +/// password, as one placed without `password` does; a password that is given goes to `file.place`. +#[test] +fn an_empty_password_still_asks_for_the_password() { + let mut app = app(); + let bytes = pdf(&[PdfPage::new(120.0, 60.0, "1 0 0 rg 0 0 20 20 re f")], Some("pw")); + let data = vectorcraft_format::base64_encode(&bytes); + for password in [json!(""), json!(null)] { + app.ui.dialog = None; + let p = json!({"name": "locked.pdf", "dataBase64": data, "password": password}); + assert!(import_pdf::offer_place_password(&mut app, &p), "asks with password {password}"); + assert_eq!((field(&app, "__locked"), field(&app, "__passwordOnly")), (json!(true), json!(true))); + } + app.ui.dialog = None; + let p = json!({"name": "locked.pdf", "dataBase64": data, "password": "pw"}); + assert!(!import_pdf::offer_place_password(&mut app, &p), "a given password is placed with"); + assert!(app.ui.dialog.is_none()); +} diff --git a/docs/mcp.md b/docs/mcp.md index 3cb8d1d239..49e9b808d1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8982,7 +8982,7 @@ unless `link: false`; a Photoshop document as its merged image), an SVG as one g and swatches it uses. A VectorCraft document read from `path` is a placed document: one locked object showing its artboard `page` (or, with `crop: "bounding"`, its art's bounds), linked to the file and read again when it changes (see Linked images), and vectors in every output; with `link: false` (or from `dataBase64`) it is an editable copy -of its art, as one clipped group. A PDF, `.ai` or `.ait` page read from `path` (with neither `password` nor +of its art, as one clipped group. A PDF, `.ai` or `.ait` page read from `path` (with neither a non-empty `password` nor `textAs: "outlines"`) is a placed document the same way, showing page `page` clipped to its `crop` box (or its art's bounds); with `link: false` it is placed as one clipped group. An EPS file, a PostScript file or a PostScript `.ai` read from `path` is a placed document too, showing the art `link: false` places (clipped to its bounding box, or its art's bounds with `crop: "bounding"`); @@ -9055,7 +9055,7 @@ slices (Place PSD). `showImportOptions: false` places such a file without asking its dialog: the text options, the DXF fit, lineweight, centering and layer choices with the drawing at 1:1 in its own unit, and the PSD conversion, hidden-layer and Import Slices choices. A PDF is placed on page 1 (or `page`) and its crop box, and an encrypted PDF given no -`password` still asks for the password. An encrypted PDF given a `page` and no `password` asks for the password with +`password` (or an empty one) still asks for the password. An encrypted PDF given a `page` and no `password` asks for the password with Show Import Options on too, and places that page. A `showImportOptions` that is not true or false is refused, and nothing is placed. The Place dialog (File › Place, or `file.place {paths}`) has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). From cd4ac68c09bc3e55439e6b777e26d6015bcaae54 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:05:34 -0800 Subject: [PATCH 28/78] Document Info: Linked Images and Embedded Images show each image's format, resolution and memory MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Linked Images row now gives the image's format, its size in pixels, its resolution at the size it is placed at and its file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`, both axes when they differ, `resolution unavailable` when the transform leaves the image no area). An Embedded Images row gives the format, the size and the estimated memory of the 8-bit RGBA pixels the image is drawn from (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`). The format comes from a linked file's extension, else from the type of the pixels the document holds, and reads `Unknown format` when neither is known. document.info's imageObjects entries gain format, effectivePpi, memoryBytes and storedBytes (the encoded bytes an embedded image keeps). The Document Info report and Package's report write the same rows, and the panel shows them in the interface language, with the new templates in every complete catalog. --- crates/engine/src/cmd.rs | 5 +- crates/engine/src/cmd/docinfo.rs | 261 ++++++++++++++++++++++++-- crates/ui-egui/src/i18n/bg.tsv | 6 + crates/ui-egui/src/i18n/bs.tsv | 6 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/gu.tsv | 6 + crates/ui-egui/src/i18n/hi.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tests.rs | 12 +- crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + crates/ui-egui/src/panels/doc_info.rs | 77 +++++++- docs/mcp.md | 12 +- docs/target-app-parity.md | 1 + 34 files changed, 507 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..b982b0d48f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -845,8 +845,9 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; /// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. pub use addons::{fold_source, print_hidden}; -/// Document Info's category titles and the Objects category's count labels. -pub use docinfo::{CATEGORIES, OBJECT_LABELS}; +/// Document Info's category titles, the Objects category's count labels, and how its image rows +/// write a resolution and a number of bytes. +pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number}; pub use docmenu::guide_indexes; pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index bb22ae5c16..3fa7cce615 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", has_doc, info ), @@ -183,8 +183,123 @@ fn count_fonts(fonts: &mut BTreeMap, t: &vectorcr } } -/// An image object as Document Info lists it: (name, width, height, linked file). -type ImageRow = (String, u32, u32, Option); +/// An image object as Linked Images or Embedded Images lists it. +struct ImageRow { + name: String, + width: u32, + height: u32, + /// What a linked image's row names: its file's path, or the file's name alone when the request + /// may not read it. `None` for an embedded image. + file: Option, + /// The image's format ([`image_format`]); `None` when it is not known. + format: Option<&'static str>, + /// The pixels per inch across and down at the size the image is placed at; `None` when its + /// transform flattens it. + ppi: Option<[f64; 2]>, + /// For an embedded image, the bytes its pixels take when drawn (8-bit RGBA: width × height × 4). + memory: Option, + /// For an embedded image, the bytes of the encoded image the document holds. + stored: Option, +} + +impl ImageRow { + /// Image object `n` (image `im`) of `d`, `file` the row value of its link. + fn of(d: &Document, n: &Node, im: &vectorcraft_doc::ImageObject, file: Option) -> Self { + let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string()); + // A distorted image is measured at its middle, as `image.info` measures it. + let xf = vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf); + let ppi = super::place::effective_ppi(xf); + // A transform that lays both pixel axes on one line leaves the image no area. + let has_area = xf.determinant().abs() > 1e-12; + let embedded = im.link.is_none(); + let memory = || u64::from(im.width).checked_mul(u64::from(im.height))?.checked_mul(4); + Self { + name, + width: im.width, + height: im.height, + file, + format: image_format(d, im), + ppi: (has_area && ppi.iter().all(|v| *v > 0.0 && v.is_finite())).then_some(ppi), + memory: if embedded { memory() } else { None }, + stored: if embedded { d.images.get(&im.key).map(|b| b.bytes.len() as u64) } else { None }, + } + } + + /// The row's value: the format, the size in pixels, and for a linked image its resolution and + /// file, for an embedded one the memory its pixels take. + fn value(&self) -> String { + let format = self.format.unwrap_or("Unknown format"); + let size = format!("{} × {} px", self.width, self.height); + match &self.file { + Some(file) => { + let ppi = match self.ppi { + Some([x, y]) if ppi_number(x) == ppi_number(y) => format!("{} ppi", ppi_number(x)), + Some([x, y]) => format!("{} × {} ppi", ppi_number(x), ppi_number(y)), + None => "resolution unavailable".into(), + }; + format!("{format}; {size}; {ppi} — {file}") + } + None => { + let memory = self.memory.map_or_else(|| "memory unavailable".to_string(), |b| format!("estimated memory {}", byte_size(b))); + format!("{format}; {size}; {memory}") + } + } + } + + /// The row's `imageObjects` entry. + fn entry(&self) -> Value { + json!({ + "name": self.name, + "width": self.width, + "height": self.height, + "linked": self.file.is_some(), + "file": self.file, + "format": self.format, + "effectivePpi": self.ppi, + "memoryBytes": self.memory, + "storedBytes": self.stored, + }) + } +} + +/// The format of image `im` of `d`, as the Links panel names it: for a linked image its file's, by +/// its extension (DCS for a separated one), else the type of the pixels the document holds for it; +/// `None` when neither names a known format. +fn image_format(d: &Document, im: &vectorcraft_doc::ImageObject) -> Option<&'static str> { + use super::fileio; + if im.link.is_some() && d.images.get(&im.key).is_some_and(vectorcraft_doc::ImageBlob::is_separated) { + return Some("DCS"); + } + im.link + .as_ref() + .and_then(|l| fileio::format_for_name(l.name()).or_else(|| fileio::readable_format_for_name(l.name()))) + .or_else(|| d.images.get(&im.key).and_then(|b| fileio::FORMATS.iter().find(|f| f.raster && f.mime == b.mime))) + .map(|f| f.label) +} + +/// A resolution as Document Info shows it: rounded to a tenth (below 1, to a hundredth), without a +/// trailing `.0`. +pub fn ppi_number(ppi: f64) -> String { + let k = if ppi.abs() < 1.0 { 100.0 } else { 10.0 }; + format!("{}", (ppi * k).round() / k) +} + +/// A number of bytes as Document Info shows it: in B below 1 KiB, else in KiB, MiB or GiB rounded +/// to a tenth. +pub fn byte_size(bytes: u64) -> String { + const UNITS: [&str; 3] = ["KiB", "MiB", "GiB"]; + if bytes < 1024 { + return format!("{bytes} B"); + } + let mut v = bytes as f64 / 1024.0; + let mut unit = 0; + // 1023.96 KiB is shown as 1 MiB rather than as 1024 KiB. + while v >= 1023.95 && unit + 1 < UNITS.len() { + v /= 1024.0; + unit += 1; + } + format!("{} {}", (v * 10.0).round() / 10.0, UNITS[unit]) +} /// A Repeat object as Document Info lists it: its `repeatObjects` entry, and its row, which gives /// its name and then its kind with the number of instances it draws (for a grid, its rows and @@ -337,11 +452,9 @@ fn sections( "symbols" => names("symbols"), "fonts" => fonts.to_vec(), "fontDetails" => font_details.to_vec(), - "linkedImages" => { - images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect() - } + "linkedImages" => images.iter().filter(|i| i.file.is_some()).map(|i| (i.name.clone(), i.value())).collect(), "repeats" => repeats.to_vec(), - _ => images.iter().filter(|i| i.3.is_none()).map(|(name, w, h, _)| (name.clone(), format!("{w} × {h} px"))).collect(), + _ => images.iter().filter(|i| i.file.is_none()).map(|i| (i.name.clone(), i.value())).collect(), }; Section { id, title, rows } }) @@ -753,8 +866,8 @@ fn info(s: &mut Session, p: &Value) -> Result { im.key.clone(), json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": link.and_then(|(l, ok)| ok.then_some(&l.path)) }), ); - let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string()); - image_rows.push((name, im.width, im.height, link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() }))); + let file = link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() }); + image_rows.push(ImageRow::of(d, n, im, file)); Some("images") } NodeKind::SymbolInstance { symbol, .. } => { @@ -835,13 +948,8 @@ fn info(s: &mut Session, p: &Value) -> Result { let font_names: Vec = fonts.keys().map(super::fonts::font_label).collect(); let (font_uses, font_use_rows): (Vec, Vec<(String, String)>) = fonts.iter().map(|(f, n)| font_use(f, *n)).unzip(); let (font_entries, font_rows): (Vec, Vec<(String, String)>) = fonts.keys().map(font_detail).unzip(); - // The image objects in walk order, as Linked Images and Embedded Images list them: `file` is a - // linked image's row value (its path, or its file name alone when the request may not read it), - // and null for an embedded one. - let image_objects: Vec = image_rows - .iter() - .map(|(name, w, h, file)| json!({ "name": name, "width": w, "height": h, "linked": file.is_some(), "file": file })) - .collect(); + // The image objects in walk order, as Linked Images and Embedded Images list them. + let image_objects: Vec = image_rows.iter().map(ImageRow::entry).collect(); // Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the first of two // brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type // as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them. @@ -2246,11 +2354,130 @@ mod tests { assert_eq!(objects.len(), 2, "{objects:?}"); for (o, r) in objects.iter().zip(&embedded) { assert_eq!((o["linked"].clone(), o["file"].clone(), o["name"].clone()), (json!(false), Value::Null, r[0].clone()), "{o}"); - assert_eq!(r[1], format!("{} × {} px", o["width"], o["height"])); + let memory = byte_size(o["memoryBytes"].as_u64().unwrap()); + assert_eq!(r[1], format!("{}; {} × {} px; estimated memory {memory}", o["format"].as_str().unwrap(), o["width"], o["height"])); } assert!(section("linkedImages").is_empty()); } + /// An image object to place: (key, MIME type, linked path, width, height, transform). + type Placed<'a> = (&'a str, &'a str, Option<&'a str>, u32, u32, Affine); + + /// Image objects `images` placed in a new document, with a blob of `100 + n` bytes of type + /// `mime` for each new key; their ids in order. + fn images_in(s: &mut Session, images: &[Placed]) -> Vec { + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.edit("Place", |d, _| { + let mut ids = vec![]; + for (n, (key, mime, link, width, height, xf)) in images.iter().enumerate() { + if !d.images.contains_key(*key) { + d.images.insert((*key).into(), vectorcraft_doc::ImageBlob::new(*mime, vec![0; 100 + n])); + } + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: (*key).into(), + width: *width, + height: *height, + xf: *xf, + link: link.map(vectorcraft_doc::LinkInfo::new), + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), usize::MAX, Node::new(id, NodeKind::Image(Box::new(im))))?; + ids.push(id); + } + Ok(ids) + }) + .unwrap() + } + + /// Linked Images gives each linked image's format, size in pixels, resolution at the size it is + /// placed at and file, and Embedded Images each embedded image's format, size and the memory + /// its pixels take; `imageObjects` gives the same facts with the bytes the document holds for an + /// embedded image, the text report writes the same rows, and Selection Only lists the selected + /// images alone. + #[test] + fn image_rows_give_format_resolution_and_memory() { + let mut s = Session::new(); + let half = Affine::scale(0.5); + let ids = images_in( + &mut s, + &[ + ("a", "image/png", None, 1200, 800, half), + ("b", "image/jpeg", None, 10, 10, half), + ("c", "image/x-unheard-of", None, 3, 2, half), + ("a", "image/png", Some("/art/photo.png"), 1200, 800, Affine::scale(0.48)), + ("a", "image/png", Some("/art/photo.png"), 1200, 800, Affine::scale(0.24)), + ("a", "image/png", Some("/art/wide.png"), 1200, 800, Affine::scale_non_uniform(0.5, 1.0)), + ("a", "image/png", Some("/art/scan.tif"), 1200, 800, half), + ("a", "image/png", Some("/art/flat.png"), 1200, 800, Affine::scale_non_uniform(0.5, 0.0)), + // Both pixel axes on one line: neither has length 0, but the image has no area. + ("a", "image/png", Some("/art/line.png"), 1200, 800, Affine::new([0.5, 0.5, 1.0, 1.0, 0.0, 0.0])), + ("c", "image/x-unheard-of", Some("/art/odd.qqq"), 3, 2, half), + ], + ); + let i = s.execute("document.info", &json!({})).unwrap(); + let rows = |i: &Value, id: &str| -> Vec<(String, String)> { + let section = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == id).unwrap().clone(); + section["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().into(), r[1].as_str().unwrap().into())).collect() + }; + let embedded = rows(&i, "embeddedImages"); + let values: Vec<&str> = embedded.iter().map(|(_, v)| v.as_str()).collect(); + assert_eq!( + values, + [ + "PNG; 1200 × 800 px; estimated memory 3.7 MiB", + "JPEG; 10 × 10 px; estimated memory 400 B", + "Unknown format; 3 × 2 px; estimated memory 24 B" + ] + ); + let linked = rows(&i, "linkedImages"); + assert_eq!( + linked, + [ + ("photo.png", "PNG; 1200 × 800 px; 150 ppi — /art/photo.png"), + ("photo.png", "PNG; 1200 × 800 px; 300 ppi — /art/photo.png"), + ("wide.png", "PNG; 1200 × 800 px; 144 × 72 ppi — /art/wide.png"), + ("scan.tif", "TIFF; 1200 × 800 px; 144 ppi — /art/scan.tif"), + ("flat.png", "PNG; 1200 × 800 px; resolution unavailable — /art/flat.png"), + ("line.png", "PNG; 1200 × 800 px; resolution unavailable — /art/line.png"), + ("odd.qqq", "Unknown format; 3 × 2 px; 144 ppi — /art/odd.qqq"), + ] + .map(|(a, b)| (a.to_string(), b.to_string())) + ); + let objects = i["imageObjects"].as_array().unwrap(); + assert_eq!(objects.len(), 10); + assert_eq!( + (objects[0]["format"].clone(), objects[0]["effectivePpi"].clone(), objects[0]["memoryBytes"].clone(), objects[0]["storedBytes"].clone()), + (json!("PNG"), json!([144.0, 144.0]), json!(1200 * 800 * 4), json!(100)) + ); + assert_eq!((objects[1]["format"].clone(), objects[1]["storedBytes"].clone()), (json!("JPEG"), json!(101))); + assert_eq!(objects[2]["format"], Value::Null); + // A linked image gives no memory and no stored bytes: the document holds only its preview. + assert_eq!((objects[3]["memoryBytes"].clone(), objects[3]["storedBytes"].clone()), (Value::Null, Value::Null)); + let ppi = |o: &Value| -> Vec { o["effectivePpi"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect() }; + assert!(ppi(&objects[3]).iter().all(|v| (v - 150.0).abs() < 1e-9), "{}", objects[3]); + assert_eq!(ppi(&objects[5]), [144.0, 72.0]); + assert_eq!((objects[7]["effectivePpi"].clone(), objects[8]["effectivePpi"].clone()), (Value::Null, Value::Null)); + let text = s.execute("document.info", &json!({"format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(text.contains("\nphoto.png: PNG; 1200 × 800 px; 150 ppi — /art/photo.png\n"), "{text}"); + assert!(text.contains(": JPEG; 10 × 10 px; estimated memory 400 B\n"), "{text}"); + // Selection Only lists the selected images alone, with the same rows. + s.execute("select.set", &json!({"ids": [ids[1].0, ids[5].0]})).unwrap(); + let selected = s.execute("document.info", &json!({"selectionOnly": true})).unwrap(); + assert_eq!(rows(&selected, "embeddedImages").iter().map(|(_, v)| v.as_str()).collect::>(), [values[1]]); + assert_eq!(rows(&selected, "linkedImages"), [linked[2].clone()]); + } + + /// A number of bytes reads in B below 1 KiB, else in KiB, MiB or GiB to a tenth, and a + /// resolution to a tenth without a trailing `.0`. + #[test] + fn byte_sizes_and_resolutions_read_to_a_tenth() { + let shown = [0, 1023, 1024, 1536, 1024 * 1024 - 1, 3_840_000, 5 << 30, u64::MAX].map(byte_size); + assert_eq!(shown, ["0 B", "1023 B", "1 KiB", "1.5 KiB", "1 MiB", "3.7 MiB", "5 GiB", "17179869184 GiB"]); + assert_eq!([150.0, 72.0 / 0.48, 205.714, 0.04, 0.001].map(ppi_number), ["150", "150", "205.7", "0.04", "0"]); + } + /// A `gradientObjects` entry's `kinds` gives the kind of each gradient listed by its kind /// rather than by a swatch, and null for a swatch's name, even one that reads like a kind and /// one an object's gradient of that kind shares; a type object's characters count as its own. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..d5a95bcab3 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2384,6 +2384,12 @@ font-technology Variable Променливи {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable разделителната способност не е налична + estimated memory {memory} приблизителна памет {memory} + memory unavailable паметта не е налична + Unknown format Неизвестен формат {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..2c4a1b1af2 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3676,6 +3676,12 @@ theme Appearance Izgled {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable rezolucija nije dostupna + estimated memory {memory} procijenjena memorija {memory} + memory unavailable memorija nije dostupna + Unknown format Nepoznat format {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..b14773be36 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3434,6 +3434,12 @@ digits Malayalam Malaiàlam {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppp + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppp + resolution unavailable resolució no disponible + estimated memory {memory} memòria estimada {memory} + memory unavailable memòria no disponible + Unknown format Format desconegut {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..ea9616e3e8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3777,6 +3777,12 @@ theme Appearance Motiv {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable rozlišení není k dispozici + estimated memory {memory} odhadovaná paměť {memory} + memory unavailable paměť není k dispozici + Unknown format Neznámý formát {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..f6ab620948 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6257,6 +6257,12 @@ theme Appearance Udseende {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable opløsning ikke tilgængelig + estimated memory {memory} anslået hukommelse {memory} + memory unavailable hukommelse ikke tilgængelig + Unknown format Ukendt format {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..0c8638678e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2435,6 +2435,12 @@ file-filter Templates Vorlagen {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable Auflösung nicht verfügbar + estimated memory {memory} geschätzter Speicher {memory} + memory unavailable Speicher nicht verfügbar + Unknown format Unbekanntes Format {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..054a383f16 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2088,6 +2088,12 @@ font-technology Variable Μεταβλητές {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}· {size}· {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable η ανάλυση δεν είναι διαθέσιμη + estimated memory {memory} εκτιμώμενη μνήμη {memory} + memory unavailable η μνήμη δεν είναι διαθέσιμη + Unknown format Άγνωστη μορφή {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..4452cc4269 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2478,6 +2478,12 @@ font-technology Variable Variables {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppp + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppp + resolution unavailable resolución no disponible + estimated memory {memory} memoria estimada {memory} + memory unavailable memoria no disponible + Unknown format Formato desconocido {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..1aea0986ec 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3714,6 +3714,12 @@ theme Appearance Ulkoasu {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable tarkkuus ei saatavilla + estimated memory {memory} arvioitu muisti {memory} + memory unavailable muisti ei saatavilla + Unknown format Tuntematon muoto {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..254605d5d9 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2466,6 +2466,12 @@ font-technology Variable Variables {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppp + {format}; {size}; {detail} {format}, {size}, {detail} + {x} × {y} ppi {x} × {y} ppp + resolution unavailable résolution indisponible + estimated memory {memory} mémoire estimée {memory} + memory unavailable mémoire indisponible + Unknown format Format inconnu {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..f93a5fcbd1 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -5205,6 +5205,12 @@ antiAlias Sharp શાર્પ {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable રિઝોલ્યુશન ઉપલબ્ધ નથી + estimated memory {memory} અંદાજિત મેમરી {memory} + memory unavailable મેમરી ઉપલબ્ધ નથી + Unknown format અજ્ઞાત ફોર્મેટ {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..af755e78b8 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3979,6 +3979,12 @@ arrowhead Feather पंख {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable रिज़ॉल्यूशन उपलब्ध नहीं + estimated memory {memory} अनुमानित मेमोरी {memory} + memory unavailable मेमोरी उपलब्ध नहीं + Unknown format अज्ञात फ़ॉर्मेट {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..7083da40c7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3316,6 +3316,12 @@ file-filter Templates Sablonok {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable a felbontás nem érhető el + estimated memory {memory} becsült memória {memory} + memory unavailable a memória nem érhető el + Unknown format Ismeretlen formátum {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..fcec930ddb 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4125,6 +4125,12 @@ theme Appearance Tampilan {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable resolusi tidak tersedia + estimated memory {memory} perkiraan memori {memory} + memory unavailable memori tidak tersedia + Unknown format Format tidak dikenal {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..71090e837c 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2520,6 +2520,12 @@ file-filter Templates Modelli {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable risoluzione non disponibile + estimated memory {memory} memoria stimata {memory} + memory unavailable memoria non disponibile + Unknown format Formato sconosciuto {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..31829a6420 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2703,6 +2703,12 @@ antiAlias Sharp シャープ {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}、{size}、{detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable 解像度を取得できません + estimated memory {memory} 推定メモリ {memory} + memory unavailable メモリを取得できません + Unknown format 不明な形式 {kind}, {instances} {kind}、{instances} {kind}, {rows} × {cols} {kind}、{rows} × {cols} {grid}, {instances} {grid}、{instances} diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..93f789283a 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5535,6 +5535,12 @@ theme Appearance იერსახე {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable გარჩევადობა მიუწვდომელია + estimated memory {memory} სავარაუდო მეხსიერება {memory} + memory unavailable მეხსიერება მიუწვდომელია + Unknown format უცნობი ფორმატი {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..d6fd74c8e0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2693,6 +2693,12 @@ antiAlias Sharp 날카롭게 {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable 해상도를 알 수 없음 + estimated memory {memory} 예상 메모리 {memory} + memory unavailable 메모리를 알 수 없음 + Unknown format 알 수 없는 형식 {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..7845581267 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4123,6 +4123,12 @@ theme Appearance Vormgeving {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable resolutie niet beschikbaar + estimated memory {memory} geschat geheugen {memory} + memory unavailable geheugen niet beschikbaar + Unknown format Onbekend formaat {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..623933886e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3656,6 +3656,12 @@ theme Appearance Wygląd {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable rozdzielczość niedostępna + estimated memory {memory} szacowana pamięć {memory} + memory unavailable pamięć niedostępna + Unknown format Nieznany format {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..58a550f076 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2015,6 +2015,12 @@ antiAlias Sharp Nítido {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppp + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppp + resolution unavailable resolução indisponível + estimated memory {memory} memória estimada {memory} + memory unavailable memória indisponível + Unknown format Formato desconhecido {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..1895437037 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2504,6 +2504,12 @@ file-filter Templates Шаблоны {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable разрешение недоступно + estimated memory {memory} оценка памяти {memory} + memory unavailable память недоступна + Unknown format Неизвестный формат {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..a0e47b46e6 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2406,6 +2406,12 @@ font-technology Variable Variabla {width} × {height} px {width} × {height} px {size} — {file} {size} – {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable upplösning inte tillgänglig + estimated memory {memory} uppskattat minne {memory} + memory unavailable minne inte tillgängligt + Unknown format Okänt format {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..cbb18c3798 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1061,12 +1061,12 @@ fn document_info_labels_are_in_complete_catalogs() { } /// The values Document Info makes and shows in the interface language: the font states and -/// embedding permissions, the templates of the font, image, raster effects and Repeat object -/// values, the names of gradients named by their kind, the counted uses, instances, rows and +/// embedding permissions, the templates of the font, image (format, size, resolution and memory), +/// raster effects and Repeat object values, the names of gradients named by their kind, the counted uses, instances, rows and /// columns, and the transparency settings' values. #[test] fn document_info_values_are_in_complete_catalogs() { - const VALUES: [&str; 22] = [ + const VALUES: [&str; 28] = [ "unknown type", "{type}; {uses}", "built in", @@ -1081,6 +1081,12 @@ fn document_info_values_are_in_complete_catalogs() { "{width} × {height} px", "{size} — {file}", "{n} ppi", + "{format}; {size}; {detail}", + "{x} × {y} ppi", + "resolution unavailable", + "estimated memory {memory}", + "memory unavailable", + "Unknown format", "{kind}, {instances}", "{kind}, {rows} × {cols}", "{grid}, {instances}", diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..738d515da3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7178,6 +7178,12 @@ theme Appearance Görünüm {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable çözünürlük kullanılamıyor + estimated memory {memory} tahmini bellek {memory} + memory unavailable bellek kullanılamıyor + Unknown format Bilinmeyen biçim {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..d8c2962759 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2512,6 +2512,12 @@ file-filter Templates Шаблони {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable роздільна здатність недоступна + estimated memory {memory} орієнтовна пам’ять {memory} + memory unavailable пам’ять недоступна + Unknown format Невідомий формат {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..ae621eed62 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3139,6 +3139,12 @@ digits Hindi Hindi {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format}; {size}; {detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable không có độ phân giải + estimated memory {memory} bộ nhớ ước tính {memory} + memory unavailable không có thông tin bộ nhớ + Unknown format Định dạng không xác định {kind}, {instances} {kind}, {instances} {kind}, {rows} × {cols} {kind}, {rows} × {cols} {grid}, {instances} {grid}, {instances} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..7775f4b94f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2367,6 +2367,12 @@ file-filter Templates 模板 {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format};{size};{detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable 分辨率不可用 + estimated memory {memory} 估计内存 {memory} + memory unavailable 内存不可用 + Unknown format 未知格式 {kind}, {instances} {kind},{instances} {kind}, {rows} × {cols} {kind},{rows} × {cols} {grid}, {instances} {grid},{instances} diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..6037d96a62 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3805,6 +3805,12 @@ liquify-list-end {0}, {1} {0}和{1} {width} × {height} px {width} × {height} px {size} — {file} {size} — {file} {n} ppi {n} ppi + {format}; {size}; {detail} {format};{size};{detail} + {x} × {y} ppi {x} × {y} ppi + resolution unavailable 解析度無法使用 + estimated memory {memory} 估計記憶體 {memory} + memory unavailable 記憶體無法使用 + Unknown format 未知格式 {kind}, {instances} {kind},{instances} {kind}, {rows} × {cols} {kind},{rows} × {cols} {grid}, {instances} {grid},{instances} diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index ed6bdcdaab..99cc22b59a 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -226,11 +226,32 @@ fn font_detail_value(e: &Value) -> Option { } } -/// An `imageObjects` entry as Linked Images and Embedded Images show it: its size in pixels, and -/// for a linked image the file it shows. +/// An `imageObjects` entry as Linked Images and Embedded Images show it: its format, its size in +/// pixels, and for a linked image its resolution and the file it shows, for an embedded one the +/// memory its pixels take. Format names and file names stay as they are. fn image_value(o: &Value) -> Option { + use vectorcraft_engine::cmd::{byte_size, ppi_number}; + let format = match &o["format"] { + Value::Null => tl!("Unknown format"), + f => f.as_str()?, + }; let size = fill(tl!("{width} × {height} px"), &[("width", &o["width"].as_u64()?.to_string()), ("height", &o["height"].as_u64()?.to_string())]); - if o["linked"] == true { Some(fill(tl!("{size} — {file}"), &[("size", &size), ("file", o["file"].as_str()?)])) } else { Some(size) } + let detail = if o["linked"] == true { + match &o["effectivePpi"] { + Value::Null => tl!("resolution unavailable").to_string(), + ppi => { + let (x, y) = (ppi_number(ppi.get(0)?.as_f64()?), ppi_number(ppi.get(1)?.as_f64()?)); + if x == y { fill(tl!("{n} ppi"), &[("n", &x)]) } else { fill(tl!("{x} × {y} ppi"), &[("x", &x), ("y", &y)]) } + } + } + } else { + match &o["memoryBytes"] { + Value::Null => tl!("memory unavailable").to_string(), + bytes => fill(tl!("estimated memory {memory}"), &[("memory", &byte_size(bytes.as_u64()?))]), + } + }; + let shown = fill(tl!("{format}; {size}; {detail}"), &[("format", format), ("size", &size), ("detail", &detail)]); + if o["linked"] == true { Some(fill(tl!("{size} — {file}"), &[("size", &shown), ("file", o["file"].as_str()?)])) } else { Some(shown) } } /// A `repeatObjects` entry as Repeat Objects shows it: its kind and the number of instances it @@ -597,7 +618,7 @@ mod tests { let gone = fonts.iter().find(|(l, _)| l.starts_with("Qx Absent Family")).unwrap_or_else(|| panic!("{fonts:?}")).1.clone(); assert!(gone == "fehlt" || gone.starts_with("fehlt: angezeigt in "), "{gone}"); assert_eq!(images.len(), 1); - assert!(images[0].1.ends_with(" px") && images[0].1.contains(" × "), "{images:?}"); + assert!(images[0].1.contains(" × ") && images[0].1.contains(" px; geschätzter Speicher ") && images[0].1.ends_with(" B"), "{images:?}"); // A swatch named like a kind keeps its name; the gradient named by its kind is translated. assert_eq!(value(&gradients, "Glow"), "Linear gradient, Radialer Verlauf"); assert_eq!(value(&selected, "Glow"), "Linear gradient, Radialer Verlauf"); @@ -650,6 +671,54 @@ mod tests { assert!(report.contains("Source Sans 3 Regular: TrueType; 2 uses\n"), "{report}"); } + /// Linked Images and Embedded Images show each image's format, size, resolution or memory in + /// the interface language, the format and file names as they are; values that do not fit an + /// image entry are shown as `document.info` gives the row. + #[test] + fn image_details_show_in_the_interface_language() { + let linked = |format: Value, ppi: Value| json!({"name": "a.png", "width": 3, "height": 2, "linked": true, "file": "/art/a.png", "format": format, "effectivePpi": ppi}); + let embedded = + |memory: Value| json!({"name": "Image", "width": 3, "height": 2, "linked": false, "file": null, "format": "PNG", "memoryBytes": memory}); + let shown = || { + [ + linked(json!("PNG"), json!([150.0, 150.0])), + linked(json!(null), json!([144.0, 72.0])), + linked(json!("TIFF"), json!(null)), + embedded(json!(1536)), + embedded(json!(null)), + ] + .map(|o| image_value(&o)) + }; + assert_eq!( + shown(), + [ + "PNG; 3 × 2 px; 150 ppi — /art/a.png", + "Unknown format; 3 × 2 px; 144 × 72 ppi — /art/a.png", + "TIFF; 3 × 2 px; resolution unavailable — /art/a.png", + "PNG; 3 × 2 px; estimated memory 1.5 KiB", + "PNG; 3 × 2 px; memory unavailable", + ] + .map(|v| Some(v.to_string())) + ); + let Some(de) = crate::i18n::Lang::from_code("de") else { panic!("no German catalog") }; + crate::i18n::set_current(de); + let german = shown(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!( + german, + [ + "PNG; 3 × 2 px; 150 ppi – /art/a.png", + "Unbekanntes Format; 3 × 2 px; 144 × 72 ppi – /art/a.png", + "TIFF; 3 × 2 px; Auflösung nicht verfügbar – /art/a.png", + "PNG; 3 × 2 px; geschätzter Speicher 1.5 KiB", + "PNG; 3 × 2 px; Speicher nicht verfügbar", + ] + .map(|v| Some(v.to_string())) + ); + assert_eq!(image_value(&linked(json!("PNG"), json!([150.0]))), None); + assert_eq!(image_value(&embedded(json!("big"))), None); + } + /// Document shows the transparency settings with their values in the interface language (two /// custom grid colors as they are), and while the Artboard tool is the current tool the /// artboards it has selected, following its selection without an edit to the document. diff --git a/docs/mcp.md b/docs/mcp.md index 3cb8d1d239..df4eb70bfb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9948,9 +9948,15 @@ type in a mask or in a symbol's or pattern's art once however many objects show (`[{font, match, family, style, file, embedding}]`: each font of `fonts`, in order, as the fontDetails category's rows give it: `match` is `exact`, `style` (a style the family lacks, shown in `family` `style`), `missingWithFallback` (not installed, shown in `family` `style`) or `missing`; `file` is the face's file name, null for a built-in face; `embedding` is `allowed`, `editing`, `previewPrint` or `forbidden`, null when no -face is found), `imageObjects` (`[{name, width, height, linked, file}]`: the image objects in the order the -linkedImages and embeddedImages categories list them, with the file a linked image's row shows and null for an -embedded one), `document.unitId` (the document's units as Preferences › Units names them, such as `millimeters`, beside +face is found), `imageObjects` (`[{name, width, height, linked, file, format, effectivePpi, memoryBytes, +storedBytes}]`: the image objects in the order the linkedImages and embeddedImages categories list them, with the file +a linked image's row shows and null for an embedded one; `format` is a linked image's file format by its extension, +else the format of the pixels the document holds, null when neither is known; `effectivePpi` is `[x, y]`, the pixels +per inch at the size the image is placed at (a distorted image measured at its middle), null when it has no area; +`memoryBytes` is, for an embedded image, width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, and +`storedBytes` is the bytes of the encoded image the document holds; both are null for a linked image; a linkedImages row reads +`PNG; 1200 × 800 px; 150 ppi — /art/photo.png` and an embeddedImages row `PNG; 1200 × 800 px; estimated memory 3.7 MiB`, +with `Unknown format`, `resolution unavailable` or `memory unavailable` for a value that is null), `document.unitId` (the document's units as Preferences › Units names them, such as `millimeters`, beside the English `document.units`), `document.transparency` (`{gridSize, gridColors, gridColorsName, simulatePaper, flattenerPreset}`: File › Document Setup's transparency settings, the grid's size (`small`, `medium` or `large`), its two colors as `#rrggbb`, their preset's name or `Custom`, Simulate Colored Paper and the flattener preset, which the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5e8483f80a..8209052608 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2071,6 +2071,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Brushes panel's Delete Brush button and panel menu item ask "Delete the selected brushes?" with Yes and No when none of the brushes is in use. Alt-click (Option-click on macOS) on the button deletes them without asking, as the [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for panel deletion outside the Layers panel (archived copy). When a stroke uses one of the brushes, the button, Alt-click and the menu item all ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. Tests: `panels::brushes::tests`, `dialogs::brush_delete::tests`. Document Info has a Brushes category after Graphic Styles. It lists the names and types of the brushes applied to the artwork, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes, or with Selection Only the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`, `brushes`). Listing each brush once, leaving out the Brushes panel's brushes no art uses (`panelBrushNames` lists the panel's brushes), hidden strokes, strokes at an opacity of 0, strokes with no paint or width, guides, paths with no segment, type that draws no characters, a group's or layer's own strokes, a compound path member's own strokes and an image's strokes without a shape, and listing a brush the panel does not hold as missing, are VectorCraft's own rules. Tests: `cmd::docinfo::tests::info_lists_the_brushes` and `info_brushes_skip_undrawn_strokes_and_name_missing_brushes` (vectorcraft-engine). Document Info's Fonts category gives each font's type and number of uses beside its name, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) describes, for the whole document or with Selection Only for the selected type. The Document Info report and Package's report give them too (`document.info {category: "fonts"}`, `fontUses`), and the panel shows the type and count in the interface language. Counting a use as a text object set in the font (once however many of its runs use it, and the type in a mask or in a symbol's or pattern's art once however many objects show it), naming the type by the face's outlines (TrueType for `glyf`, OpenType for `CFF` or `CFF2`) and showing an unknown type for a font that is not installed in the family and style the type names are VectorCraft's own rules. Tests: `cmd::docinfo::tests::info_fonts_give_each_font_s_type_and_uses` (vectorcraft-engine), `panels::doc_info::tests::font_types_and_uses_show_in_the_interface_language` (vectorcraft-ui-egui), `fontdb::face::tests::outline_format_follows_the_outline_tables` (vectorcraft-text). + Document Info's Linked Images category gives each linked image's format, size in pixels, resolution and file, and its Embedded Images category gives each embedded image's format, size in pixels and memory size, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) describes, for the whole document or with Selection Only for the selected images. The Document Info report and Package's report give them too (`document.info {category: "linkedImages"}`, `imageObjects`' `format`, `effectivePpi`, `memoryBytes` and `storedBytes`), and the panel shows them in the interface language. Taking the format from a linked file's extension or else from the pixels the document holds, measuring the resolution at the size the image is placed at, counting the memory as the 8-bit RGBA pixels the image is drawn from (width × height × 4), and showing `Unknown format` or `resolution unavailable` when those are not known are VectorCraft's own rules. Tests: `cmd::docinfo::tests::image_rows_give_format_resolution_and_memory` and `byte_sizes_and_resolutions_read_to_a_tenth` (vectorcraft-engine), `panels::doc_info::tests::image_details_show_in_the_interface_language` (vectorcraft-ui-egui). Document Info has a Repeat Objects category after Embedded Images. It lists each radial, grid and mirror Repeat object by name with its kind and the number of instances it makes. For a grid it gives the rows and columns instead, followed by the number of instances it draws when that is fewer. With Selection Only it lists the Repeat objects in the selection. The Document Info report and Package's report list them too (`document.info {category: "repeats"}`, `repeatObjects`). Document Info's Pattern Objects category lists the objects whose fill or stroke is a pattern, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes, each by name with the patterns it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "patterns"}`, `patternObjects`). Listing an object with a pattern fill and a pattern stroke once, listing objects inside groups and type objects whose characters use a pattern, and leaving out hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, a compound path member's own fills and strokes, an image's fills and strokes without a shape, characters the type does not draw and patterns no art uses, and counting the listed objects in Objects, are VectorCraft's own rules. Test: `cmd::docinfo::tests::info_lists_the_pattern_objects` (vectorcraft-engine). Document Info's Gradient Objects category lists the objects whose fill or stroke is a gradient, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes as the count of objects with gradient fills or strokes. Each object is listed by name with the gradients it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "gradients"}`, `gradientObjects`). Naming a linked gradient by its swatch and any other gradient by its kind, and leaving out paint that draws nothing by the rules Pattern Objects follows, gradient swatches no art uses, gradient meshes and gradients drawn by effects, are VectorCraft's own rules. Objects counts the listed objects as Gradient Objects. Test: `cmd::docinfo::tests::info_lists_the_gradient_objects` (vectorcraft-engine). From 5caea7ad329bd1332fd1ebadb2b7b182db6f116b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 22:16:00 -0800 Subject: [PATCH 29/78] Artboards: Rearrange works on the selected artboards only artboard.rearrange takes indices (the artboards to lay out, in document order) and at (the grid's top-left). The other artboards, their art and their guides stay where they are, and a listed locked artboard keeps its place and its cell. Without indices the command lays out every artboard as before. With indices the reply adds indices and moved, and no undo step is recorded when nothing moved. With the Artboard tool, the canvas menu's Rearrange, the Contextual Task Bar's Rearrange, the Artboards panel menu's new Rearrange... and the panel's Rearrange button open the Rearrange dialog for the selected artboards, with their count. After OK the grid's outline follows the pointer, and a click on the canvas places its top-left there in one undo step. Enter places it from the keyboard when no other control has the focus, a Space-drag pans, and Esc, another tool, another document or a change to the listed artboards cancels it. Rearrange All Artboards is unchanged. The help page describes the selected-artboard arrangement and the click that places it: https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/rearrange-artboards.html The top-left reference point, the outline, the fallback to the first selected artboard's corner and the rules for locked artboards and for art on other artboards are VectorCraft's own. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/menucmds.rs | 52 ++-- crates/engine/src/cmd/newdoc.rs | 24 ++ crates/engine/src/tests/newdoc.rs | 93 +++++++ crates/engine/tests/command_sweep.rs | 7 +- crates/ui-egui/src/canvas.rs | 1 + crates/ui-egui/src/canvas/input.rs | 4 + crates/ui-egui/src/canvas/task_bar.rs | 20 +- crates/ui-egui/src/canvas/tests.rs | 216 +++++++++++++++- .../src/dialogs/rearrange_artboards.rs | 231 +++++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/gu.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tests.rs | 16 ++ crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/menus/context.rs | 6 +- crates/ui-egui/src/menus/invoke.rs | 8 + crates/ui-egui/src/panels/artboards.rs | 33 ++- crates/ui-egui/src/panels/artboards/tests.rs | 26 +- crates/ui-egui/src/state.rs | 20 ++ docs/mcp.md | 49 +++- docs/target-app-parity.md | 3 +- 45 files changed, 824 insertions(+), 69 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index aa330e11ea..96365e6553 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -187,7 +187,7 @@ pub fn specs() -> Vec { "Rearrange All Artboards…", ["Object", "Artboards"], None, - "{layout?: gridByRow|gridByColumn|row|column (gridByRow; byColumn?: true is gridByColumn), order?: leftToRight|rightToLeft (leftToRight: right-to-left mirrors the order along the rows), columns?: n (2; the rows for gridByColumn; row and column ignore it), spacing?: pt (20), moveArtwork?: true (each object of a layer or sublayer moves with the artboard its center is on; locked and hidden art, and art on a locked artboard, only with lockedAndHidden), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard), byColumn?: bool (an older way to ask for layout gridByColumn)} lay the artboards out in their order, the grid's top-left at the first artboard's; a locked artboard stays where it is → {artboards, rows, columns}", + "{layout?: gridByRow|gridByColumn|row|column (gridByRow; byColumn?: true is gridByColumn), order?: leftToRight|rightToLeft (leftToRight: right-to-left mirrors the order along the rows), columns?: n (2; the rows for gridByColumn; row and column ignore it), spacing?: pt (20), moveArtwork?: true (each object of a layer or sublayer moves with the artboard its center is on; locked and hidden art, and art on a locked artboard, only with lockedAndHidden), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard), byColumn?: bool (an older way to ask for layout gridByColumn), indices?: [n] (lay out only these artboards, in document order; the others and their art and guides stay where they are), at?: [x, y] (the grid's top-left)} lay the artboards out in their order, the grid's top-left at `at`, else at the first artboard's laid out; a locked artboard stays where it is and keeps its place in the grid → {artboards, rows, columns; with indices also indices and moved, the count of artboards that moved}", has_doc, rearrange_artboards ), @@ -1718,32 +1718,48 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(CMD, "order must be leftToRight or rightToLeft")), }; let count = s.doc()?.doc.artboards.len(); - let n_ab = count.max(1); - // Columns of a grid by row, rows of a grid by column. - let lines = whole_or(p, "columns", 2, CMD)?.clamp(1, n_ab as u64) as usize; - let (rows, cols) = match layout { - L::GridByRow => (n_ab.div_ceil(lines), lines), - L::GridByColumn => (lines, n_ab.div_ceil(lines)), - L::Row => (1, n_ab), - L::Column => (n_ab, 1), + // `indices` lays out only those artboards, in document order; left out, every artboard. + let picked: Option> = match p.get("indices") { + Some(v) => Some(super::panelcmds::listed_artboards(&s.doc()?.doc, v, "indices", CMD)?), + None => None, }; + let at = match p.get("at") { + Some(v) => Some(super::finite_numbers::<2>(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(CMD, "`at` must be [x, y]"))?), + None => None, + }; + // Columns of a grid by row, rows of a grid by column. + let lines = whole_or(p, "columns", 2, CMD)?; check_numbers(p, &["spacing"], CMD)?; let spacing = f64_or(p, "spacing", 20.0).clamp(-1.0e5, 1.0e5); let move_art = switch_or(p, "moveArtwork", true, CMD)?; check_switches(p, &["patterns"], CMD)?; let locked_and_hidden = super::panelcmds::locked_and_hidden(s, p, move_art, CMD)?; let d = &s.doc()?.doc; - let rects: Vec = d.artboards.iter().map(|a| a.rect).collect(); + let laid: Vec = picked.clone().unwrap_or_else(|| (0..count).collect()); + let rects: Vec = laid.iter().filter_map(|i| d.artboards.get(*i)).map(|a| a.rect).collect(); let sizes: Vec<(f64, f64)> = rects.iter().map(|r| (r.width(), r.height())).collect(); - let first = rects.first().map_or(Point::ZERO, |r| r.origin()); - let origins = super::newdoc::grid_origins_rc(&sizes, first, (rows, cols), spacing, layout == L::GridByColumn, rtl); - // A locked artboard stays where it is, and keeps its place in the grid. - let deltas: Vec = - rects.iter().zip(origins).zip(&d.artboards).map(|((r, o), a)| if a.locked { Vec2::ZERO } else { o - r.origin() }).collect(); + // The grid's top-left: `at`, else the first artboard laid out's. + let origin = at.unwrap_or_else(|| rects.first().map_or(Point::ZERO, |r| r.origin())); + let (origins, rows, cols) = super::newdoc::rearrange_grid(&sizes, origin, layout, lines, spacing, rtl); + // A locked artboard stays where it is, and keeps its place in the grid; an artboard not laid + // out stays where it is. + let mut deltas = vec![Vec2::ZERO; count]; + for ((i, r), o) in laid.iter().zip(&rects).zip(origins) { + if let Some(dl) = deltas.get_mut(*i) + && !d.artboards.get(*i).is_some_and(|a| a.locked) + { + *dl = o - r.origin(); + } + } + let moved = deltas.iter().filter(|dl| dl.x.abs() > 1e-9 || dl.y.abs() > 1e-9).count(); + let result = match &picked { + Some(indices) => json!({ "artboards": count, "indices": indices, "moved": moved, "rows": rows, "columns": cols }), + None => json!({ "artboards": count, "rows": rows, "columns": cols }), + }; // When no artboard moves more than 1e-9 pt on either axis, or there is none, the document and // its undo history stay as they are. - if deltas.iter().all(|dl| dl.x.abs() <= 1e-9 && dl.y.abs() <= 1e-9) { - return Ok(json!({ "artboards": count, "rows": rows, "columns": cols })); + if moved == 0 { + return Ok(result); } // With moveArtwork, each top-level object (a child of a layer or sublayer) moves with the // artboard its center is on, with symbol instances measured by their art as @@ -1791,5 +1807,5 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result { } Ok(()) })?; - Ok(json!({ "artboards": count, "rows": rows, "columns": cols })) + Ok(result) } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index e74a570a5b..89f67594a1 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -601,6 +601,30 @@ pub(crate) fn grid_origins_rc( .collect() } +/// Rearrange Artboards' grid for artboards of `sizes`, in their order, its top-left at `origin`: +/// `lines` is the column count of a grid by row and the row count of a grid by column (kept to 1 +/// to the artboard count), and `rtl` puts the first column at the right. Returns each artboard's +/// top-left corner and the grid's rows and columns. +pub fn rearrange_grid( + sizes: &[(f64, f64)], + origin: Point, + layout: ArtboardLayout, + lines: u64, + spacing: f64, + rtl: bool, +) -> (Vec, usize, usize) { + let n = sizes.len().max(1); + let lines = usize::try_from(lines).unwrap_or(usize::MAX).clamp(1, n); + let (rows, cols) = match layout { + ArtboardLayout::GridByRow => (n.div_ceil(lines), lines), + ArtboardLayout::GridByColumn => (lines, n.div_ceil(lines)), + ArtboardLayout::Row => (1, n), + ArtboardLayout::Column => (n, 1), + }; + let origins = grid_origins_rc(sizes, origin, (rows, cols), spacing, layout == ArtboardLayout::GridByColumn, rtl); + (origins, rows, cols) +} + /// The built-in presets: (category, presets as (name, width, height, units)), with the category's /// colour mode and raster effects resolution. Sizes in `units` (converted to points on use). type Category = (&'static str, ColorMode, f64, &'static [(&'static str, f64, f64, Unit)]); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index c6699190b6..b60f40f023 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -532,6 +532,99 @@ fn rearrange_that_moves_no_artboard_records_no_undo_step() { assert_eq!(history(&s), before); } +/// Rearrange with `indices` lays out only those artboards, in document order whatever order they +/// are listed in, with the grid's top-left at `at`: their art and guides go along, and the other +/// artboards, their art and their guides stay where they are, all in one undo step. +#[test] +fn rearrange_lays_out_only_the_listed_artboards() { + let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 4})); + let before = boards(&s); + let art: Vec = before + .iter() + .map(|r| { + NodeId( + s.execute("shape.rectangle", &json!({"x": r.x0 + 10.0, "y": r.y0 + 10.0, "width": 10, "height": 10})).unwrap()["id"] + .as_u64() + .unwrap(), + ) + }) + .collect(); + for i in [0, 1] { + s.execute("guide.add", &json!({"vertical": true, "pos": before[i].x0 + 5.0, "artboard": i})).unwrap(); + } + let undo = s.doc().unwrap().history.undo.len(); + let p = json!({"indices": [3, 1], "layout": "row", "spacing": 10, "at": [500, 400]}); + let r = s.execute("artboard.rearrange", &p).unwrap(); + assert_eq!(r, json!({"artboards": 4, "indices": [1, 3], "moved": 2, "rows": 1, "columns": 2})); + let after = boards(&s); + assert_eq!((after[0], after[2]), (before[0], before[2]), "the artboards not listed stay"); + assert_eq!((after[1], after[3]), (Rect::new(500.0, 400.0, 600.0, 450.0), Rect::new(610.0, 400.0, 710.0, 450.0))); + let d = &s.doc().unwrap().doc; + for (id, r) in art.iter().zip(&after) { + let b = d.node(*id).unwrap().geometric_bounds().unwrap(); + assert_eq!((b.x0, b.y0), (r.x0 + 10.0, r.y0 + 10.0), "the art is on its artboard"); + } + let guides: Vec = d.ruler_guides().iter().map(|g| g.pos).collect(); + assert_eq!(guides, [before[0].x0 + 5.0, 505.0]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(boards(&s), before); +} + +/// Without `at`, the grid of the listed artboards starts at the first one's top-left; one listed +/// artboard is laid out alone; a listed locked artboard stays and keeps its cell; when every listed +/// artboard is locked, nothing moves, no undo step is recorded and `moved` is 0. +#[test] +fn rearrange_of_listed_artboards_starts_at_the_first_and_keeps_locked_ones() { + let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 4, "artboardLayout": {"layout": "row", "spacing": 20}})); + let before = boards(&s); + // Artboards 1 and 3 in one column, from artboard 1's corner. + let r = s.execute("artboard.rearrange", &json!({"indices": [1, 3], "layout": "column", "spacing": 10})).unwrap(); + assert_eq!(r["moved"], 1); + let after = boards(&s); + assert_eq!(after[1], before[1]); + assert_eq!(after[3], Rect::new(before[1].x0, before[1].y1 + 10.0, before[1].x1, before[1].y1 + 60.0)); + // One artboard goes to `at`. + s.execute("artboard.rearrange", &json!({"indices": [2], "at": [-300, -200]})).unwrap(); + assert_eq!(boards(&s)[2], Rect::new(-300.0, -200.0, -200.0, -150.0)); + // Artboard 0 locked keeps its place and its cell: artboard 2 goes to the second cell from 0's. + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let r = s.execute("artboard.rearrange", &json!({"indices": [0, 2], "layout": "row", "spacing": 5, "at": [1000, 0]})).unwrap(); + assert_eq!(r["moved"], 1); + assert_eq!((boards(&s)[0], boards(&s)[2]), (before[0], Rect::new(1105.0, 0.0, 1205.0, 50.0))); + // Every listed artboard locked: nothing moves. + let placed = boards(&s); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("artboard.rearrange", &json!({"indices": [0], "at": [3000, 3000]})).unwrap(); + assert_eq!(r, json!({"artboards": 4, "indices": [0], "moved": 0, "rows": 1, "columns": 1})); + assert_eq!((boards(&s), s.doc().unwrap().history.undo.len()), (placed, undo)); +} + +/// Rearrange refuses `indices` that are not a non-empty list of artboards, and an `at` that is not +/// [x, y], before anything moves; a listed index given twice counts once. +#[test] +fn rearrange_refuses_bad_indices_and_at() { + let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3})); + let before = (boards(&s), s.doc().unwrap().history.undo.len()); + for (p, msg) in [ + (json!({"indices": []}), "invalid parameters for `artboard.rearrange`: `indices` must be a non-empty list of artboard indices"), + (json!({"indices": 1}), "invalid parameters for `artboard.rearrange`: `indices` must be a list of artboard indices"), + (json!({"indices": [1.5]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"), + (json!({"indices": [-1]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"), + (json!({"indices": ["1"]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"), + (json!({"indices": [0, 3]}), "no such artboard"), + (json!({"indices": [0, 1], "at": [1]}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"), + (json!({"indices": [0, 1], "at": "0,0"}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"), + (json!({"at": [0, "1"]}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"), + ] { + let err = s.execute("artboard.rearrange", &p).unwrap_err().to_string(); + assert_eq!(err, msg, "{p}"); + assert_eq!((boards(&s), s.doc().unwrap().history.undo.len()), before, "{p}"); + } + let r = s.execute("artboard.rearrange", &json!({"indices": [2, 2], "at": [0, 500]})).unwrap(); + assert_eq!((r["indices"].clone(), boards(&s)[2]), (json!([2]), Rect::new(0.0, 500.0, 100.0, 550.0))); +} + /// A session whose New Document profiles are in a fresh folder for test `name` (not made yet). fn with_profiles(name: &str) -> (Session, std::path::PathBuf) { let dir = std::env::temp_dir().join(format!("vc-newdoc-profiles-{name}-{}", std::process::id())); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 1413bb17bb..6664828398 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -93,7 +93,7 @@ fn every_command_without_a_document() { } /// Regression: huge column counts used to panic with `capacity overflow`; in every layout and -/// order (#681), with huge and negative spacing too. +/// order (#681), with huge and negative spacing too, and with `indices` and `at`. #[test] fn artboard_rearrange_huge_columns() { for fx in Fixture::ALL { @@ -106,6 +106,11 @@ fn artboard_rearrange_huge_columns() { } } } + // Listed artboards, out of range, and the grid's top-left at the far ends of the plane. + for (indices, at) in [(json!([0]), json!([1e308, -1e308])), (json!([0, u64::MAX]), json!([0, 0])), (json!([]), json!([-1e308, 1e308]))] { + let p = json!({ "indices": indices, "at": at, "columns": u64::MAX, "spacing": 1e308 }); + assert_eq!(probe(fx, "artboard.rearrange", &p), None); + } } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b366665d4..d690ea5dd0 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -430,6 +430,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { print_tiling_overlay(app, &painter, &xf); } original_path_overlay(app, &painter, &xf); + crate::dialogs::rearrange_artboards::paint_placement(app, &painter, &xf, t.selection); let overlays = selection_visuals(app, &painter, &xf, (hidden_chars, selection_marks, hover_still), revolve_edit, view_info); draw_overlays(&painter, &xf, &overlays, &t, HandleLook::of(&app.session.prefs), &mut shared_paths); diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index a6a0509de5..d7de78ec2a 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -22,6 +22,10 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo if (cancelled && pointer.primary_pressed()) || crate::dialogs::brush_key_color_input(app, ui, resp, rect) { return; } + // Rearrange's placement takes the press or Enter that places the artboards, and Esc. + if crate::dialogs::rearrange_artboards::placement_input(app, ui, resp, rect, modal, space) { + return; + } let v = *app.view().unwrap_or(&View::default()); let xf = Xf::at(rect, &v, app.canvas_ui_zoom); // A lifted pen or finger takes the pointer away in the frame it lifts (egui's `PointerGone`), diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 03ced4f7c6..253b916079 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -175,7 +175,7 @@ pub(crate) fn task_bar_shows_type(app: &VectorcraftApp) -> bool { /// The Contextual Task Bar: a floating pill under the selection with the most likely next actions. /// With the Artboard tool it sits under the selected artboards and offers Resize (Artboard -/// Options), Duplicate, Rearrange All (with two or more artboards) and Export (Export for Screens). +/// Options), Duplicate, Rearrange (the selected artboards) and Export (Export for Screens). /// A basic shape selected with the Selection tool shows a Shape Properties button in place of Lock. /// While a basic shape tool (Rectangle, Rounded Rectangle, Ellipse, Polygon or Star) has one closed /// path selected, as after it draws one, the bar offers Edit Path, Fill and Stroke, and Shape @@ -252,7 +252,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // Edit Path: the Direct Selection tool, to edit the path's anchors. let edit_path = || (tl!("Edit Path"), "dc-direct", "tool.select", json!({"tool": "directSelection"})); if on_artboards { - artboard_items(&mut items, st.doc.artboards.len()); + artboard_items(&mut items); } else if blank { // Draw (Pencil) switches to the Pencil tool; Place Image picks files for the Place dialog. items.push((tl!("Draw (Pencil)"), "pencil", "tool.select", json!({"tool": "pencil"}))); @@ -576,10 +576,10 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // Properties or the Control bar, it leaves the Image Trace panel as it was. Some((TASK_BAR_IMAGE_TRACE, _)) => crate::menus::invoke(app, "imageTrace.make", json!({"preset": "Default"})), // The Artboard tool's buttons: Artboard Options for the active artboard, as Properties' - // icon opens it; Duplicate for every selected artboard; Rearrange All Artboards. + // icon opens it; Duplicate and Rearrange for every selected artboard. Some((TASK_BAR_ARTBOARD_OPTIONS, _)) => crate::menus::invoke(app, "tool.options", json!({"tool": "artboard"})), Some((TASK_BAR_DUPLICATE_ARTBOARDS, _)) => crate::panels::artboards::duplicate_picked(app), - Some((TASK_BAR_REARRANGE_ARTBOARDS, _)) => crate::panels::artboards::open_rearrange(app), + Some((TASK_BAR_REARRANGE_ARTBOARDS, _)) => crate::panels::artboards::open_rearrange_selected(app), // The convert buttons convert the direct-selected anchors, as the Control bar's buttons do. Some((TASK_BAR_TO_CORNER, _)) => crate::menus::invoke(app, "path.convertAnchors", json!({"to": "corner"})), Some((TASK_BAR_TO_SMOOTH, _)) => crate::menus::invoke(app, "path.convertAnchors", json!({"to": "smooth"})), @@ -980,17 +980,15 @@ fn paint_chip(ui: &mut Ui, t: &Tokens, paint: &vectorcraft_color::Paint, mixed: resp.on_hover_text(tip).clicked() } -/// The Contextual Task Bar's items with the Artboard tool in a document of `artboards` artboards: -/// Resize, Duplicate, Rearrange All (with two or more) and Export. -fn artboard_items(items: &mut Vec<(&'static str, &'static str, &'static str, serde_json::Value)>, artboards: usize) { +/// The Contextual Task Bar's items with the Artboard tool: Resize, Duplicate, Rearrange (the +/// selected artboards) and Export. +fn artboard_items(items: &mut Vec<(&'static str, &'static str, &'static str, serde_json::Value)>) { // As in the reference app, the Artboard tool offers to resize, duplicate and export the // artboards (), // and to rearrange them (). items.push((tl!("Resize"), "move-diagonal-2", TASK_BAR_ARTBOARD_OPTIONS, json!({}))); items.push((tl!("Duplicate"), "copy", TASK_BAR_DUPLICATE_ARTBOARDS, json!({}))); - if artboards > 1 { - items.push((tl!("Rearrange All"), "dc-rearrange", TASK_BAR_REARRANGE_ARTBOARDS, json!({}))); - } + items.push((tl!("Rearrange"), "dc-rearrange", TASK_BAR_REARRANGE_ARTBOARDS, json!({}))); items.push((tl!("Export"), "share-2", "file.exportForScreens", json!({}))); } @@ -1018,7 +1016,7 @@ const TASK_BAR_ARTBOARD_OPTIONS: &str = "taskBar.artboardOptions"; /// The Contextual Task Bar's Duplicate button with the Artboard tool. const TASK_BAR_DUPLICATE_ARTBOARDS: &str = "taskBar.duplicateArtboards"; -/// The Contextual Task Bar's Rearrange All button with the Artboard tool. +/// The Contextual Task Bar's Rearrange button with the Artboard tool. const TASK_BAR_REARRANGE_ARTBOARDS: &str = "taskBar.rearrangeArtboards"; /// The Contextual Task Bar's Convert Selected Anchor Points to Corner button, for direct-selected diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..8e56795605 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -12504,7 +12504,7 @@ fn task_bar_labels(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(String } /// With the Artboard tool, the Contextual Task Bar sits under the selected artboards and offers -/// Resize, Duplicate, Rearrange All (with two or more artboards) and Export instead of the +/// Resize, Duplicate, Rearrange (the selected artboards, one included) and Export instead of the /// selected objects' actions. With the Selection tool it offers the objects' actions again, and /// with nothing in the document the blank canvas actions. #[test] @@ -12522,7 +12522,7 @@ fn the_task_bar_offers_the_artboard_tools_actions() { let b = app.session.active().unwrap().doc.artboards[1].rect; let view = app.view_mut().unwrap(); (view.center, view.zoom) = (b.center(), 1.0); - assert_eq!(names(&mut app), ["Resize", "Duplicate", "Rearrange All", "Export"]); + assert_eq!(names(&mut app), ["Resize", "Duplicate", "Rearrange", "Export"]); // Under artboard 2. let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); let bar = task_bar_rect(&ctx).unwrap(); @@ -12534,10 +12534,212 @@ fn the_task_bar_offers_the_artboard_tools_actions() { app.session.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); assert_eq!(names(&mut app), ["Edit Path", "Offset Path", "Simplify", "Duplicate"]); - // One artboard: nothing to rearrange. + // One artboard, selected: Rearrange places it. app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); app.select_tool("artboard"); - assert_eq!(names(&mut app), ["Resize", "Duplicate", "Export"]); + assert_eq!(names(&mut app), ["Resize", "Duplicate", "Rearrange", "Export"]); +} + +/// The task bar's Rearrange, confirmed, waits for a click: the grid's outline follows the pointer, +/// and a press on the canvas puts the selected artboards' grid there with its top-left at the press, +/// as one undo step, leaving the other artboards and giving the tool no press. Esc cancels a second +/// one, and so does another tool, with nothing moved. +#[test] +fn rearrange_places_the_selected_artboards_where_the_canvas_is_clicked() { + use crate::dialogs::rearrange_artboards::PLACE_HINT; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([0, 2])); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let wait = |app: &mut VectorcraftApp| { + crate::panels::artboards::open_rearrange_selected(app); + let d = app.ui.dialog.as_mut().expect("Rearrange opens"); + d.fields.insert("layout".into(), json!("row")); + d.fields.insert("spacing".into(), json!(10)); + crate::dialogs::confirm(app).unwrap(); + assert!(app.ui.rearrange_placement.is_some() && app.ui.status == PLACE_HINT); + }; + let (before, steps) = (boards(&app), undo(&app)); + let canvas = app.canvas_rect.unwrap(); + let at = canvas.center() + vec2(-150.0, -120.0); + let xf = Xf::at(canvas, app.view().unwrap(), app.canvas_ui_zoom); + let doc = xf.to_doc(at); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + + // Esc: nothing moves. + wait(&mut app); + frame( + &mut app, + &ctx, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], + ); + assert!(app.ui.rearrange_placement.is_none()); + // Another tool: nothing moves. + wait(&mut app); + app.select_tool("selection"); + frame(&mut app, &ctx, vec![]); + assert!(app.ui.rearrange_placement.is_none()); + assert_eq!((boards(&app), undo(&app)), (before.clone(), steps)); + + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([0, 2])); + wait(&mut app); + // The grid's outline: artboard 0's top-left at the pointer. + let outlines = |app: &mut VectorcraftApp| { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), + events: vec![egui::Event::PointerMoved(at)], + ..Default::default() + }; + let out = ctx.run_ui(raw, |ui| show(app, ui)); + out.shapes.iter().any(|s| match &s.shape { + egui::Shape::Path(p) => p.closed && p.points.first().is_some_and(|q| (*q - at).length() < 0.5), + _ => false, + }) + }; + outlines(&mut app); + assert!(outlines(&mut app), "the grid's outline starts at the pointer"); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(true)]); + frame(&mut app, &ctx, vec![button(false)]); + let after = boards(&app); + assert_eq!(after.len(), 3, "the Artboard tool made no artboard"); + assert_eq!(after[1], before[1], "artboard 2 is not selected"); + let near = |a: f64, b: f64| (a - b).abs() < 1e-3; + assert!(near(after[0].x0, doc.x) && near(after[0].y0, doc.y), "{:?} at {doc:?}", after[0]); + assert!(near(after[2].x0, doc.x + 210.0) && near(after[2].y0, doc.y), "{:?}", after[2]); + assert_eq!(undo(&app), steps + 1); + assert!(app.ui.rearrange_placement.is_none() && app.ui.status != PLACE_HINT); +} + +/// A waiting Rearrange takes Enter from the keyboard, but not in the frame it was confirmed in (the +/// dialog's own Enter): with the pointer off the canvas, the grid starts at the first selected +/// artboard's top-left, in one undo step. A press with Space held pans and places nothing. +#[test] +fn rearrange_places_the_selected_artboards_with_enter_and_lets_space_pan() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([2, 0])); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let (before, steps) = (boards(&app), undo(&app)); + crate::panels::artboards::open_rearrange_selected(&mut app); + let d = app.ui.dialog.as_mut().expect("Rearrange opens"); + d.fields.insert("layout".into(), json!("row")); + d.fields.insert("spacing".into(), json!(10)); + crate::dialogs::confirm(&mut app).unwrap(); + let key = |key, pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + // The Enter that confirmed the dialog places nothing. + frame(&mut app, &ctx, vec![key(egui::Key::Enter, true)]); + assert!(app.ui.rearrange_placement.is_some()); + // Space held: the press pans. + let at = app.canvas_rect.unwrap().center(); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![key(egui::Key::Space, true), egui::Event::PointerMoved(at), button(true)]); + frame(&mut app, &ctx, vec![button(false), key(egui::Key::Space, false)]); + assert!(app.ui.rearrange_placement.is_some()); + assert_eq!((boards(&app), undo(&app)), (before.clone(), steps)); + // Enter while another control has the keyboard focus is that control's. + ctx.memory_mut(|m| m.request_focus(egui::Id::unique("another control"))); + frame(&mut app, &ctx, vec![key(egui::Key::Enter, true)]); + assert!(app.ui.rearrange_placement.is_some(), "Enter in another control places nothing"); + assert_eq!((boards(&app), undo(&app)), (before.clone(), steps)); + ctx.memory_mut(|m| m.surrender_focus(egui::Id::unique("another control"))); + // Enter with the pointer off the canvas: from artboard 1's corner, artboard 3 next to it. + frame(&mut app, &ctx, vec![egui::Event::PointerGone, key(egui::Key::Enter, true)]); + let after = boards(&app); + assert!(app.ui.rearrange_placement.is_none()); + assert_eq!((after[0], after[1]), (before[0], before[1])); + assert_eq!((after[2].x0, after[2].y0), (before[0].x0 + 210.0, before[0].y0)); + assert_eq!(undo(&app), steps + 1); +} + +/// A waiting Rearrange is dropped when its artboards change places in the list before the click, +/// so the click moves no artboard the tool did not select. +#[test] +fn rearrange_waiting_for_a_click_is_dropped_when_its_artboards_are_reordered() { + use crate::dialogs::rearrange_artboards::PLACE_HINT; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([0])); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + crate::panels::artboards::open_rearrange_selected(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.rearrange_placement.is_some()); + app.run("artboard.reorder", json!({"index": 2, "to": 0})).unwrap(); + let before: Vec<_> = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let at = app.canvas_rect.unwrap().center(); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(true)]); + frame(&mut app, &ctx, vec![button(false)]); + assert!(app.ui.rearrange_placement.is_none() && app.ui.status != PLACE_HINT); + let after: Vec<_> = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(after, before); +} + +/// A Rearrange placement that moves nothing says the artboard is locked only when every selected +/// artboard is locked; a locked artboard beside one already in its cell leaves no such message. +#[test] +fn rearrange_says_locked_only_when_every_selected_artboard_is_locked() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let layout = json!({"layout": "row", "spacing": 20}); + app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3, "artboardLayout": layout})).unwrap(); + app.session.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + app.select_tool("artboard"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + for (selected, status) in [(json!([0, 1]), ""), (json!([0]), "the artboard is locked")] { + app.session.set_tool_option("selected", &selected); + crate::panels::artboards::open_rearrange_selected(&mut app); + let d = app.ui.dialog.as_mut().expect("Rearrange opens"); + d.fields.insert("layout".into(), json!("row")); + d.fields.insert("spacing".into(), json!(20)); + crate::dialogs::confirm(&mut app).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![egui::Event::PointerGone, enter.clone()]); + assert!(app.ui.rearrange_placement.is_none(), "{selected}"); + assert_eq!(app.ui.status, status, "{selected}"); + } +} + +/// A press on a floating panel over the canvas does not place a waiting Rearrange; a press on the +/// open canvas does. +#[test] +fn rearrange_is_not_placed_by_a_press_on_a_panel_over_the_canvas() { + let (mut app, ctx, _, over, _) = distance_scene(false); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([0])); + crate::panels::artboards::open_rearrange_selected(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + let board = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards[0].rect; + let before = board(&app); + let cover = Some(Cover::Panel(egui::Rect::from_center_size(over, vec2(120.0, 120.0)))); + let run = |app: &mut VectorcraftApp, events, cover| distance_frame_covered(app, &ctx, events, cover); + // A new window takes a sizing pass before it covers anything. + for _ in 0..3 { + run(&mut app, vec![egui::Event::PointerMoved(over)], cover); + } + let button = |pressed| egui::Event::PointerButton { pos: over, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![button(true)], cover); + run(&mut app, vec![button(false)], cover); + assert!(app.ui.rearrange_placement.is_some(), "the press is the panel's"); + assert_eq!(board(&app), before); + for _ in 0..3 { + run(&mut app, vec![egui::Event::PointerMoved(over)], None); + } + run(&mut app, vec![button(true)], None); + run(&mut app, vec![button(false)], None); + assert!(app.ui.rearrange_placement.is_none(), "placed on the open canvas"); + assert_ne!(board(&app), before); } /// Screen readers name the Contextual Task Bar's text buttons by their labels. @@ -12581,7 +12783,7 @@ fn the_task_bar_leaves_isolate_out_while_an_opacity_mask_is_edited() { } /// The Artboard tool's Contextual Task Bar buttons act on its selected artboards: Resize opens -/// Artboard Options for the active one, Rearrange All opens Rearrange All Artboards, Export opens +/// Artboard Options for the active one, Rearrange opens Rearrange for the selected artboards, Export opens /// Export for Screens with the selected artboards checked, and Duplicate copies each selected /// artboard in one undo step and selects the copies. #[test] @@ -12603,8 +12805,8 @@ fn the_artboard_tools_task_bar_buttons_act_on_the_selected_artboards() { }; let d = press(&mut app, "Resize").expect("Artboard Options"); assert_eq!((d.kind.as_str(), d.f64("index", 9.0)), ("artboardOptions", 2.0)); - let d = press(&mut app, "Rearrange All").expect("Rearrange All Artboards"); - assert_eq!(d.kind, crate::dialogs::rearrange_artboards::KIND); + let d = press(&mut app, "Rearrange").expect("Rearrange"); + assert_eq!((d.kind.as_str(), &d.fields["indices"]), (crate::dialogs::rearrange_artboards::KIND, &json!([0, 2]))); let d = press(&mut app, "Export").expect("Export for Screens"); assert_eq!((d.kind.as_str(), &d.fields["boards"]), (crate::dialogs::EXPORT_FOR_SCREENS, &json!([true, false, true]))); diff --git a/crates/ui-egui/src/dialogs/rearrange_artboards.rs b/crates/ui-egui/src/dialogs/rearrange_artboards.rs index 6fa90910a4..42c31efa7e 100644 --- a/crates/ui-egui/src/dialogs/rearrange_artboards.rs +++ b/crates/ui-egui/src/dialogs/rearrange_artboards.rs @@ -4,14 +4,26 @@ //! Spacing and Move Artwork with Artboard, with the document's artboard count. OK runs //! `artboard.rearrange` as one undo step (#681). //! +//! Rearrange (the Artboard tool's canvas menu and Contextual Task Bar, the Artboards panel's +//! Rearrange… and its button while the Artboard tool is in use) is the same dialog for the +//! selected artboards (field `indices`), with their count. Its OK waits for a click on the canvas, +//! which places the grid's top-left there: the grid follows the pointer until then, Enter places it +//! at the pointer (or, off the canvas, at the first selected artboard's top-left), a Space-drag +//! still pans, and Esc, another tool or another document cancels it. The click or Enter runs +//! `artboard.rearrange` with `indices` and `at` as one undo step +//! (https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/rearrange-artboards.html). +//! //! Fields: `layout` (`gridByRow` | `gridByColumn` | `row` | `column`), `order` (`leftToRight` | -//! `rightToLeft`), `columns` (the rows of a grid by column), `spacing` (pt) and `moveArtwork`. +//! `rightToLeft`), `columns` (the rows of a grid by column), `spacing` (pt), `moveArtwork` and, for +//! Rearrange, `indices`. use serde_json::{Value, json}; -use vectorcraft_engine::cmd::newdoc::ArtboardLayout; +use vectorcraft_engine::cmd::newdoc::{ArtboardLayout, rearrange_grid}; +use vectorcraft_geom::Rect; use super::{DialogSpec, form, run_and_close}; -use crate::state::Dialog; +use crate::canvas::Xf; +use crate::state::{Dialog, RearrangePlacement, View}; use crate::{VectorcraftApp, widgets}; /// The dialog kind of Rearrange All Artboards. @@ -19,11 +31,17 @@ pub const KIND: &str = "rearrangeArtboards"; const CMD: &str = "artboard.rearrange"; +/// The status bar's message while a Rearrange waits for its click. +pub(crate) const PLACE_HINT: &str = "Click on the canvas to place the artboards (Esc cancels)"; + /// Width of the label column. const LABEL_W: f32 = 96.0; -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Rearrange All Artboards").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 320.0, ..DialogSpec::FORM }; + +fn heading(d: &Dialog) -> String { + if indices(d).is_some() { tl!("Rearrange") } else { tl!("Rearrange All Artboards") }.into() +} /// The fields a fresh dialog starts with. pub fn fields() -> Value { @@ -39,6 +57,133 @@ pub fn open_fields(app: &VectorcraftApp) -> Value { fields } +/// Open Rearrange for artboards `indices`, kept sorted and once each; none opens nothing. A +/// placement still waiting is dropped. +pub(crate) fn open_selected(app: &mut VectorcraftApp, indices: &[usize]) { + cancel_placement(app); + if indices.is_empty() { + return; + } + let mut indices = indices.to_vec(); + indices.sort_unstable(); + indices.dedup(); + let mut fields = open_fields(app); + fields["indices"] = json!(indices); + app.ui.dialog = Some(Dialog::new(KIND, fields)); +} + +/// The artboards of a menu item's params that list nothing but `indices` (the Artboard tool's +/// Rearrange), as whole numbers. +pub(crate) fn menu_indices(p: &Value) -> Option> { + let o = p.as_object().filter(|o| o.len() == 1)?; + let list = o.get("indices")?.as_array()?; + list.iter().map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok())).collect() +} + +/// The artboards a Rearrange dialog lays out; `None` for Rearrange All Artboards. +fn indices(d: &Dialog) -> Option> { + d.fields.get("indices").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).filter_map(|i| usize::try_from(i).ok()).collect()) +} + +/// The artboards a waiting placement lays out. +fn placed(pl: &RearrangePlacement) -> Vec { + pl.params["indices"].as_array().into_iter().flatten().filter_map(Value::as_u64).filter_map(|i| usize::try_from(i).ok()).collect() +} + +/// Drop the placement waiting for its click, and its message in the status bar. +pub(crate) fn cancel_placement(app: &mut VectorcraftApp) { + if app.ui.rearrange_placement.take().is_some() && app.ui.status == PLACE_HINT { + app.status(""); + } +} + +/// Whether a placement waits for its click: one whose document is no longer the active one, whose +/// tool is no longer the tool in use, or whose listed places no longer hold the artboards it was +/// confirmed for (removed or moved in the list) is dropped. +pub(crate) fn refresh_placement(app: &mut VectorcraftApp) -> bool { + let Some(pl) = app.ui.rearrange_placement.as_ref() else { return false }; + let same = app.session.active().filter(|d| d.uid == pl.doc).is_some_and(|d| { + let listed = placed(pl); + listed.len() == pl.ids.len() && listed.iter().zip(&pl.ids).all(|(i, id)| d.doc.artboards.get(*i).is_some_and(|a| a.id == *id)) + }); + if same && app.session.tool_id() == pl.tool { + return true; + } + cancel_placement(app); + false +} + +/// The canvas's input while a placement waits and no modal dialog is open (`modal`): Esc cancels +/// it, a press on the canvas runs `artboard.rearrange` with the grid's top-left (`at`) at the +/// pressed point, and Enter, when no other control has the keyboard focus, runs it with `at` at the +/// pointer over the canvas, else with the grid at the first selected artboard's top-left. While +/// Space lends the view tools (`space`), presses pan or zoom as usual. Returns true when the +/// placement takes the frame's input, so no tool gets it. +pub(crate) fn placement_input(app: &mut VectorcraftApp, ui: &egui::Ui, resp: &egui::Response, rect: egui::Rect, modal: bool, space: bool) -> bool { + if !refresh_placement(app) || modal { + return false; + } + if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + cancel_placement(app); + return true; + } + let armed = app.ui.rearrange_placement.as_ref().is_some_and(|pl| pl.armed); + if let Some(pl) = app.ui.rearrange_placement.as_mut() { + pl.armed = true; + } + if space { + return false; + } + let pointer = ui.input(|i| i.pointer.clone()); + // The grid follows the pointer. + if pointer.is_moving() { + ui.ctx().request_repaint(); + } + let xf = Xf::at(rect, app.view().unwrap_or(&View::default()), app.canvas_ui_zoom); + let pressed = pointer.interact_pos().filter(|p| pointer.primary_pressed() && resp.hovered() && rect.contains(*p)); + // Enter belongs to the control that has the keyboard focus, when another one has it. + let free_keys = ui.memory(|m| m.focused().is_none_or(|id| id == resp.id)); + let entered = armed && free_keys && ui.input(|i| i.key_pressed(egui::Key::Enter)); + let at = match (pressed, entered) { + (Some(p), _) => Some(xf.to_doc(p)), + (None, true) => pointer.hover_pos().filter(|p| resp.hovered() && rect.contains(*p)).map(|p| xf.to_doc(p)), + (None, false) => return false, + }; + let Some(mut pl) = app.ui.rearrange_placement.take() else { return false }; + let listed = placed(&pl); + let locked = app.session.active().is_some_and(|d| listed.iter().all(|i| d.doc.artboards.get(*i).is_some_and(|a| a.locked))); + if let Some(at) = at { + pl.params["at"] = json!([at.x, at.y]); + } + match app.run(CMD, pl.params) { + // Every selected artboard locked: nothing could move. + Ok(r) if r["moved"] == 0 && locked => app.status("the artboard is locked"), + Ok(_) => app.status(""), + Err(e) => app.status(e), + } + true +} + +/// The grid a waiting placement makes with its top-left at the pointer: the outline of each +/// artboard that moves, in `color`, 1 point wide on screen. +pub(crate) fn paint_placement(app: &VectorcraftApp, painter: &egui::Painter, xf: &Xf, color: egui::Color32) { + let Some(pl) = app.ui.rearrange_placement.as_ref().filter(|pl| app.session.tool_id() == pl.tool) else { return }; + let (Some(at), Some(st)) = (app.hover_doc, app.session.active().filter(|d| d.uid == pl.doc)) else { return }; + let boards: Vec<&vectorcraft_doc::Artboard> = placed(pl).into_iter().filter_map(|i| st.doc.artboards.get(i)).collect(); + let sizes: Vec<(f64, f64)> = boards.iter().map(|a| (a.rect.width(), a.rect.height())).collect(); + let p = &pl.params; + let layout = p["layout"].as_str().and_then(ArtboardLayout::parse).unwrap_or_default(); + let lines = p["columns"].as_f64().filter(|c| c.is_finite()).map_or(2, |c| c.round().max(1.0) as u64); + let spacing = p["spacing"].as_f64().filter(|s| s.is_finite()).unwrap_or(20.0).clamp(-1.0e5, 1.0e5); + let (origins, ..) = rearrange_grid(&sizes, at, layout, lines, spacing, p["order"] == "rightToLeft"); + // A locked artboard keeps its cell but stays where it is. + for ((o, (w, h)), a) in origins.iter().zip(&sizes).zip(&boards) { + if !a.locked { + painter.add(egui::Shape::closed_line(xf.quad(Rect::new(o.x, o.y, o.x + w, o.y + h)), egui::Stroke::new(1.0, color))); + } + } +} + /// A layout's toggle: its tooltip and its artboards' cells (column, row) in their order, left to /// right. fn layout_glyph(l: ArtboardLayout) -> (&'static str, &'static [(u8, u8)]) { @@ -58,15 +203,20 @@ fn mirrored(cells: &[(u8, u8)], rtl: bool) -> Vec<(u8, u8)> { /// `artboard.rearrange` parameters from the fields. fn params(d: &Dialog) -> Value { - json!({ + let mut p = json!({ "layout": d.str("layout"), "order": d.str("order"), "columns": d.f64("columns", 2.0), "spacing": d.f64("spacing", 20.0), "moveArtwork": d.bool("moveArtwork"), - }) + }); + if let Some(indices) = indices(d) { + p["indices"] = json!(indices); + } + p } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let unit = app.session.general_unit(); - let n = app.session.active().map_or(0, |doc| doc.doc.artboards.len()); + let selected = indices(d); + let n = selected.as_ref().map_or_else(|| app.session.active().map_or(0, |doc| doc.doc.artboards.len()), Vec::len); let layout = ArtboardLayout::parse(&d.str("layout")).unwrap_or_default(); let rtl = d.str("order") == "rightToLeft"; widgets::label_row(ui, tl!("Layout:"), LABEL_W, |ui| { @@ -114,12 +264,32 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { form::check(ui, d, "moveArtwork", tl!("Move Artwork with Artboard")); }); ui.add_space(8.0); - widgets::dim_label(ui, &crate::i18n::fmt(tl!("Artboards: {n}"), &[("n", &n.to_string())])); + let count = if selected.is_some() { tl!("Selected Artboards: {n}") } else { tl!("Artboards: {n}") }; + widgets::dim_label(ui, &crate::i18n::fmt(count, &[("n", &n.to_string())])); false } +/// Rearrange All Artboards runs at once. Rearrange closes and waits for its click on the canvas +/// ([`placement_input`]). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let result = run_and_close(app, CMD, params(d))?; + let result = match indices(d) { + None => { + cancel_placement(app); + run_and_close(app, CMD, params(d))? + } + Some(listed) => { + let st = app.session.active().ok_or_else(|| "no document".to_string())?; + let ids: Vec = listed.iter().filter_map(|i| st.doc.artboards.get(*i)).map(|a| a.id).collect(); + if ids.len() != listed.len() { + return Err("no such artboard".into()); + } + let (doc, tool) = (st.uid, app.session.tool_id().to_string()); + app.ui.rearrange_placement = Some(RearrangePlacement { doc, tool, params: params(d), ids, armed: false }); + app.ui.dialog = None; + app.status(PLACE_HINT); + Value::Null + } + }; app.ui.rearrange_artboards_spacing = json!(d.f64("spacing", 20.0)); Ok(result) } @@ -229,4 +399,45 @@ mod tests { // Two rows (Columns 2 reads Rows for a grid by column), the first column at the right. assert_eq!(origins(&app), [(120.0, 0.0), (120.0, 70.0), (0.0, 0.0), (0.0, 70.0)]); } + + /// The Artboard tool's canvas menu opens Rearrange for the artboards the tool has selected, + /// with their count; OK moves nothing and waits for a click on the canvas with those artboards + /// and the dialog's fields. Rearrange All Artboards still lays out every artboard at once. + #[test] + fn rearrange_from_the_canvas_menu_waits_for_a_click_with_the_selected_artboards() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([0, 2])); + let items = crate::menus::context_items(&app); + let target = items.iter().find_map(|i| match i { + crate::menus::Item::Cmd("Rearrange", id, p) => Some(crate::menus::click_target("Rearrange", id, p)), + _ => None, + }); + let (id, p) = target.expect("Rearrange in the canvas menu"); + crate::menus::invoke(&mut app, &id, p); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + let ctx = context(); + frame(&mut app, &ctx, vec![]); + let texts = frame(&mut app, &ctx, vec![]); + for want in ["Rearrange", "Layout:", "Move Artwork with Artboard", "Selected Artboards: 2"] { + assert!(texts.iter().any(|t| t == want), "{want:?} in {texts:?}"); + } + assert!(!texts.iter().any(|t| t == "Rearrange All Artboards" || t == "Artboards: 3"), "{texts:?}"); + app.ui.dialog.as_mut().unwrap().fields.insert("layout".into(), json!("row")); + let (before, undo) = (origins(&app), app.session.doc().unwrap().history.undo.len()); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!((origins(&app), app.session.doc().unwrap().history.undo.len()), (before.clone(), undo)); + let waiting = app.ui.rearrange_placement.as_ref().expect("waits for a click"); + assert_eq!((waiting.params["indices"].clone(), waiting.params["layout"].clone()), (json!([0, 2]), json!("row"))); + assert_eq!(app.ui.status, PLACE_HINT); + + // Rearrange All Artboards drops it and runs at once. + app.run("ui.menuDialog", json!({"command": CMD})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + assert_ne!(origins(&app), before); + assert!(app.ui.rearrange_placement.is_none()); + assert_ne!(app.ui.status, PLACE_HINT); + } } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..dce0f2c36e 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2969,6 +2969,9 @@ digits Malayalam Малаялам Scale Artwork with Artboard Мащабиране на графиката заедно с работната област Artboards: {n} Работни области: {n} Rearrange All Artboards… Пренареждане на всички работни области… + Rearrange… Пренареждане… + Selected Artboards: {n} Избрани работни области: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Кликнете върху платното, за да поставите работните области (Esc отменя) Recall Selection Възстановяване на селекцията RECENT СКОРОШНИ Recent Скорошни diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..0ede519045 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -343,6 +343,9 @@ Artboards Radne ploče Convert to Artboards Pretvori u radne ploče Rearrange All Artboards… Preuredi sve radne ploče… + Rearrange… Preuredi… + Selected Artboards: {n} Odabrane radne ploče: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Kliknite na platno da postavite radne ploče (Esc otkazuje) Fit to Artwork Bounds Uklopi u granice crteža Fit to Selected Art Uklopi u odabrani crtež Graph Grafikon diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..ee851070ea 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3791,6 +3791,9 @@ digits Malayalam Malaiàlam Rearrange All Reorganitza-ho tot Rearrange All Artboards Reorganitza tots els taulers Rearrange All Artboards… Reorganitza tots els taulers… + Rearrange… Reorganitza… + Selected Artboards: {n} Taulers seleccionats: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Fes clic al llenç per col·locar els taulers (Esc cancel·la) Rearrange Artboards Reorganitza els taulers Recall Selection Recupera la selecció RECENT RECENTS diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..62d89ff1c0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -350,6 +350,9 @@ Artboards Pracovní plochy Convert to Artboards Převést na pracovní plochy Rearrange All Artboards… Přeuspořádat všechny pracovní plochy… + Rearrange… Přeuspořádat… + Selected Artboards: {n} Vybrané pracovní plochy: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Kliknutím na plátno umístíte pracovní plochy (Esc zruší) Fit to Artwork Bounds Přizpůsobit hranicím kresby Fit to Selected Art Přizpůsobit vybrané kresbě Graph Graf diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..c15122b46a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3081,6 +3081,9 @@ liquify-list-end {0}, {1} {0} og {1} Artboards Tegneflader Convert to Artboards Konvertér til tegneflader Rearrange All Artboards… Omarrangér alle tegneflader… + Rearrange… Omarrangér… + Selected Artboards: {n} Markerede tegneflader: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Klik på lærredet for at placere tegnefladerne (Esc annullerer) Fit to Artwork Bounds Tilpas til grafikkens grænser Fit to Selected Art Tilpas til valgt grafik Graph Diagram diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..31b26f673c 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3037,6 +3037,9 @@ digits Malayalam Malayalam Scale Artwork with Artboard Grafik mit Zeichenfläche skalieren Artboards: {n} Zeichenflächen: {n} Rearrange All Artboards… Alle Zeichenflächen neu anordnen… + Rearrange… Neu anordnen… + Selected Artboards: {n} Ausgewählte Zeichenflächen: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Klicken Sie auf die Arbeitsfläche, um die Zeichenflächen zu platzieren (Esc bricht ab) Recall Selection Auswahl abrufen RECENT ZULETZT VERWENDET Recent Zuletzt verwendet diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..5aac0384ed 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3939,6 +3939,9 @@ digits Malayalam Μαλαγιάλαμ Scale Artwork with Artboard Κλιμάκωση σχεδίου μαζί με τον πίνακα σχεδίασης Artboards: {n} Πίνακες σχεδίασης: {n} Rearrange All Artboards… Αναδιάταξη όλων των πινάκων σχεδίασης… + Rearrange… Αναδιάταξη… + Selected Artboards: {n} Επιλεγμένοι πίνακες σχεδίασης: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Κάντε κλικ στον καμβά για να τοποθετήσετε τους πίνακες σχεδίασης (Esc για ακύρωση) Recall Selection Ανάκληση επιλογής RECENT ΠΡΟΣΦΑΤΑ Recent Colors Πρόσφατα χρώματα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..688ba57a94 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3074,6 +3074,9 @@ digits Malayalam Malayálam Scale Artwork with Artboard Escalar la ilustración con la mesa de trabajo Artboards: {n} Mesas de trabajo: {n} Rearrange All Artboards… Reorganizar todas las mesas de trabajo… + Rearrange… Reorganizar… + Selected Artboards: {n} Mesas de trabajo seleccionadas: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Haz clic en el lienzo para colocar las mesas de trabajo (Esc cancela) Recall Selection Recuperar selección RECENT RECIENTES Recent Recientes diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..e1f8d0cc89 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -357,6 +357,9 @@ Artboards Piirtoalustat Convert to Artboards Muunna piirtoalustoiksi Rearrange All Artboards… Järjestä kaikki piirtoalustat uudelleen… + Rearrange… Järjestä uudelleen… + Selected Artboards: {n} Valitut piirtoalustat: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Sijoita piirtoalustat napsauttamalla kangasta (Esc peruuttaa) Fit to Artwork Bounds Sovita kuvituksen rajoihin Fit to Selected Art Sovita valittuun kuvitukseen Graph Kaavio diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..7d8839460e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3062,6 +3062,9 @@ digits Malayalam Malayalam Scale Artwork with Artboard Mettre à l’échelle l’illustration avec le plan de travail Artboards: {n} Plans de travail : {n} Rearrange All Artboards… Réorganiser tous les plans de travail… + Rearrange… Réorganiser… + Selected Artboards: {n} Plans de travail sélectionnés ({n}) +@msg Click on the canvas to place the artboards (Esc cancels) Cliquez sur la zone de travail pour placer les plans de travail (Échap pour annuler) Recall Selection Rappeler la sélection RECENT RÉCENTS Recent Récents diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..3cf704bff4 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3080,6 +3080,9 @@ Rearrange All બધું ફરીથી ગોઠવો Rearrange All Artboards બધા આર્ટબોર્ડ ફરીથી ગોઠવો Rearrange All Artboards… બધા આર્ટબોર્ડ ફરીથી ગોઠવો… + Rearrange… ફરીથી ગોઠવો… + Selected Artboards: {n} પસંદ કરેલા આર્ટબોર્ડ: {n} +@msg Click on the canvas to place the artboards (Esc cancels) આર્ટબોર્ડ મૂકવા કેનવાસ પર ક્લિક કરો (Esc રદ કરે છે) Rearrange Artboards આર્ટબોર્ડ ફરીથી ગોઠવો Recall Selection પસંદગી યાદ કરો Recent Colors તાજેતરના રંગો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..a4e94e2dd7 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4389,6 +4389,9 @@ arrowhead Feather पंख Rearrange All सभी को फिर से व्यवस्थित करें Rearrange All Artboards सभी आर्टबोर्ड को फिर से व्यवस्थित करें Rearrange All Artboards… सभी आर्टबोर्ड को पुनर्व्यवस्थित करें… + Rearrange… फिर से व्यवस्थित करें… + Selected Artboards: {n} चुने गए आर्टबोर्ड: {n} +@msg Click on the canvas to place the artboards (Esc cancels) आर्टबोर्ड प्लेस करने के लिए कैनवास पर क्लिक करें (Esc से कैंसल करें) Rearrange Artboards रीरेंज आर्टबोर्ड Recall Selection सिलेक्शन वापस लाएँ Recent हाल के diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..5090c8611e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3639,6 +3639,9 @@ mark-style Japanese Japán Rearrange All Összes átrendezése Rearrange All Artboards Összes rajztábla átrendezése Rearrange All Artboards… Összes rajztábla átrendezése… + Rearrange… Átrendezés… + Selected Artboards: {n} Kijelölt rajztáblák: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Kattints a vászonra a rajztáblák elhelyezéséhez (Esc: mégse) Recall Selection Kijelölés visszahívása Recent Legutóbbi RECENT LEGUTÓBBI diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..2d6cb32cd4 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -958,6 +958,9 @@ Artboards Artboard Convert to Artboards Konversi ke artboard Rearrange All Artboards… Atur ulang semua artboard… + Rearrange… Atur ulang… + Selected Artboards: {n} Artboard terpilih: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Klik kanvas untuk menempatkan artboard (Esc membatalkan) Fit to Artwork Bounds Sesuaikan ke batas karya seni Fit to Selected Art Sesuaikan ke karya seni terseleksi Graph Grafik diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..f4815b087e 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3122,6 +3122,9 @@ digits Malayalam Malayalam Scale Artwork with Artboard Scala la grafica con la tavola da disegno Artboards: {n} Tavole da disegno: {n} Rearrange All Artboards… Ridisponi tutte le tavole da disegno… + Rearrange… Ridisponi… + Selected Artboards: {n} Tavole da disegno selezionate: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Fai clic sull'area di lavoro per posizionare le tavole da disegno (Esc annulla) Recall Selection Richiama selezione RECENT RECENTI Recent Recenti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..9ac7433248 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -412,6 +412,9 @@ digits Malayalam マラヤーラム数字 Artboards アートボード Convert to Artboards アートボードに変換 Rearrange All Artboards… すべてのアートボードを再配置… + Rearrange… 再配置… + Selected Artboards: {n} 選択したアートボード: {n} +@msg Click on the canvas to place the artboards (Esc cancels) キャンバスをクリックしてアートボードを配置します (Esc でキャンセル) Fit to Artwork Bounds アートワーク境界に合わせる Fit to Selected Art 選択オブジェクトに合わせる Graph グラフ diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..8da0dd59d7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2493,6 +2493,9 @@ Artboards სამუშაო დაფები Convert to Artboards სამუშაო დაფებად გარდაქმნა Rearrange All Artboards… ყველა სამუშაო დაფის გადალაგება… + Rearrange… გადალაგება… + Selected Artboards: {n} მონიშნული სამუშაო დაფები: {n} +@msg Click on the canvas to place the artboards (Esc cancels) დაწკაპეთ ტილოზე სამუშაო დაფების განსათავსებლად (Esc აუქმებს) Fit to Artwork Bounds ნახატის საზღვრებზე მორგება Fit to Selected Art მონიშნულ ნახატზე მორგება Graph დიაგრამა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..8bba69752a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -405,6 +405,9 @@ digits Malayalam 말라얄람어 Artboards 아트보드 Convert to Artboards 아트보드로 변환 Rearrange All Artboards… 모든 아트보드 재정렬… + Rearrange… 재정렬… + Selected Artboards: {n} 선택한 아트보드: {n} +@msg Click on the canvas to place the artboards (Esc cancels) 캔버스를 클릭하여 아트보드를 배치하세요(Esc로 취소) Fit to Artwork Bounds 아트워크 경계에 맞추기 Fit to Selected Art 선택한 아트에 맞추기 Graph 그래프 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..2e2bbc801f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -945,6 +945,9 @@ liquify-list-end {0}, {1} {0} en {1} Artboards Tekengebieden Convert to Artboards Converteren naar tekengebieden Rearrange All Artboards… Alle tekengebieden herschikken… + Rearrange… Herschikken… + Selected Artboards: {n} Geselecteerde tekengebieden: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Klik op het canvas om de tekengebieden te plaatsen (Esc annuleert) Fit to Artwork Bounds Op artworkgrenzen passend maken Fit to Selected Art Op geselecteerd artwork passend maken Graph Grafiek diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..7dec21b241 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -310,6 +310,9 @@ Artboards Obszary kompozycji Convert to Artboards Konwertuj na obszary kompozycji Rearrange All Artboards… Przestaw wszystkie obszary kompozycji… + Rearrange… Przestaw… + Selected Artboards: {n} Zaznaczone obszary kompozycji: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Kliknij obszar roboczy, aby umieścić obszary kompozycji (Esc anuluje) Fit to Artwork Bounds Dopasuj do granic kompozycji Fit to Selected Art Dopasuj do zaznaczonej kompozycji Graph Wykres diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..5e9251d5bb 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2554,6 +2554,9 @@ digits Malayalam Malaiala Scale Artwork with Artboard Dimensionar Arte com a Mesa de Trabalho Artboards: {n} Mesas de Trabalho: {n} Rearrange All Artboards… Reorganizar Todas as Mesas de Trabalho… + Rearrange… Reorganizar… + Selected Artboards: {n} Mesas de Trabalho Selecionadas: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Clique na tela para posicionar as mesas de trabalho (Esc cancela) Recall Selection Relembrar Seleção Recent Colors Cores Recentes Recent Files Arquivos Recentes diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..3a3a301a38 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3104,6 +3104,9 @@ digits Malayalam Малаялам Scale Artwork with Artboard Масштабировать иллюстрацию вместе с монтажной областью Artboards: {n} Монтажные области: {n} Rearrange All Artboards… Переставить все монтажные области… + Rearrange… Переставить… + Selected Artboards: {n} Выбранные монтажные области: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Щёлкните холст, чтобы разместить монтажные области (Esc отменяет) Recall Selection Восстановить выделение RECENT ПОСЛЕДНИЕ Recent Последние diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..4692322465 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2995,6 +2995,9 @@ digits Malayalam Malayalam Scale Artwork with Artboard Skala grafik med rityta Artboards: {n} Ritytor: {n} Rearrange All Artboards… Ordna om alla ritytor… + Rearrange… Ordna om… + Selected Artboards: {n} Markerade ritytor: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Klicka på arbetsytan för att placera ritytorna (Esc avbryter) Recall Selection Hämta markering RECENT SENASTE Recent Senaste diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..aaeaeb33d1 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -517,6 +517,22 @@ fn attributes_panel_options_strings_are_in_complete_catalogs() { } } +/// Rearrange for selected artboards: the Artboards panel menu's Rearrange…, its dialog's count and +/// the message while it waits for its click on the canvas. +#[test] +fn rearrange_selected_artboards_strings_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Rearrange…", "Selected Artboards: {n}"] { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + let hint = crate::dialogs::rearrange_artboards::PLACE_HINT; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, hint), hint, "{code}"); + } +} + /// Area Type Options › First Baseline's choices (the dropdown reads them in the "effect" context, /// falling back to the plain row). #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..170a8da290 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2843,6 +2843,9 @@ digits Malayalam Malayalam Scale Artwork with Artboard Çalışma Yüzeyi ile Resmi Ölçeklendirin Artboards: {n} Çalışma yüzeyleri: {n} Rearrange All Artboards… Tüm Çalışma Yüzeylerini Yeniden Düzenleme… + Rearrange… Yeniden Düzenle… + Selected Artboards: {n} Seçili çalışma yüzeyleri: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Çalışma yüzeylerini yerleştirmek için tuvale tıklayın (Esc iptal eder) Recall Selection Seçimi Geri Çağır RECENT SON Recent Son diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..d44e2fc353 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3114,6 +3114,9 @@ digits Malayalam Малаялам Scale Artwork with Artboard Масштабувати ілюстрацію разом із монтажною областю Artboards: {n} Монтажні області: {n} Rearrange All Artboards… Переставити всі монтажні області… + Rearrange… Переставити… + Selected Artboards: {n} Вибрані монтажні області: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Клацніть полотно, щоб розмістити монтажні області (Esc скасовує) Recall Selection Відновити виділення RECENT ОСТАННІ Recent Останні diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..b047b0382e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3431,6 +3431,9 @@ mark-style Japanese Kiểu Nhật Rearrange All Sắp xếp lại tất cả Rearrange All Artboards Sắp xếp lại tất cả bảng vẽ Rearrange All Artboards… Sắp xếp lại tất cả bảng vẽ… + Rearrange… Sắp xếp lại… + Selected Artboards: {n} Bảng vẽ đã chọn: {n} +@msg Click on the canvas to place the artboards (Esc cancels) Bấm vào khung vẽ để đặt các bảng vẽ (Esc để hủy) Recall Selection Khôi phục vùng chọn RECENT GẦN ĐÂY Recent Gần đây diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..feea46f4a0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2966,6 +2966,9 @@ digits Malayalam 马拉雅拉姆数字 Scale Artwork with Artboard 随画板缩放图稿 Artboards: {n} 画板:{n} Rearrange All Artboards… 重新排列所有画板… + Rearrange… 重新排列… + Selected Artboards: {n} 选定的画板:{n} +@msg Click on the canvas to place the artboards (Esc cancels) 单击画布以放置画板 (Esc 取消) Recall Selection 召回选区 RECENT 最近使用 Recent 最近使用 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..35e3165ad7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4412,6 +4412,9 @@ digits Malayalam 馬來亞拉姆數字 Scale Artwork with Artboard 隨工作區域縮放圖稿 Artboards: {n} 工作區域:{n} Rearrange All Artboards… 重新排列所有工作區域… + Rearrange… 重新排列… + Selected Artboards: {n} 選取的工作區域:{n} +@msg Click on the canvas to place the artboards (Esc cancels) 按一下畫布以放置工作區域 (Esc 取消) Recall Selection 叫出選取範圍 RECENT 最近使用 Recent 最近使用 diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index d80b69038b..d310e84c78 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -236,8 +236,10 @@ fn artboard_items(app: &VectorcraftApp) -> Vec { } } v.push(Sep); - if n > 1 { - v.push(c("Rearrange", "artboard.rearrange")); + // Rearrange lays out the selected artboards: a click on the item opens its dialog + // (`canvas::context`), whose OK waits for a click on the canvas. + if !sel.is_empty() { + v.push(cp("Rearrange", "artboard.rearrange", json!({ "indices": sel }))); } if facts.map_or_else(|| boards::fit_has_art(app, &free), |f| f.any_art) { v.push(c("Fit to Artwork Bounds", "artboard.fitToArt")); diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 7186f0707d..e4ed40b2fb 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -186,6 +186,14 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) { { return; } + // The Artboard tool's Rearrange (its canvas menu) opens Rearrange for the artboards it lists, + // whose OK waits for a click on the canvas. + if id == "artboard.rearrange" + && let Some(indices) = crate::dialogs::rearrange_artboards::menu_indices(&p) + { + crate::dialogs::rearrange_artboards::open_selected(app, &indices); + return; + } // Params first: some dialogs' fields take a look through the session (Move's last move). if p.as_object().is_none_or(|o| o.is_empty()) && let Some((kind, fields)) = menu_dialog(app, id) diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 94560b9f76..2f4a4715a2 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -221,6 +221,16 @@ pub(crate) fn selected(app: &VectorcraftApp, n: usize) -> usize { /// The selected artboards (of `n`): while the Artboard tool is in use, those it has selected /// (Shift-click, #1139), else the active one. pub(crate) fn picked(app: &VectorcraftApp, n: usize) -> Vec { + let mut all = tool_selection(app, n); + if all.is_empty() { + all.push(selected(app, n)); + } + all +} + +/// The artboards (of `n`) the Artboard tool has selected while it is in use, sorted and once +/// each; empty with another tool or with none selected. +pub(crate) fn tool_selection(app: &VectorcraftApp, n: usize) -> Vec { let tool = (app.session.tool_id() == "artboard").then(|| app.session.tool_options()["selected"].clone()); let mut all: Vec = tool .iter() @@ -230,9 +240,6 @@ pub(crate) fn picked(app: &VectorcraftApp, n: usize) -> Vec { .filter_map(|i| usize::try_from(i).ok()) .filter(|i| *i < n) .collect(); - if all.is_empty() { - all.push(selected(app, n)); - } all.sort_unstable(); all.dedup(); all @@ -721,7 +728,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { set_pstate(ui.ctx(), "ab-keys", keys.then_some(app.frame_iteration())); let n = abs.len(); widgets::bottom_bar(ui, |ui| { - if widgets::icon_button_enabled(ui, "dc-rearrange", tl!("Rearrange All Artboards"), false, n > 1, 24.0).clicked() { + // With artboards selected by the Artboard tool, Rearrange for those. + if !tool_selection(app, n).is_empty() { + if widgets::icon_button_enabled(ui, "dc-rearrange", tl!("Rearrange"), false, true, 24.0).clicked() { + open_rearrange_selected(app); + } + } else if widgets::icon_button_enabled(ui, "dc-rearrange", tl!("Rearrange All Artboards"), false, n > 1, 24.0).clicked() { open_rearrange(app); } ui.add_space((ui.available_width() - 4.0 * 28.0).max(0.0)); @@ -766,6 +778,16 @@ pub(crate) fn open_rearrange(app: &mut VectorcraftApp) { app.run("ui.menuDialog", json!({ "command": "artboard.rearrange" })).ok(); } +/// Open Rearrange for the selected artboards ([`picked`]), whose OK waits for a click on the +/// canvas. +pub(crate) fn open_rearrange_selected(app: &mut VectorcraftApp) { + let n = app.session.active().map_or(0, |d| d.doc.artboards.len()); + if n > 0 { + let indices = picked(app, n); + crate::dialogs::rearrange_artboards::open_selected(app, &indices); + } +} + pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let n = app.session.active().map(|d| d.doc.artboards.len()).unwrap_or(0); let sel = selected(app, n); @@ -797,6 +819,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Rearrange All Artboards…"), n > 1, false) { open_rearrange(app); } + if menu_item(ui, tl!("Rearrange…"), !tool_selection(app, n).is_empty(), false) { + open_rearrange_selected(app); + } ui.separator(); if menu_item(ui, tl!("Fit to Artwork Bounds"), n > 0, false) { app.run("artboard.fitToArt", json!({ "indices": picked(app, n) })).ok(); diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index b52d1da682..ba7a01eee2 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -1601,16 +1601,17 @@ fn the_artboard_tools_menu_lists_the_pages_entries_in_order() { } /// An entry whose command can't run is left out: Cut with every artboard selected, or a locked one; -/// Delete Artboards in a document of one; Select All Artboards with all selected; Rearrange with one; -/// Fit to Artwork Bounds without art; Switch Orientation on a square artboard. +/// Delete Artboards in a document of one; Select All Artboards with all selected; Fit to Artwork +/// Bounds without art; Switch Orientation on a square artboard. Rearrange lays out the one selected +/// artboard. #[test] fn the_artboard_tools_menu_leaves_out_what_cannot_run() { let shown = |app: &VectorcraftApp, label: &str| menu_labels(&crate::menus::context_items(app)).contains(&label); let mut app = menu_app(1); - for label in ["Cut", "Delete Artboards", "Delete Empty Artboards", "Select All Artboards", "Rearrange", "Fit to Artwork Bounds"] { + for label in ["Cut", "Delete Artboards", "Delete Empty Artboards", "Select All Artboards", "Fit to Artwork Bounds"] { assert!(!shown(&app, label), "{label} with one empty artboard"); } - assert!(shown(&app, "Copy") && shown(&app, "Switch Orientation")); + assert!(shown(&app, "Copy") && shown(&app, "Switch Orientation") && shown(&app, "Rearrange")); app.session.execute("artboard.setProps", &json!({"index": 0, "width": 50})).unwrap(); assert!(!shown(&app, "Switch Orientation"), "a square artboard"); @@ -1782,6 +1783,23 @@ fn the_artboard_tools_menu_deletes_empty_artboards_and_opens_dialogs() { assert_eq!(selected(&app, 1), 0); } +/// The panel's Rearrange button and Rearrange… lay out the artboards the Artboard tool has +/// selected, once each and in document order; with another tool nothing is selected by it, so the +/// button is Rearrange All Artboards and Rearrange… is off, while the other entries still act on +/// the active artboard. +#[test] +fn the_panels_rearrange_lays_out_only_what_the_artboard_tool_selected() { + let mut app = menu_app(3); + app.session.set_tool_option("selected", &json!([2, 0, 2])); + assert_eq!(tool_selection(&app, 3), [0, 2]); + open_rearrange_selected(&mut app); + let d = app.ui.dialog.take().unwrap(); + assert_eq!((d.kind.as_str(), d.fields["indices"].clone()), (crate::dialogs::rearrange_artboards::KIND, json!([0, 2]))); + app.select_tool("selection"); + select(&mut app, 1); + assert_eq!((tool_selection(&app, 3), picked(&app, 3)), (vec![], vec![1]), "another tool"); +} + /// A lock entry lists only the artboards it changes and is left out when it has none, so it never /// records an undo step that changes nothing. #[test] diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f8bce4e088..46d3c389bf 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -23,6 +23,21 @@ pub struct BrushKeyColorPick { pub press: Option, } +/// Rearrange for selected artboards, confirmed and waiting for the click on the canvas that places +/// the grid's top-left: the document (`DocState::uid`) and the tool it was confirmed in, and the +/// `artboard.rearrange` parameters, `indices` included, with the `Artboard::id` of each listed +/// artboard (`ids`), so a placement whose artboards moved in the list or were removed is dropped. +/// `armed` is false until the canvas has seen one frame of it, so the Enter that confirmed the +/// dialog does not also place the artboards. +#[derive(Clone, Debug)] +pub struct RearrangePlacement { + pub doc: u64, + pub tool: String, + pub params: Value, + pub ids: Vec, + pub armed: bool, +} + /// Per-document view (camera). #[derive(Clone, Copy, Debug, Serialize, Deserialize)] pub struct View { @@ -636,6 +651,10 @@ pub struct UiState { pub dialog: Option, #[serde(skip)] pub brush_key_color_pick: Option, + /// Rearrange for selected artboards waiting for its click on the canvas + /// (`dialogs::rearrange_artboards`). + #[serde(skip)] + pub rearrange_placement: Option, /// Messages to show in a dialog once the open one is closed (`dialogs::confirm::tell`), in /// the order they came. #[serde(skip)] @@ -1359,6 +1378,7 @@ impl Default for UiState { view: ViewFlags::default(), dialog: None, brush_key_color_pick: None, + rearrange_placement: None, told: vec![], answering_control: false, flyout: None, diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..345b743a49 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9326,22 +9326,49 @@ page in the page's order, and no entries for objects or the view: Cut (`artboard (`edit.paste`), Undo, Redo, New Artboard (`artboard.new`), Duplicate Artboards (`artboard.duplicate`), Rename (`artboard.rename`), Delete Artboards (`artboard.delete` with `indices`), Delete Empty Artboards (`artboard.deleteEmpty`), Select All Artboards (`artboard.selectAll`), Lock Artboards and Unlock Artboards -(`artboard.setProps` with `locked`), Rearrange (`artboard.rearrange`), Fit to Artwork Bounds (`artboard.fitToArt`), -Switch Orientation (`artboard.switchOrientation`), Artboard Options (`tool.options {tool: "artboard"}`) and Export -(`file.exportForScreens`). Exit Isolation Mode and the Unlock submenu for locked objects under the pointer follow them. -Cut, Copy, Duplicate Artboards, Rename, Delete Artboards, Lock Selected, Unlock Selected, Fit to Artwork Bounds, Switch -Orientation and Export act on the artboards the tool has selected, else the active one. Artboard Options opens on the -active artboard. New Artboard, Paste, Undo, Redo, Delete Empty Artboards, Select All Artboards and Rearrange do not act on -the selected artboards. Lock All and Unlock All act on every artboard, and Lock All Except Selected acts on the artboards -that are not selected. A right-click on an artboard that is not selected first selects it alone. An entry that cannot -run is left out: Cut with a locked artboard or every artboard selected, Delete Artboards with no artboard to delete, Select All Artboards with every artboard selected, Rearrange with -one artboard, Fit to Artwork Bounds with no art on a selected unlocked artboard, Switch Orientation with no selected -artboard to change, and a lock entry with no artboard to change. The menu measures the art for Delete Empty Artboards and +(`artboard.setProps` with `locked`), Rearrange (`artboard.rearrange` with `indices`), Fit to Artwork Bounds +(`artboard.fitToArt`), Switch Orientation (`artboard.switchOrientation`), Artboard Options +(`tool.options {tool: "artboard"}`) and Export (`file.exportForScreens`). Exit Isolation Mode and the Unlock submenu +for locked objects under the pointer follow them. Cut, Copy, Duplicate Artboards, Rename, Delete Artboards, Lock +Selected, Unlock Selected, Rearrange, Fit to Artwork Bounds, Switch Orientation and Export act on the artboards the tool +has selected, else the active one. Artboard Options opens on the active artboard. New Artboard, Paste, Undo, Redo, +Delete Empty Artboards and Select All Artboards do not act on the selected artboards. Lock All and Unlock All act on +every artboard, and Lock All Except Selected acts on the artboards that are not selected. A right-click on an artboard +that is not selected first selects it alone. An entry that cannot run is left out: Cut with a locked artboard or every +artboard selected, Delete Artboards with no artboard to delete, Select All Artboards with every artboard selected, Fit +to Artwork Bounds with no art on a selected unlocked artboard, Switch Orientation with no selected artboard to change, +and a lock entry with no artboard to change. The menu measures the art for Delete Empty Artboards and Fit to Artwork Bounds once, at the right-click. Paste centers copied artboards on the right-click's point (`edit.paste {artboardsAt: [x, y]}`) and centers copied objects there too (`center`). Chosen from a menu or the command palette with the tool in use, `artboard.new` makes the new artboard active, `artboard.duplicate` selects the copies, and `artboard.delete` and `artboard.deleteEmpty` make a remaining artboard active. +Rearrange for selected artboards: the +[Rearrange artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/rearrange-artboards.html) +help page describes rearranging only the artboards picked with the Artboard tool, with the same layout, order, count, +spacing and move-artwork choices as for all artboards, and a click on the canvas that puts the arrangement in place. +`artboard.rearrange {indices: [n…]}` lays out only those artboards (zero-based, sorted, an index given twice counts once), +in document order, and leaves every other artboard, its art and its guides where they are; `at: [x, y]` puts the +grid's top-left there, else at the first listed artboard's top-left. A listed locked artboard stays where it is and +keeps its cell. With `moveArtwork`, an object moves with the listed artboard its center is on; an object whose center +is on another artboard stays. `indices` that is not a list, an empty list, an entry that is not a whole number and an +`at` that is not [x, y] are refused before anything moves, and an index past the last artboard is `no such artboard`. +The reply adds `indices` and `moved`, the number of artboards that moved; with none moved (every listed artboard +locked, or already in place) no undo step is recorded. Without `indices` the command lays out every artboard as +before, and its reply is `{artboards, rows, columns}`. In the desktop app, the Artboard tool's canvas menu and +Contextual Task Bar (Rearrange), and while the Artboard tool is in use the Artboards panel's menu (Rearrange…) and its +Rearrange button, open the Rearrange dialog (kind `rearrangeArtboards` with field `indices`) for the artboards the tool +has selected, showing their count. With another tool Rearrange… is off and the panel's button is Rearrange All +Artboards. Its OK changes nothing yet: the grid's outline follows the pointer, and the +next press on the canvas runs `artboard.rearrange` with `indices` and `at` at the press, as one undo step. Enter, when +no other control has the keyboard focus, runs it with `at` at the pointer over the canvas, else without `at` (the grid at the first selected artboard's top-left). +A press with Space held pans or zooms as usual and places nothing. Esc, another tool or another document cancels it +without an edit. The status bar reads "Click on the canvas to place the +artboards (Esc cancels)" meanwhile. The top-left reference point, the outline, the fallback to the first artboard's +corner and the rules for locked artboards and art on other artboards are VectorCraft's own. Object › Artboards › +Rearrange All Artboards…, the Artboards panel's Rearrange All Artboards… and the Properties panel's Rearrange All still +lay out every artboard at once. + Locked artboards: `artboard.setProps {index, locked: true}` locks an artboard and `{index, locked: false}` unlocks it, each in one undo step. The Artboards panel's lock column, left of a row's options icon, shows a lock on a locked artboard, and a click there runs this command. A locked artboard keeps its place and size. `artboard.setProps` with a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..50a9451aa2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1093,7 +1093,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The contextual task bar's handle drags it anywhere on the canvas (kept whole on it as the window resizes); unpinned it keeps that offset as it follows the selection, and its More Options menu hides it, pins its position across selection changes (`window.taskBar.pin`), resets it under the selection (`window.taskBar.reset`) and shows the Properties panel. As in Illustrator the position isn't kept across launches. Not done: the bar's variants for other tools (only the selection tools, the Type tools, the basic shape tools, the Smooth tool and the Artboard tool show it). - A click on another object moves the contextual task bar under it without hiding it for the press; it gives way only to a drag (#4681). - With one image selected, the contextual task bar offers Image Trace, which traces the image at once with the Default preset (the Image Trace panel is left as it was), and Crop Image; with an Image Trace object it offers Expand, which keeps only the traced paths. This follows Illustrator's bar: for a selected image it includes Image Trace, Retype and Crop Image, and traced artwork can be expanded from it ([Contextual Task Bar announcement](https://community.adobe.com/announcements-651/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580)). Offset Path and Simplify, which don't apply to an image, aren't offered for one. Not done: Retype, which the app doesn't have. - - With the Artboard tool, the contextual task bar sits under the selected artboards and offers Resize (Artboard Options for the active artboard), Duplicate (each selected artboard, in one undo step, the copies then selected), Rearrange All (with two or more artboards) and Export (Export for Screens with the selected artboards checked). This follows Illustrator's bar: while the Artboard tool is in use, it has options for resizing, duplicating and exporting artboards (the [Contextual Task Bar announcement](https://community.adobe.com/questions-652/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580); Rearrange and Export on the bar: [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/)). + - With the Artboard tool, the contextual task bar sits under the selected artboards and offers Resize (Artboard Options for the active artboard), Duplicate (each selected artboard, in one undo step, the copies then selected), Rearrange (the selected artboards, placed with a click on the canvas) and Export (Export for Screens with the selected artboards checked). This follows Illustrator's bar: while the Artboard tool is in use, it has options for resizing, duplicating and exporting artboards (the [Contextual Task Bar announcement](https://community.adobe.com/questions-652/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580); Rearrange and Export on the bar: [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/)). - On a blank canvas the contextual task bar offers Draw (Pencil), which switches to the Pencil tool, and Place Image, which picks files for the Place dialog, as the help page lists for a new document (). VectorCraft's own rules: the bar shows them while a selection tool is in use in a document with no artwork (layers and guides only), sits under the active artboard (under the canvas's center when the artboard is out of view), and leaves out the Fill, Stroke, Recolor Artwork and Lock controls. Not done: Generate Vectors. Evidence: `a_blank_canvas_offers_draw_and_place_image`, `the_blank_canvas_bar_draws_with_the_pencil_and_places_an_image` and `the_blank_canvas_bar_wraps_on_a_narrow_canvas` in `crates/ui-egui/src/tests/taskbar.rs`. - The contextual task bar offers more next steps by selection (): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, point or area type Convert To Area Type or Convert To Point Type beside Create Outlines, and type on a path, for which the overview names an item to add an effect and rearrange the text, Type on a Path Options (`type.pathOptions`; its options: ) beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`. - While a Type tool (Type, Area Type, Type on a Path and their vertical versions) adds or edits type, the contextual task bar shows the font family menu, the font style menu, the Font Size combo and the Fill chip (); the Touch Type tool shows no bar, as the same page describes. Type selected with a selection tool shows the same three font controls beside its Create Outlines, conversion and Type on a Path items (). The controls act as the Character panel's do: on the characters a Type tool selects, else on every selected type object, with the size left blank where the sizes differ. VectorCraft's own rules: a Type tool's bar leaves out the object actions, the Stroke chip, Recolor Artwork and Lock; a Type tool shows no bar before it adds type or with other art selected; type selected with other art shows no font controls; the font controls go on a second row when one row would be wider than the canvas, and narrow to fit a canvas narrower than they are; while a Type tool edits type, the Fill chip shows the edited characters' fill ("?" where it differs). Evidence: `the_type_tools_show_font_and_fill_controls`, `the_type_tools_show_no_bar_without_type`, `selected_type_shows_font_controls_beside_its_actions`, `the_task_bars_font_size_sets_what_the_character_panel_would`, `the_type_tools_fill_chip_activates_the_fill`, `the_type_tools_bar_is_named_and_stays_on_the_canvas`, `selected_types_font_controls_take_a_second_row_on_a_narrow_canvas` and `the_type_tools_fill_chip_shows_the_edited_characters_fill` in `crates/ui-egui/src/tests/taskbar.rs`. @@ -1648,6 +1648,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With the Artboard tool selecting several artboards, Paste in Place, Paste in Front and Paste in Back put a copy of the copied art on each, where it was on the artboard it was copied from, in one undo step, as the public [Cut, copy, and paste artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/cut-copy-and-paste-artboards.html) page describes (`artboards` on the three commands). Art copied from no artboard keeps its place on the first selected artboard and its offset to it on the others, and an `artboard` or `artboards` index the document does not have is an error; these rules are VectorCraft's own. The three commands used to paste one copy, on the active artboard, and an `artboard` index the document did not have pasted the art where it was. A replay of the journal repeats a Cut or Copy made with the Artboard tool on the artboards it took (`edit.cut` and `edit.copy` record `selectedArtboards` and `art`), whichever tool is chosen in the new session and whatever is selected there. A recorded action follows the tool chosen when it plays. The replay used to act on the objects selected then, or stop with nothing selected. This rule is VectorCraft's own. With the Artboard tool, the canvas context menu lists the entries of the public [Use the artboard context menu](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/use-artboard-context-menu.html) page in its order: Cut, Copy, Paste at the pointer, Undo, Redo, New Artboard, Duplicate Artboards, Rename (`artboard.rename`), Delete Artboards, Delete Empty Artboards, Select All Artboards (`artboard.selectAll`), Lock Artboards and Unlock Artboards, Rearrange, Fit to Artwork Bounds, Switch Orientation (`artboard.switchOrientation`), Artboard Options and Export. A right-click on an artboard that is not selected selects it first. + Rearrange lays out only the artboards the Artboard tool has selected, as the [Rearrange artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/rearrange-artboards.html) help page describes for a selection: the canvas context menu's Rearrange, the Contextual Task Bar's Rearrange, the Artboards panel menu's Rearrange… and the panel's Rearrange button with the Artboard tool open the Rearrange dialog for them, and after OK the grid's outline follows the pointer until a click on the canvas places its top-left there, in one undo step (`artboard.rearrange {indices, at}`); Enter places it from the keyboard, a Space-drag still pans, and Esc or another tool cancels it. The other artboards, their art and their guides stay where they are, and a selected locked artboard keeps its place and its cell. The top-left reference point and the handling of locked artboards and of art on unselected artboards are VectorCraft's own. Evidence: `tests::newdoc::{rearrange_lays_out_only_the_listed_artboards, rearrange_of_listed_artboards_starts_at_the_first_and_keeps_locked_ones, rearrange_refuses_bad_indices_and_at}` in `crates/engine`, `canvas::tests::rearrange_places_the_selected_artboards_where_the_canvas_is_clicked` and `dialogs::rearrange_artboards::tests::rearrange_from_the_canvas_menu_waits_for_a_click_with_the_selected_artboards` in `crates/ui-egui`. The Artboards panel menu's New Artboard adds the artboard in one undo step and makes it the active one, as the panel's button, the Control bar and Properties do; with the Artboard tool it is then the only one selected. This is VectorCraft's own rule. The menu item used to leave the active artboard where it was. With the Artboard tool, Paste and Paste in Place make the first pasted artboard the active one (the navigator's and the Artboards panel's), and Cut makes the artboard before the first cut one active (the new first artboard when artboard 1 was cut). A command that chooses another document (`document.activate`) starts the tool on that document's active artboard, as choosing its tab does, and File › Revert keeps the active artboard and starts the tool on it. Paste used to leave the active artboard where it was while the tool had the pasted artboard active, and Cut left the active artboard on the artboard after the cut one while the tool had the one before it. With the Artboard tool, an action that reverts the document or switches to another document and back (`command.batch`), and the Actions panel menu's Batch… over a folder whose files it closes or over data sets with a Revert step (`action.batch`), keep the active artboard and start the tool on it, as File › Revert does. They used to make artboard 1 the active one. From 557a6be962f5a546c6498913ce1c6da3d718b07e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 22:33:51 -0800 Subject: [PATCH 30/78] Document Info: an image placed at a very small size keeps its resolution The test for a transform that leaves an image no area compares the determinant with the product of the two pixel axes' lengths instead of a fixed 1e-12, so a placement at 1e-7 pt per pixel still reports its resolution. The package report test expects the new Linked Images row with the format and resolution. --- crates/engine/src/cmd/docinfo.rs | 17 +++++++++++++++-- crates/engine/src/tests/package.rs | 4 ++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 3fa7cce615..f58eb97e41 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -209,8 +209,10 @@ impl ImageRow { // A distorted image is measured at its middle, as `image.info` measures it. let xf = vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf); let ppi = super::place::effective_ppi(xf); - // A transform that lays both pixel axes on one line leaves the image no area. - let has_area = xf.determinant().abs() > 1e-12; + // A transform that lays both pixel axes on one line leaves the image no area. The + // determinant is compared with the product of the two axes' lengths, at any scale. + let [xx, xy, yx, yy, ..] = xf.as_coeffs(); + let has_area = xf.determinant().abs() > 1e-9 * xx.hypot(xy) * yx.hypot(yy); let embedded = im.link.is_none(); let memory = || u64::from(im.width).checked_mul(u64::from(im.height))?.checked_mul(4); Self { @@ -2469,6 +2471,17 @@ mod tests { assert_eq!(rows(&selected, "linkedImages"), [linked[2].clone()]); } + /// An image placed at a very small size still has an area, so its row gives a resolution. + #[test] + fn a_tiny_placement_still_gives_a_resolution() { + let mut s = Session::new(); + images_in(&mut s, &[("a", "image/png", Some("/art/huge.png"), 100_000, 100_000, Affine::scale(1e-7))]); + let i = s.execute("document.info", &json!({})).unwrap(); + let ppi = i["imageObjects"][0]["effectivePpi"].as_array().map(|v| v.iter().map(|v| v.as_f64().unwrap_or(0.0)).collect::>()); + let ppi = ppi.unwrap_or_default(); + assert!(ppi.len() == 2 && ppi.iter().all(|v| (v / 7.2e8 - 1.0).abs() < 1e-9), "{}", i["imageObjects"][0]); + } + /// A number of bytes reads in B below 1 KiB, else in KiB, MiB or GiB to a tenth, and a /// resolution to a tenth without a trailing `.0`. #[test] diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index f146e39941..e39fe2885f 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -792,7 +792,7 @@ fn the_document_info_report_has_every_category() { assert!(text.contains(&format!("\n{h}\n")), "{h}: {text}"); } assert!(text.contains("Images: 3") && text.contains("Source Sans 3 Regular: built in; embedding allowed"), "{text}"); - assert!(text.contains("red.png: 600 × 300 px — ") && text.contains("Color Mode: RGB") && text.contains("\nSwatches: "), "{text}"); + assert!(text.contains("red.png: PNG; 600 × 300 px; 72 ppi — ") && text.contains("Color Mode: RGB") && text.contains("\nSwatches: "), "{text}"); let fonts = run(&mut s, "document.info", json!({"format": "text", "category": "fonts"}))["text"].as_str().unwrap().to_string(); assert!(fonts.contains("FONTS") && !fonts.contains("OBJECTS"), "{fonts}"); let i = run(&mut s, "document.info", json!({"category": "linkedImages"})); @@ -802,7 +802,7 @@ fn the_document_info_report_has_every_category() { // embedded one with no file. let linked: Vec = i["imageObjects"].as_array().unwrap().iter().filter(|o| o["linked"] == true).cloned().collect(); for (o, r) in linked.iter().zip(i["sections"][0]["rows"].as_array().unwrap()) { - let shown = format!("{} × {} px — {}", o["width"], o["height"], o["file"].as_str().unwrap()); + let shown = format!("PNG; {} × {} px; 72 ppi — {}", o["width"], o["height"], o["file"].as_str().unwrap()); assert_eq!((&o["name"], shown.as_str()), (&r[0], r[1].as_str().unwrap())); } assert_eq!(linked.len(), 2); From 6b123376fd8c572dbac71bab1f6b34ca9ad1328f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 23:51:45 -0800 Subject: [PATCH 31/78] Docs: artboard.rearrange with at and no indices places the whole grid Without indices the command lays out every artboard; at still sets the grid's top-left there. The mcp.md paragraph now says so. --- docs/mcp.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 345b743a49..410b1ac04a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9354,12 +9354,12 @@ keeps its cell. With `moveArtwork`, an object moves with the listed artboard its is on another artboard stays. `indices` that is not a list, an empty list, an entry that is not a whole number and an `at` that is not [x, y] are refused before anything moves, and an index past the last artboard is `no such artboard`. The reply adds `indices` and `moved`, the number of artboards that moved; with none moved (every listed artboard -locked, or already in place) no undo step is recorded. Without `indices` the command lays out every artboard as -before, and its reply is `{artboards, rows, columns}`. In the desktop app, the Artboard tool's canvas menu and -Contextual Task Bar (Rearrange), and while the Artboard tool is in use the Artboards panel's menu (Rearrange…) and its -Rearrange button, open the Rearrange dialog (kind `rearrangeArtboards` with field `indices`) for the artboards the tool -has selected, showing their count. With another tool Rearrange… is off and the panel's button is Rearrange All -Artboards. Its OK changes nothing yet: the grid's outline follows the pointer, and the +locked, or already in place) no undo step is recorded. Without `indices` the command lays out every artboard, and its +reply is `{artboards, rows, columns}`; `at` there puts the grid's top-left at `at` too. In the desktop app, the +Artboard tool's canvas menu and Contextual Task Bar (Rearrange), and while the Artboard tool is in use the Artboards +panel's menu (Rearrange…) and its Rearrange button, open the Rearrange dialog (kind `rearrangeArtboards` with field +`indices`) for the artboards the tool has selected, showing their count. With another tool Rearrange… is off and the +panel's button is Rearrange All Artboards. Its OK changes nothing yet: the grid's outline follows the pointer, and the next press on the canvas runs `artboard.rearrange` with `indices` and `at` at the press, as one undo step. Enter, when no other control has the keyboard focus, runs it with `at` at the pointer over the canvas, else without `at` (the grid at the first selected artboard's top-left). A press with Space held pans or zooms as usual and places nothing. Esc, another tool or another document cancels it From f85fc7614ede48573de4c1b391305148dd4f7473 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:10:09 -0800 Subject: [PATCH 32/78] i18n: Bulgarian translates status and error messages Bulgarian joins COMPLETE_MESSAGES. bg.tsv gets 987 new message rows (982 @msg, 5 @msgplural) for the keys the other complete-message languages translate, plus the liquify and variable context rows the list tests read. Nine existing Bulgarian @msg rows began with a space, so those status messages were shown with a leading space. They are fixed, and the new test message_translations_keep_their_english_edges checks every catalog for a translation that adds whitespace at either end. Docs: docs/localization-parity.md, docs/target-app-parity.md and docs/development.md list Bulgarian with the other complete-message languages. --- crates/ui-egui/src/i18n/bg.tsv | 1031 +++++++++++++++++++++++++++++- crates/ui-egui/src/i18n/tests.rs | 26 +- docs/development.md | 2 +- docs/localization-parity.md | 4 +- docs/target-app-parity.md | 2 +- 5 files changed, 1051 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..85178d48d4 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1283,6 +1283,147 @@ font-technology Variable Променливи Drop Artwork Поставяне на графика @msg {key} must be [x, y] with finite coordinates {key} трябва да е [x, y] с крайни координати @msg ids must contain 1–10000 object ids ids трябва да съдържа от 1 до 10000 идентификатора на обекти +@msg {what} can't be exported in 3D: {e} {what} не може да се експортира в 3D: {e} +@msg asset {id} isn't a 3D asset ресурсът {id} не е 3D ресурс +@msg asset {id} is a 3D asset: assets.export3D writes it ресурсът {id} е 3D ресурс: записва се с assets.export3D +@msg no 3D assets yet: collect an object with a 3D effect first (assets.add3D) все още няма 3D ресурси: първо съберете обект с 3D ефект (assets.add3D) +@msg select an object with a 3D effect (or give its ids) изберете обект с 3D ефект (или задайте идентификаторите му) +@msg select point type or type on a path изберете точков текст или текст по пътя +@msg type on a path in a thread cannot use Dynamic Text: {frames} текст по пътя в свързана верига не може да използва динамичен текст: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} текст по отворен или съставен път не може да се центрира по горния или долния си край: {open} +@msg type on a path with no length or no height cannot be centered: {flat} текст по път без дължина или без височина не може да се центрира: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} текст по пътя в свързана верига не може да се центрира по горния или долния си край: {frames} +@msg select type on a closed path изберете текст по затворен път +@msg `Custom` stands for changed settings: save the preset under another name `Custom` означава променени настройки: запазете предварителната настройка под друго име +@msg the selection has no gradient fill селекцията няма запълване с градиент +@msg the selection has no gradient stroke селекцията няма щрих с градиент +@msg the selection has no pattern fill селекцията няма запълване с мостра +@msg the selection has no pattern stroke селекцията няма щрих с мостра +@msg no gradient swatch `{name}` няма образец на градиент `{name}` +@msg no pattern swatch `{name}` няма образец на мостра `{name}` +@msg the library item is damaged елементът от библиотеката е повреден +@msg its zlib compression is damaged компресията му zlib е повредена +@msg its Zstandard compression is damaged компресията му Zstandard е повредена +@msg it decompresses to more than {_1} MB след декомпресиране заема повече от {_1} MB +@msg its editing data is for a different page данните му за редактиране са за друга страница +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` трябва да е "emBox", "capHeight", "xHeight" или "icfBox" +@msg Choose a .js or .jsx script Изберете скрипт .js или .jsx +@msg Ran {name} Изпълнен е {name} +@msg The script was stopped and its changes were undone Скриптът беше спрян и промените му бяха отменени +@msg a script is running: stop it or wait for it to finish изпълнява се скрипт: спрете го или изчакайте да завърши +@msg this is a compiled script, which cannot be run; use its source text това е компилиран скрипт, който не може да се изпълни; използвайте изходния му текст +@msg the script is not UTF-8 text скриптът не е текст в UTF-8 +@msg the script is too large to run скриптът е твърде голям, за да се изпълни +@msg a drag or an undo group is open; finish it before running a script има отворено влачене или група за отмяна; завършете го, преди да изпълните скрипт +@msg the script left a document that cannot be kept скриптът остави документ, който не може да се запази +@msg the script is no longer in the Scripts folder скриптът вече не е в папката Scripts +@msg the script's run is no longer available изпълнението на скрипта вече не е налично +@msg a failed command changed undo steps that could not be put back, so the script was stopped неуспешна команда промени стъпки за отмяна, които не можаха да се възстановят, затова скриптът беше спрян +@msg a recovery copy could not be written, so the script was not run не можа да се запише копие за възстановяване, затова скриптът не беше изпълнен +@msg Script file access denied Достъпът до файла на скрипта е отказан +@msg Script file exceeds 8 MiB Файлът на скрипта надхвърля 8 MiB +@msg Script file is not open Файлът на скрипта не е отворен +@msg Script file cannot be decoded Файлът на скрипта не може да се декодира +@msg Script file is not a regular file Файлът на скрипта не е обикновен файл +@msg Script file does not exist Файлът на скрипта не съществува +@msg Script file could not be read Файлът на скрипта не можа да се прочете +@msg Script folder has more than 2,048 entries Папката на скрипта има повече от 2,048 елемента +@msg Script file open mode must be r, w, e or a Режимът на отваряне на файла на скрипта трябва да е r, w, e или a +@msg Script file writing is not available Записването на файлове от скрипт не е налично +@msg Script file dialogs are not available Файловите диалогови прозорци за скриптове не са налични +@msg Script files cannot be opened in another application Файловете на скриптове не могат да се отварят в друго приложение +@msg Script file access is unavailable on the web Достъпът до файлове от скрипт не е наличен в уеб версията +@msg Script has 256 files open Скриптът има 256 отворени файла +@msg Script file path exceeds 32,767 characters Пътят до файла на скрипта надхвърля 32,767 знака +@msg Script folder mask takes too many steps to match Маската за папка на скрипта изисква твърде много стъпки за съвпадение +@msg the script opened more file data than one run may open (32 MiB) скриптът отвори повече файлови данни, отколкото е разрешено за едно изпълнение (32 MiB) +@msg File.seek: takes a position and a mode File.seek: приема позиция и режим +@msg vc.run: give a command id, as a string vc.run: задайте идентификатор на команда като низ +@msg vc.run: takes a command id and an object of parameters vc.run: приема идентификатор на команда и обект с параметри +@msg vc.run: the parameters must be an object vc.run: параметрите трябва да са обект +@msg vc.run: the result{place} is too large for a script vc.run: резултатът{place} е твърде голям за скрипт +@msg $.evalFile requires a file path $.evalFile изисква път до файл +@msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: времето за изчакване трябва да е крайно число милисекунди, 0 или повече +@msg $.evalFile: takes a file path and a timeout $.evalFile: приема път до файл и време за изчакване +@msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: ред {line}, колона {column} от {file}: {e} (хвърлена грешка) +@msg {name}: line {line}, column {column}: {e} (thrown) {name}: ред {line}, колона {column}: {e} (хвърлена грешка) +@msg {name}: {e} (thrown) {name}: {e} (хвърлена грешка) +@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: ред {line}, колона {column} от {file}: {e} (ограничение) +@msg {name}: line {line}, column {column}: {e} (limit) {name}: ред {line}, колона {column}: {e} (ограничение) +@msg {name}: {e} (limit) {name}: {e} (ограничение) +@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: ред {line}, колона {column} от {file}: {e} (синтаксис) +@msg {name}: line {line}, column {column}: {e} (syntax) {name}: ред {line}, колона {column}: {e} (синтаксис) +@msg {name}: {e} (syntax) {name}: {e} (синтаксис) +@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: ред {line}, колона {column} от {file}: {e} (спрян) +@msg {name}: line {line}, column {column}: {e} (stopped) {name}: ред {line}, колона {column}: {e} (спрян) +@msg {name}: {e} (stopped) {name}: {e} (спрян) +@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: ред {line}, колона {column} от {file}: {e} (вътрешна грешка) +@msg {name}: line {line}, column {column}: {e} (internal) {name}: ред {line}, колона {column}: {e} (вътрешна грешка) +@msg {name}: {e} (internal) {name}: {e} (вътрешна грешка) +@msg {e} (these files stay written: {paths}) {e} (тези файлове остават записани: {paths}) +@msg $.{name}: give a name, as a string $.{name}: задайте име като низ +@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: задайте локал, например "en" или "de_DE", или null за този на интерфейса +@msg $.localize: give true or false $.localize: задайте true или false +@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: може да се зададе само 512, което включва локализацията, или 0 +@msg $.flags: give a number $.flags: задайте число +@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: скриптовете тук четат и записват само UTF-8 +@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: задайте името на кодировка като низ +@msg $.memCache: the memory cache size cannot be set $.memCache: размерът на кеша в паметта не може да се задава +@msg $.setenv: give a value, as a string $.setenv: задайте стойност като низ +@msg $.setenv: only {_1} can be set $.setenv: може да се зададе само {_1} +@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: стойността има най-много {MAX_ENV_BYTES} букви, цифри и _ . - @ +@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: задайте брой милисекунди от 0 до {MAX_SLEEP_MS} +@msg $.sleep: give a number of milliseconds $.sleep: задайте брой милисекунди +@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: изпълнението не може да чака в обратно извикване на вградена функция, в getter, в преобразуване или във файл, изпълнен от $.evalFile; извикайте го от собствения код на скрипта +@msg $.bp: scripts here have no debugger $.bp: скриптовете тук нямат дебъгер +@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: скриптовете все още не могат да показват диалогов прозорец +@msg {name}: give a message {name}: задайте съобщение +@msg {name}: give the text the field starts with {name}: задайте началния текст на полето +@msg {name}: the message is longer than 16 KiB {name}: съобщението е по-дълго от 16 KiB +@msg {name}: the title is longer than 256 bytes {name}: заглавието е по-дълго от 256 байта +@msg {name}: the text the field starts with is longer than 16 KiB {name}: началният текст на полето е по-дълъг от 16 KiB +@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: диалогов прозорец не може да се отвори в обратно извикване на вградена функция, в getter, в преобразуване или във файл, изпълнен от $.evalFile; извикайте го от собствения код на скрипта +@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: следващият отговор в `answers` е за {_1}, а не за {name} +@msg {name}: `answers` has no answer left for this dialog {name}: в `answers` не е останал отговор за този диалогов прозорец +@msg `answers` must be a list of answers `answers` трябва да е списък с отговори +@msg `answers` has more than {MAX_ANSWERS} answers `answers` има повече от {MAX_ANSWERS} отговора +@msg `answers` is larger than 1 MiB `answers` е по-голям от 1 MiB +@msg must be an object with `kind` and `value` трябва да е обект с `kind` и `value` +@msg must have exactly `kind` and `value` трябва да има точно `kind` и `value` +@msg is an alert's answer, whose `value` must be "ok" е отговор на предупреждение, чиято стойност `value` трябва да е "ok" +@msg is a confirm's answer, whose `value` must be true or false е отговор на потвърждение, чиято стойност `value` трябва да е true или false +@msg is longer than 16 KiB е по-дълъг от 16 KiB +@msg is a prompt's answer, whose `value` must be a string or null е отговор на подкана, чиято стойност `value` трябва да е низ или null +@msg must have `kind` alert, confirm or prompt трябва да има `kind` alert, confirm или prompt +@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` е само за изпълнение без човек, когото да се пита: в приложението човекът отговаря на всеки диалогов прозорец +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` трябва да е цяло число от 1 до {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` е вложен на повече от 64 нива +@msg `args` must be an object `args` трябва да е обект +@msg `args` is larger than 1 MiB `args` е по-голям от 1 MiB +@msg `path` is empty `path` е празен +@msg `installed` takes a `path`, not a `source` `installed` приема `path`, а не `source` +@msg `path` must name a .js or .jsx file `path` трябва да сочи файл .js или .jsx +@msg give exactly one of `path` and `source` задайте точно едно от `path` и `source` +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg vc.document{place} is too large for a script vc.document{place} е твърде голям за скрипт +@msg vc.log: the log of this run is full vc.log: дневникът на това изпълнение е пълен +@msg this function's script run has ended изпълнението на скрипта на тази функция е приключило +@msg the script made more host calls than one run may make скриптът направи повече извиквания към приложението, отколкото е разрешено за едно изпълнение +@msg the script passed more data to and from commands than one run may pass скриптът предаде повече данни към и от команди, отколкото е разрешено за едно изпълнение +@msg the script added more objects and data to the documents than one run may add скриптът добави повече обекти и данни в документите, отколкото е разрешено за едно изпълнение +@msg {what}: the object is not a File or a Folder {what}: обектът не е File или Folder +@msg {what}: the count must be a finite number, 0 or more {what}: броят трябва да е крайно число, 0 или повече +@msg File.seek: the position must be a finite number File.seek: позицията трябва да е крайно число +@msg File.seek: the mode must be 0, 1 or 2 File.seek: режимът трябва да е 0, 1 или 2 +@msg script file is compiled: {value} файлът на скрипта е компилиран: {value} +@msg `name` must be the name of a script engine `name` трябва да е име на скриптов двигател +@msg the main script engine is new for each run and is never kept, so it cannot be dropped основният скриптов двигател е нов при всяко изпълнение и никога не се запазва, затова не може да бъде премахнат +@msg there is no script engine named {name} няма скриптов двигател с име {name} +@msg Running a script Изпълнява се скрипт +@msg Data Recovery can't keep copies in {path}: {e} Възстановяването на данни не може да пази копия в {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Приставките не могат да се зареждат от {path}: {e} +@msg select a path изберете път File Файл File Dimensions Размери на файла @@ -3945,6 +4086,8 @@ digits Malayalam Малаялам Flattener Preset Предварителна настройка за сплескване X X Y Y +@msg the file's layers weren't read ({_1}): it comes in as its page, in one layer слоевете на файла не бяха прочетени ({_1}): той се импортира като своята страница, в един слой +@msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part слоевете на файла не бяха прочетени от данните му за редактиране ({_1}): те идват от частта му PDF Spot Colors Спот цветове Spot Colors… Спот цветове… Spread: Разпространение: @@ -4116,6 +4259,48 @@ digits Malayalam Малаялам Composite Fonts Съставни шрифтове Export Composite Fonts Експортиране на съставни шрифтове Import Composite Fonts Импортиране на съставни шрифтове +@msg each font must be {{name, parts}} всеки шрифт трябва да е {{name, parts}} +@msg unknown key `{k}`; a font takes name and parts неизвестен ключ `{k}`; шрифтът приема name и parts +@msg each font needs a name всеки шрифт изисква име +@msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` не може да е име на съставен шрифт (от 1 до {COMPOSITE_NAME_MAX} знака, без управляващи знаци) +@msg `{name}`: parts must be an object `{name}`: parts трябва да е обект +@msg `{name}`: unknown class `{k}`; the classes are kanji, kana, punctuation, symbols, roman and numerals `{name}`: неизвестен клас `{k}`; класовете са kanji, kana, punctuation, symbols, roman и numerals +@msg `{name}`: {_1} must be an object `{name}`: {_1} трябва да е обект +@msg `{name}`: unknown key `{k}` in {_1} `{name}`: неизвестен ключ `{k}` в {_1} +@msg `{name}`: give the kanji part `{name}`: задайте частта kanji +@msg a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts документът съдържа най-много {COMPOSITE_FONTS_MAX} съставни шрифта +@msg two composite fonts are named `{_1}` два съставни шрифта имат името `{_1}` +@msg `{_1}` is the name of an installed font `{_1}` е името на инсталиран шрифт +@msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} е зададен с `{font}`, който е съставен шрифт +@msg give fonts: [{{name, parts}}…] задайте fonts: [{{name, parts}}…] +@msg path is empty path е празен +@msg fonts must be a list of composite fonts fonts трябва да е списък от съставни шрифтове +@msg names must be strings names трябва да са низове +@msg no composite font named `{n}` няма съставен шрифт с име `{n}` +@msg names must be a list of names names трябва да е списък от имена +@msg no composite fonts to export няма съставни шрифтове за експортиране +@msg not a composite fonts file: {e} не е файл със съставни шрифтове: {e} +@msg not a composite fonts file: no compositeFonts list не е файл със съставни шрифтове: няма списък compositeFonts +@msg the file holds more than {COMPOSITE_FONTS_MAX} composite fonts файлът съдържа повече от {COMPOSITE_FONTS_MAX} съставни шрифта +@msg the file is larger than 4 MB файлът е по-голям от 4 MB +@msg dataBase64 is not base64 dataBase64 не е в base64 +@msg give one of path, data or dataBase64 задайте едно от path, data или dataBase64 +@msg the file holds no composite fonts файлът не съдържа съставни шрифтове +@msg the file holds two composite fonts named `{_1}` файлът съдържа два съставни шрифта с име `{_1}` +@msg `{_1}` can't name a composite font `{_1}` не може да е име на съставен шрифт +@msg {k}: give a font {k}: задайте шрифт +@msg `{name}`: {k}: give a font `{name}`: {k}: задайте шрифт +@msg {k}: size must be {_1} to {_2}% {k}: size трябва да е от {_1} до {_2}% +@msg `{name}`: {k}: size must be {_1} to {_2}% `{name}`: {k}: size трябва да е от {_1} до {_2}% +@msg {k}: baseline must be {_1} to {_2}% {k}: baseline трябва да е от {_1} до {_2}% +@msg `{name}`: {k}: baseline must be {_1} to {_2}% `{name}`: {k}: baseline трябва да е от {_1} до {_2}% +@msg {k}: scale must be {_1} to {_2}% {k}: мащабът трябва да е от {_1} до {_2}% +@msg `{name}`: {k}: scale must be {_1} to {_2}% `{name}`: {k}: мащабът трябва да е от {_1} до {_2}% +@msg {k}: only kana, roman and numerals can be scaled {k}: само kana, roman и numerals могат да се мащабират +@msg `{name}`: {k}: only kana, roman and numerals can be scaled `{name}`: {k}: само kana, roman и numerals могат да се мащабират +@msg {k}: only kana can be scaled at the center {k}: само kana може да се мащабира спрямо центъра +@msg `{name}`: {k}: only kana can be scaled at the center `{name}`: {k}: само kana може да се мащабира спрямо центъра +@msg no composite font няма съставен шрифт Delete Font Изтриване на шрифт Kanji Канджи Kana Кана @@ -4782,6 +4967,10 @@ axis Both И двете @msg Save for Web: the image is empty Запис за уеб: изображението е празно @msg Save writes {_1}, not {_2}: use document.export for other formats Записът записва {_1}, а не {_2}: използвайте document.export за други формати @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Записът записва {_1}, а не {_2}: използвайте file.saveAsTemplate, за да го запишете +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 записва стари файлове .ai, а не шаблони .ait +@msg `groupColors` must be an array `groupColors` трябва да е масив +@msg `preserve` must be an object `preserve` трябва да е обект +@msg `{key}` must be an array `{key}` трябва да е масив @msg Saved recovery data for {title} Запазени данни за възстановяване за {title} @msg Saved to User Defined: {_1} Запазено в Потребителски: {_1} @msg Saved {path} Записано: {path} @@ -4793,13 +4982,18 @@ axis Both И двете @msg Split Into Grid: select paths large enough for the grid Разделяне на мрежа: изберете пътища, достатъчно големи за мрежата @msg Targa files are RGB: colorModel rgb Файловете Targa са RGB: colorModel rgb @msg Text Wrap: select a wrap object Обгръщане на текст: изберете обгръщащ обект -@msg This shortcut file is in a form VectorCraft can't read. Този файл с преки пътища е във формат, който VectorCraft не може да прочете. +@msg This shortcut file is in a form VectorCraft can't read. Този файл с преки пътища е във формат, който VectorCraft не може да прочете. @msg `antiAlias` must be "none", "sharp", "crisp" or "strong" `antiAlias` трябва да е "none", "sharp", "crisp" или "strong" @msg `aspect` must be a number (%) `aspect` трябва да бъде число (%) @msg `at` must be [x, y] `at` трябва да бъде [x, y] @msg `color` must be a colour `color` трябва да бъде цвят @msg `sliders` must be none, oklch or hsl `sliders` трябва да бъде none, oklch или hsl @msg OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство +@msg the Color Picker is not open Палитрата с цвят не е отворена +@msg the screen color sampler is already open инструментът за вземане на цвят от екрана вече е отворен +@msg this system has no screen color sampler тази система няма инструмент за вземане на цвят от екрана +@msg the screen color sampler did not answer инструментът за вземане на цвят от екрана не отговори +@msg the screen color sampler failed инструментът за вземане на цвят от екрана се провали @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` трябва да бъде команда, чийто елемент от менюто отваря диалогов прозорец (вижте ui.menuDialog) @msg `freeform.points` must be an array `freeform.points` трябва да бъде масив @msg `freeform.lines` must be an array `freeform.lines` трябва да бъде масив @@ -4818,6 +5012,19 @@ axis Both И двете @msg `{keep}` is not a side of this axis `{keep}` не е страна на тази ос @msg `{key}` must be `auto` or a language code such as `en` or `zh-hant` `{key}` трябва да бъде `auto` или езиков код като `en` или `zh-hant` @msg `{key}` must be a #rrggbb color `{key}` трябва да бъде цвят във формат #rrggbb +@msg `{key}` must be a #rrggbb color or a layer color name `{key}` трябва да бъде цвят във формат #rrggbb или име на цвят на слой +@msg unknown Live Paint option `{key}` неизвестна опция за динамично оцветяване `{key}` +@msg unknown Shape Builder option `{key}` неизвестна опция за инструмента за създаване на форми `{key}` +@msg `{key}` must be a profile name or null `{key}` трябва да е име на профил или null +@msg `top` and `below` can't both be true `top` и `below` не могат да са true едновременно +@msg `select` must be true or false `select` трябва да е true или false +@msg `minAnchors` and `maxAnchors` must be whole numbers `minAnchors` и `maxAnchors` трябва да са цели числа +@msg `{key}` must be a number not below 0 `{key}` трябва да е число не по-малко от 0 +@msg `{key}` must be four numbers not below 0: [tl, tr, br, bl] `{key}` трябва да е четири числа не по-малки от 0: [tl, tr, br, bl] +@msg `{key}` must be [x, y, width, height]: four finite numbers, width and height not negative `{key}` трябва да е [x, y, width, height]: четири крайни числа, като width и height не са отрицателни +@msg `{min_key}` is greater than `{max_key}` `{min_key}` е по-голямо от `{max_key}` +@msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` задайте поне едно от `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` +@msg a process color can't colorize a grayscale image with transparency: use a spot color, black or white триадичен цвят не може да оцвети изображение в нива на сивото с прозрачност: използвайте спот цвят, черно или бяло @msg `{key}` must be a #rrggbb colour `{key}` трябва да бъде цвят във формат #rrggbb @msg `{key}` must be a number `{key}` трябва да бъде число @msg `{key}` must be a number, not {v} `{key}` трябва да бъде число, а не {v} @@ -4874,6 +5081,10 @@ axis Both И двете @msg a gradient needs at least two stops градиентът се нуждае от поне две опорни точки @msg a graphic style named `{to}` already exists графичен стил с име `{to}` вече съществува @msg a key object sits on that point в тази точка има основен обект +@msg `name` is empty `name` е празно +@msg `newName` is empty `newName` е празно +@msg `{name}` is a built-in preset and can't change: save it under another name `{name}` е вградена предварителна настройка и не може да се променя: запазете я под друго име +@msg `{name}` is a built-in preset and stays `{name}` е вградена предварителна настройка и остава @msg a page is missing липсва страница @msg a page out of range страница извън диапазона @msg a page tree kid isn't a reference дете в дървото на страниците не е препратка @@ -4883,6 +5094,9 @@ axis Both И двете @msg a swatch or color group named `{n}` exists образец или цветова група с име `{n}` вече съществува @msg a slice size must be a positive number of points размерът на парчето трябва да бъде положително число в точки @msg a spine keeps at least two points оста запазва поне две точки +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` е null, име на цвят на слой или #rrggbb +@msg the Simplify slider is not open плъзгачът за опростяване не е отворен +@msg the Smooth slider is not open плъзгачът за изглаждане не е отворен @msg a stream runs past the end потокът преминава отвъд края @msg a stream's length is wrong дължината на потока е грешна @msg a stream's length isn't a number дължината на потока не е число @@ -4953,6 +5167,15 @@ axis Both И двете @msg index must be a number or first, previous, next or last index трябва да е число или first, previous, next или last @msg index must be a number or first, previous, next or last, not `{other}` index трябва да е число или first, previous, next или last, а не `{other}` @msg index must be ≥ 0 index трябва да е ≥ 0 +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller страницата на работна област {n} е {size}, по-дълга от ограничението на PDF за страница от 14,400 pt (200 in): записва се с UserUnit {unit}, затова приложенията, които пренебрегват UserUnit, я показват толкова пъти по-малка +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller: turn on Write pages longer than 200 in at full size in points страницата на работна област {n} е {size}, по-дълга от ограничението на PDF за страница от 14,400 pt (200 in): записва се с UserUnit {unit}, затова приложенията, които пренебрегват UserUnit, я показват толкова пъти по-малка: включете Записване на страници, по-дълги от 200 in, в пълен размер в точки +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in страницата на работна област {n} е {size}, по-дълга от ограничението на PDF за страница от 14,400 pt (200 in): страниците {label} се записват без UserUnit, в пунктове, и приложенията, които спазват ограничението, отрязват страницата до 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 няма UserUnit, който е нужен на страница, по-дълга от 14,400 pt (200 in), за да запази размера си: файлът се записва като PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 няма UserUnit, който е нужен на страница, по-дълга от 14,400 pt (200 in), за да остане в ограничението на PDF/A-2 за страница от 14,400 единици: файлът се записва като PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units страницата на работна област {n} е {size}, твърде дълга и тясна за страните на страница в PDF от 3 до 14,400 единици: записва се с UserUnit {unit}, което запазва късата страна на 3 или повече единици, а приложенията, които спазват ограничението, отрязват дългата страна до 14,400 единици +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard файловете {label} съдържат реални числа до {max}, а страницата на работна област {n}, дълга {side} pt, изисква по-големи: изберете PDF 1.6 или по-нов без стандарт PDF/X или по-малка работна област +@msg line {line}: value for `{var}` must be true or false ред {line}: стойността за `{var}` трябва да е true или false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes ред {line}: стойността за `{var}` е по-дълга от {MAX_GRAPH_CSV} байта @msg installing from a path is not available on the web; pass the module as `dataBase64` инсталирането от път не е налично в уеб; предайте модула като `dataBase64` @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) вътрешна грешка в `{cmd}`: {msg} (документът беше оставен в състоянието си отпреди; моля, докладвайте тази грешка) @msg internal error: {msg} (please report this bug) вътрешна грешка: {msg} (моля, докладвайте тази грешка) @@ -4994,6 +5217,10 @@ axis Both И двете @msg no bounds няма граници @msg no brush named `{name}` няма четка с име `{name}` @msg a bristle brush name can have at most {max} characters: `{name}` has {count} най-голяма дължина на името на четка с косъм (знаци): {max}; в `{name}` знаците са {count} +@msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}` не е документ на VectorCraft, PDF или PDF-съвместим файл .ai +@msg no saved preset named `{name}` няма запазена предварителна настройка с име `{name}` +@msg no saved preset named `{name}` to rename няма запазена предварителна настройка с име `{name}` за преименуване +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: препратката би била по-голяма от {MAX_BYTES} байта @msg no brush selected няма избрана четка @msg brushes move only within their type четките се преместват само в рамките на своя тип @msg no catalog няма каталог @@ -5078,6 +5305,7 @@ axis Both И двете @msg `link` and `independent` cannot both be true `link` и `independent` не могат и двата да са true @msg `link` places a handle: give `handle` `link` поставя дръжка: задайте `handle` @msg no such spine segment няма такъв сегмент от оста +@msg node {_1} is on a locked artboard възелът {_1} е върху заключена работна област @msg no such subpath няма такъв подпът @msg no such user library няма такава потребителска библиотека @msg no such view няма такъв изглед @@ -5097,8 +5325,10 @@ axis Both И двете @msg not a VectorCraft file: {0} не е файл на VectorCraft: {0} @msg not a VectorCraft shortcut set (missing `overrides`) не е набор от клавишни комбинации на VectorCraft (липсват `overrides`) @msg not a blend не е преливане +@msg not a PICT file не е файл PICT +@msg thumbnail: no page {n} (the file has 1) миниатюра: няма страница {n} (файлът има 1) @msg not a graphic style library (format `{_1}`) не е библиотека със стилове на графики (формат `{_1}`) -@msg not a shortcut set: the text doesn't start with a slash name and an opening brace не е набор от преки пътища: текстът не започва с име със слъш и отваряща скоба +@msg not a shortcut set: the text doesn't start with a slash name and an opening brace не е набор от преки пътища: текстът не започва с име със слъш и отваряща скоба @msg not a stored central record не е съхранен централен запис @msg not a valid plug-in module: {0} не е валиден модул за плъгин: {0} @msg not an EMF or WMF file не е EMF или WMF файл @@ -5138,6 +5368,12 @@ axis Both И двете @msg percent must be above 0 and at most 6400, not {p} percent трябва да е над 0 и най-много 6400, а не {p} @msg pick a colour, gradient or pattern to save as a swatch изберете цвят, градиент или мостра за запазване като образец @msg plane must be left, right or ground plane трябва да е left, right или ground +@msg tolerance must be 0 or more tolerance трябва да е 0 или повече +@msg give `at` or `clear`, not both задайте `at` или `clear`, но не и двете +@msg anchorPoint must be true or false anchorPoint трябва да е true или false +@msg gridlineIntersection must be true or false gridlineIntersection трябва да е true или false +@msg the perspective grid is hidden перспективната мрежа е скрита +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Автоматичното позициониране на равнина е изключено: включете anchorPoint или gridlineIntersection (perspective.widget.options) @msg plug-in ABI: {0} ABI на плъгин: {0} @msg plug-in exceeded its {0} плъгинът надвиши своя {0} @msg plug-in failed: {0} плъгинът се провали: {0} @@ -5154,14 +5390,39 @@ axis Both И двете @msg recovery copy `{file}`: {e} възстановяване на копие `{file}`: {e} @msg resolutions must be between 1 and 2400 ppi резолюциите трябва да бъдат между 1 и 2400 ppi @msg result would exceed the canvas (coordinates out of range) резултатът ще надвиши платното (координатите са извън обхвата) -@msg objects can't be nested more than 32 deep обектите не могат да бъдат вложени на повече от 32 нива -@msg the SVG's elements are nested more than {0} deep елементите на SVG са вложени на повече от {0} нива +@msg objects can't be nested more than 32 deep обектите не могат да бъдат вложени на повече от 32 нива +@msg the SVG's elements are nested more than {0} deep елементите на SVG са вложени на повече от {0} нива @msg scale must be a number from {_1} to {_2}, not {_3} scale трябва да е число от {_1} до {_2}, а не {_3} @msg scale must be a number from {_1} to {_2}, not {s} scale трябва да е число от {_1} до {_2}, а не {s} @msg select (or target) objects whose appearance isn't basic изберете (или насочете към) обекти, чийто изглед не е основен @msg select a Live Paint group изберете група за интерактивно оцветяване (Live Paint) @msg select a blend изберете преход (blend) @msg select a blend or give `id` изберете преливане или задайте неговия `id` +@msg select an Objects on Path group изберете група „Обекти по пътя“ +@msg choose the object to detach with its Select/Move widget изберете обекта за откачане с неговия манипулатор за избиране и преместване +@msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects път в съставен път, преливане, плик, повторение или група за преплитане не може да приема обекти +@msg a clipping path can't take objects изрязващ път не може да приема обекти +@msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path обекти в преливане, плик, повторение или група за преплитане не могат да се прикачват към път +@msg a clipping path can't be attached to a path изрязващ път не може да се прикачи към път +@msg `background` must be edges, corners or colors `background` трябва да е edges, corners или colors +@msg `match` must be distance or channels `match` трябва да е distance или channels +@msg `{key}` must be from 0 to 100 `{key}` трябва да е от 0 до 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` трябва да изброява от 1 до 16 цвята, всеки шестнадесетичен (#rrggbb или #rgb) или black, white, red, green или blue +@msg the linked image shows its preview: embed or relink it first свързаното изображение показва визуализацията си: първо го вградете или свържете отново +@msg a CMYK image has no transparency to set изображение в CMYK няма прозрачност за задаване +@msg every pixel matches the background: no image would be left всеки пиксел съвпада с фона: няма да остане изображение +@msg an image of {w} × {h} pixels is too large to change изображение от {w} × {h} пиксела е твърде голямо за промяна +@msg select an image with a color mask изберете изображение с цветова маска +@msg the color mask's settings are out of range настройките на цветовата маска са извън допустимия диапазон +@msg a CMYK image can't take a color mask изображение в CMYK не може да приеме цветова маска +@msg the mask would hide every pixel маската би скрила всеки пиксел +@msg Recolor completed; {locked} and {hidden} were left unchanged Преоцветяването завърши; {locked} и {hidden} останаха непроменени +@msg Recolor completed; {objects} were left unchanged Преоцветяването завърши; {objects} останаха непроменени +@msg Recolor completed; {objects} was left unchanged Преоцветяването завърши; {objects} остана непроменен +@msg 1 locked object 1 заключен обект +@msg {n} locked objects {n} заключени обекта +@msg 1 hidden object 1 скрит обект +@msg {n} hidden objects {n} скрити обекта @msg select a clip group изберете група за изрязване @msg select a flare изберете взрив @msg select a gradient mesh изберете мрежа на градиент (gradient mesh) @@ -5259,6 +5520,8 @@ axis Both И двете @msg the selection has no URL (or they differ) селекцията няма URL адрес (или те се различават) @msg the selection isn't in perspective селекцията не е в перспектива @msg the spine has no segments оста няма сегменти +@msg panels can't be shown in Presentation Mode панелите не могат да се показват в режим на презентация +@msg unknown preset `{name}`: not a built-in or saved preset (see imageTrace.presets) неизвестна предварителна настройка `{name}`: не е вградена или запазена предварителна настройка (вижте imageTrace.presets) @msg the stroke has no weight щрихът няма дебелина @msg the thumbnail image is malformed миниатюрното изображение е дефектно @msg the top object must be a path, compound path or text object to use as a clipping mask горният обект трябва да бъде път, съставен път или текстов обект, за да се използва като маска за изрязване @@ -5269,6 +5532,7 @@ axis Both И двете @msg this file's PostScript couldn't be read ({why}): {what} PostScript файлът не можа да бъде прочетен ({why}): {what} @msg this format holds one artboard: export several as PDF or with document.exportForScreens този формат съдържа една работна област: експортирайте няколко като PDF или с document.exportForScreens @msg this is a DWG drawing, which can't be read: save it from the CAD app as an ASCII DXF and open that това е DWG чертеж, който не може да бъде прочетен: запазете го от CAD приложението като ASCII DXF и го отворете +@msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), which can't be opened yet: save it as PDF, PDF-compatible .ai or SVG това е файл PostScript (.ai, запазен в по-стар формат или без съвместимост с PDF, или файл EPS), който все още не може да се отвори: запазете го като PDF, PDF-съвместим .ai или SVG @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS това е PostScript файл (.ai, запазен в по-стар формат или без съвместимост с PDF, или EPS файл), а не PDF: Файл › Отваряне и Файл › Вмъкване го четат като EPS @msg this is not a PostScript file това не е PostScript файл @msg tool shortcuts must be a single key (optionally with Shift) клавишните комбинации за инструменти трябва да са един клавиш (по избор със Shift) @@ -5310,6 +5574,9 @@ axis Both И двете @msg unknown workspace (one of {_1}) непознато работно пространство (едно от {_1}) @msg unsupported: {0} не се поддържа: {0} @msg variables are locked променливите са заключени +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} повече от {MAX_CSV_ROWS} набора от данни: Импортиране на набори от данни чете най-много {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} повече от {MAX_CSV_COLS} променливи: Импортиране на набори от данни чете най-много {MAX_CSV_COLS} +@msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` и `options.{key}: {inner}` си противоречат: задайте опцията веднъж @msg variables that aren't text were left out: {kinds} променливите, които не са текстови, бяха пропуснати: {kinds} @msg a new document won't read these variables back with their kind: {names} нов документ няма да прочете тези променливи обратно с техния вид: {names} @msg a new document refuses this file because of these variables: {names} нов документ отказва този файл заради тези променливи: {names} @@ -5318,6 +5585,121 @@ axis Both И двете @msg width and height are at least 1 pixel ширината и височината са най-малко 1 пиксел @msg workspace name can't be empty името на работното пространство не може да бъде празно @msg x and y must be finite x и y трябва да са крайни числа +@msg {_1} is an exporter (File › Export › Export As…) {_1} е формат за експортиране (Файл › Експортиране › Експортиране като…) +@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` е {size} байта (ограничение {MAX_DOCUMENT_DATA}) +@msg a mask that covers several layers comes in as a clipping group in each layer it covers маска, която покрива няколко слоя, се импортира като група за изрязване във всеки покрит слой +@msg a graph's records don't end where they should: its art was read as it is записите на диаграма не завършват където трябва: графиката ѝ беше прочетена такава, каквато е +@msg `{w}` takes no operands `{w}` не приема операнди +@msg a wraparound group is inside a compound path обгръщаща група е в съставен път +@msg it ends inside a multi-layer mask завършва вътре в многослойна маска +@msg a multi-layer mask's operators are out of order операторите на многослойна маска не са в правилния ред +@msg a multi-layer mask needs one clipping path многослойната маска изисква един изрязващ път +@msg a group crosses a multi-layer mask група пресича многослойна маска +@msg graphs come in as plain art, without their data or settings диаграмите се импортират като обикновена графика, без данните и настройките си +@msg the active document changed while the question was open; nothing was deleted активният документ се промени, докато въпросът беше отворен; нищо не беше изтрито +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Връзката е в символ, дизайн на диаграма, мостра или маска за непрозрачност и няма място върху платното +@msg source must be the id of a Shaper Group's original shape source трябва да е идентификаторът на оригинална форма от група от форми +@msg group must be the id of a Shaper Group group трябва да е идентификаторът на група от форми +@msg the shape is not an editable original shape of that Shaper Group формата не е редактируема оригинална форма от тази група от форми +@msg id {value} is a layer, not an object id {value} е слой, а не обект +@msg id {value} is a layer, not an object; move layers with layer.move id {value} е слой, а не обект; премествайте слоевете с layer.move +@msg the PCX file is cut short файлът PCX е прекъснат +@msg the PCX file's header is damaged заглавката на файла PCX е повредена +@msg PCX files with {bits}-bit pixels in {planes} planes can't be read файлове PCX с {bits}-битови пиксели в {planes} равнини не могат да се четат +@msg the Pixar file is cut short файлът Pixar е прекъснат +@msg the Pixar file's header is damaged заглавката на файла Pixar е повредена +@msg the Pixar file's image data is damaged данните за изображението във файла Pixar са повредени +@msg the JPEG 2000 file can't be read файлът JPEG 2000 не може да се прочете +@msg the JPEG 2000 file has an unsupported color space or JPX content файлът JPEG 2000 има неподдържано цветово пространство или съдържание JPX +@msg the HEIC or HEIF file can't be read файлът HEIC или HEIF не може да се прочете +@msg the HEIC or HEIF file holds a kind of image that can't be read файлът HEIC или HEIF съдържа вид изображение, което не може да се прочете +@msg HEIC and HEIF images can't be opened in this build изображенията HEIC и HEIF не могат да се отварят в тази компилация +@msg the JPEG XL file is cut short файлът JPEG XL е прекъснат +@msg the JPEG XL container is too large to read контейнерът JPEG XL е твърде голям за четене +@msg CMYK JPEG XL images can't be read изображенията JPEG XL в CMYK не могат да се четат +@msg the JPEG XL file can't be read: {e} файлът JPEG XL не може да се прочете: {e} +@msg Extrude & Bevel Избутване и фасетка +@msg Revolve Завъртане около ос +@msg Inflate Издуване +@msg Rotate Завъртане +@msg Extrude & Bevel (Classic) Избутване и фасетка (класически) +@msg Revolve (Classic) Завъртане около ос (класическо) +@msg Rotate (Classic) Ротация (класическа) +@msg This effect Този ефект +@msg clipping paths изрязващи пътища +@msg other objects други обекти +@msg {label} requires a group holding a shape with at least two anchors {label} изисква група, съдържаща форма с поне две опорни точки +@msg Revolve requires a group holding a shape with at least two anchors Завъртането около ос изисква група, съдържаща форма с поне две опорни точки +@msg Revolve requires a shape with at least two anchors Завъртането около ос изисква форма с поне две опорни точки +@msg {label} on a group needs paths, compound paths, type, groups, clipping groups, blends and symbol instances: release or expand its {what} first. {label} върху група изисква пътища, съставни пътища, текст, групи, групи за изрязване, преливания и инстанции на символи: първо освободете или разширете {what}. +@msg {label} on a group takes at most {MAX_MEMBERS} objects {label} върху група приема най-много {MAX_MEMBERS} обекта +@msg A 3D effect on a group or layer goes on the group itself, not on its fill or stroke 3D ефект върху група или слой се прилага към самата група, а не към нейното запълване или щрих +@msg a 3D effect on a group's fill or stroke draws nothing 3D ефект върху запълването или щриха на група не рисува нищо +@msg a 3D effect on a group's fill or stroke draws nothing to export 3D ефект върху запълването или щриха на група не рисува нищо за експортиране +@msg The 3D object is too complex to export 3D обектът е твърде сложен за експортиране +@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) обектът няма 3D ефект (Избутване и фасетка, Завъртане около ос, Издуване или Завъртане) +@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` трябва да е обект, съдържащ само `mode`, със стойност shaded или wireframe +@msg its 3D effect builds no solid неговият 3D ефект не изгражда тяло +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel трябва да е none или едно от {_1}, или custom с {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom изисква {BEVEL_PROFILE}, точките на фасетката +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} трябва да е низ +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} трябва да е от 2 до {most} точки [x, y], всяка стойност между 0 и 1, от [0, 0] (ръбът на капачката) до [1, 1] (страничната стена) +@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} не може да изгради тела от тази графика: нейните инстанции на символи, преливания и групи за изрязване съдържат твърде много обекти +@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} не може да изгради тяло от инстанцията на символа "{symbol}": графиката на символа не е налична +@msg {_1}: the clipping path is too complex to cut the art with {_1}: изрязващият път е твърде сложен, за да се изреже графиката с него +@msg {_1} takes at most {MAX_MEMBERS} objects {_1} приема най-много {MAX_MEMBERS} обекта +@msg {_1} can't build solids from art nested more than {MAX_DEPTH} levels deep {_1} не може да изгради тела от графика, вложена на повече от {MAX_DEPTH} нива +@msg Revolve paint is too complex for this surface; reduce Segments or simplify the gradient Боята на завъртането около ос е твърде сложна за тази повърхност; намалете Сегменти или опростете градиента +@msg Revolve edge must be left or right Завъртане около ос: edge трябва да е left или right +@msg Revolve cap must be a boolean Завъртане около ос: cap трябва да е булева стойност +@msg the revolved object has no fill or stroke завъртяният около ос обект няма запълване или щрих +@msg lightColor must be an opaque RGB color in #rrggbb form lightColor трябва да е непрозрачен цвят RGB във формат #rrggbb +@msg lights must contain one to ten lights lights трябва да съдържа от един до десет източника на светлина +@msg each light must be an object всеки източник на светлина трябва да е обект +@msg unknown light setting: use color, intensity, rotation, height, softness or behind неизвестна настройка на светлината: използвайте color, intensity, rotation, height, softness или behind +@msg light {key} must be a number from {min} to {max} {key} на светлината трябва да е число от {min} до {max} +@msg light color must use opaque #rrggbb светлина: color трябва да е непрозрачен #rrggbb +@msg light behind must be true or false behind на светлината трябва да е true или false +@msg shadow must be true or false shadow трябва да е true или false +@msg shadowPosition must be behind or below shadowPosition трябва да е behind или below +@msg {key} must be a number from {min} to {max} {key} трябва да е число от {min} до {max} +@msg each of `{GRAPHICS}` must be an object всеки елемент от `{GRAPHICS}` трябва да е обект +@msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` елементите на `{GRAPHICS}` приемат symbol, face, x, y, scale и rotation, а не `{k}` +@msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol всеки елемент от `{GRAPHICS}` изисква `symbol`, името на символ +@msg `{GRAPHICS}` face must be front or back face в `{GRAPHICS}` трябва да е front или back +@msg `{GRAPHICS}` face must be front, back or side face в `{GRAPHICS}` трябва да е front, back или side +@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} в `{GRAPHICS}` трябва да е число от {lo} до {hi} +@msg `{GRAPHICS}` must be an array `{GRAPHICS}` трябва да е масив +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Графиките се нанасят върху типовете обекти Равнина, Избутване, Завъртане около ос и Издуване +@msg Revolve maps graphics onto its side: map them onto the front Завъртането около ос нанася графиките върху страната си: нанесете ги върху предната страна +@msg Inflate maps graphics onto its front and back, not onto a side Издуването нанася графиките върху предната и задната си страна, а не върху странична +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on обект {_1}: задната страна на издуването приема графики, когато И двете страни и Капачка са включени +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Графиките са твърде сложни за тази повърхност: опростете графиката на символите или намалете Сегменти +@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` приема най-много {MAX_GRAPHICS} графики +@msg A plane has one face: map its graphics onto the front Равнината има една страна: нанесете графиките ѝ върху предната страна +@msg The graphics are too complex: simplify the symbols' art Графиките са твърде сложни: опростете графиката на символите +@msg A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art Графиката на нанесен елемент може да е вложена най-много на {MAX_LEVELS} нива: опростете графиката на символа +@msg A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art Графиката на нанесен елемент може да влага символи най-много на {MAX_NESTING} нива: опростете графиката на символа +@msg A graphic's art holds too many objects: simplify the symbol's art Графиката на нанесен елемент съдържа твърде много обекти: опростете графиката на символа +@msg A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art Нанесен елемент рисува най-много {MAX_PIECES} запълвания и щрихи: опростете графиката на символа +@msg `surface` must be one of {_1} `surface` трябва да е едно от {_1} +@msg {label} draws the source art for this object instead of its 3D surface {label} рисува изходната графика за този обект вместо 3D повърхността му +@msg {label} draws no faces for this object {label} не рисува страни за този обект +@msg the wireframe has more than {MAX_WIRE_EDGES} edges телената рамка има повече от {MAX_WIRE_EDGES} ръба +@msg the params must be an object, not {got} параметрите трябва да са обект, а не {got} +@msg unknown parameter `{path}`; the object takes no keys неизвестен параметър `{path}`; обектът не приема ключове +@msg unknown parameter `{path}`; it takes: {keys} неизвестен параметър `{path}`; приема: {keys} +@msg missing `{path}` липсва `{path}` +@msg `{path}` must be {expected}, not {got} `{path}` трябва да е {expected}, а не {got} +@msg `{path}` is nested too deeply `{path}` е вложен твърде дълбоко +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: не е изображение PNG, JPEG, WebP, TIFF или BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ изображението е {iw} × {ih} пиксела, а работната област при тази ширина е {rw} × {rh} пиксела: пропорциите им се различават +@msg `threshold` must be a number from 0 to 1 `threshold` трябва да е число от 0 до 1 +@msg background {v}: a color such as "#808080" background {v}: цвят, например "#808080" +@msg comparing with an image file isn't available in the browser сравняването с файл на изображение не е налично в браузъра +@msg columns {first} and {column} both name the variable `{name}` колоните {first} и {column} именуват една и съща променлива `{name}` +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for нищо от набора от данни {name} не беше приложено: нито един обект не е свързан с променлива, за която наборът има стойност +@msg no bound object reports a value (locked objects and embedded images report none) нито един свързан обект не връща стойност (заключените обекти и вградените изображения не връщат) @msg {C}: no effect at index {from} {C}: няма ефект на индекс {from} @msg {_1} failed: {e} {_1} неуспешно: {e} @msg {_1} files can be opened but not written (see document.formats) {_1} файловете могат да се отварят, но не и да се записват (вижте document.formats) @@ -6301,11 +6683,11 @@ theme Appearance Външен вид Drawer menu Меню на чекмеджето Toolbar: Show Controls Лента с инструменти: Показване на контроли @msg control must be fillStroke, coloring, drawMode or screenMode control трябва да бъде fillStroke, coloring, drawMode или screenMode -@msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode неизвестен контрол `{name}`: fillStroke, coloring, drawMode или screenMode -@msg give a fraction `t` from 0 to 1 въведете дробно число `t` от 0 до 1 -@msg give the path `id` въведете `id` на пътя -@msg invalid stroke widths невалидни ширини на щриха -@msg object has no weighted stroke обектът няма претеглен щрих +@msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode неизвестен контрол `{name}`: fillStroke, coloring, drawMode или screenMode +@msg give a fraction `t` from 0 to 1 въведете дробно число `t` от 0 до 1 +@msg give the path `id` въведете `id` на пътя +@msg invalid stroke widths невалидни ширини на щриха +@msg object has no weighted stroke обектът няма претеглен щрих Single Corner Radius Радиус на единичен ъгъл Top Left: Горно ляво: Top Right: Горно дясно: @@ -6461,6 +6843,8 @@ theme Appearance Външен вид Save Variable Library… Запазване на библиотека с променливи… @msg a variable library holds text variables, and the document has none библиотеката с променливи съдържа текстови променливи, а документът няма такива @msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` променливата `{name}` не може да бъде запазена в библиотека с променливи: преименувайте я така, че да започва с буква или `_`, без интервали и символи, различни от `-`, `_` и `.` +@msg {k} has control characters {k} съдържа управляващи знаци +@msg {k} has control characters or line breaks {k} съдържа управляващи знаци или нови редове @msg data set `{name}` holds a control character, which a variable library can't hold наборът от данни `{name}` съдържа управляващ знак, който библиотеката с променливи не може да съдържа @msg data set `{name}` starts or ends with white space, which a variable library can't hold наборът от данни `{name}` започва или завършва с интервал, който библиотеката с променливи не може да съдържа Make Graph Dynamic Динамична диаграма @@ -6515,6 +6899,7 @@ theme Appearance Външен вид # User Interface › Color Scheme Color Scheme Цветова схема Modern Модерна +@msg `{key}` must be an array of these names: {_1} `{key}` трябва да е масив от тези имена: {_1} # Symbol Options › Export Type Export Type: Тип на експортиране: @@ -6558,6 +6943,33 @@ theme Appearance Външен вид @msg only http, https and mailto URLs open in the browser, not “{url}” в браузъра се отварят само URL адреси с http, https и mailto, не „{url}“ @msg {id} opens another app: only the person at the keyboard can run it {id} отваря друга програма: само човекът пред клавиатурата може да изпълни командата @msg “{name}” is not a file „{name}“ не е файл +@msg a mask has more than one art block маската има повече от един блок графика +@msg mask art ends outside a mask dictionary графиката на маската завършва извън речник на маска +@msg cancelled; nothing was changed отменено; нищо не беше променено +@msg a linked image can't become a gradient mesh: embed it first свързано изображение не може да стане мрежа на градиент: първо го вградете +@msg the image has no usable size or position изображението няма използваем размер или позиция +@msg the image's pixels can't be read пикселите на изображението не могат да се прочетат +@msg Persistent libraries not found: {files} Не са намерени постоянни библиотеки: {files} +@msg `{given}` isn't a library panel (see window.swatchLibrary) `{given}` не е панел на библиотека (вижте window.swatchLibrary) +@msg library panel `{given}` isn't open панелът на библиотека `{given}` не е отворен +@msg too many changed shortcuts твърде много променени клавишни комбинации +@msg library panel `{given}` isn't missing its library на панела на библиотека `{given}` не липсва библиотеката му +@msg too many library panels were opened in this session в тази сесия бяха отворени твърде много панели на библиотеки +@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Изображението е {_1} × {_2} пиксела, повече от {LARGE_TRACE_SIDE} по една страна: трасира се, но по-бавно. Предварителна настройка с по-ниска точност или по-малко копие на изображението се трасира по-бързо. +@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Изображението беше трасирано при {_1} × {_2} пиксела, намалено от {_3} × {_4} (най-много {_5} мегапиксела). +@msg byColor must be true or false byColor трябва да е true или false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor не може да разделя групи от Автоматично групиране: трасирайте без Автоматично групиране +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor не може да прегрупира трасиране с динамичен ефект Търсач на пътища: разширете без byColor +@msg Flat Logo mode does not use keepColors: it traces the colors named in logoColors, or the colors it finds. Режимът „Плоско лого“ не използва keepColors: той трасира цветовете, посочени в logoColors, или цветовете, които намери. +@msg Nothing was traced: none of the colors the trace found matches keepColors ({_1}). Нищо не беше трасирано: нито един от цветовете, намерени при трасирането, не съвпада с keepColors ({_1}). +@msg Nothing was traced: Ignore Color leaves out every area of the colors keepColors lists. Нищо не беше трасирано: Игнориране на цвета изключва всяка област от цветовете, изброени в keepColors. +@msg Nothing was traced: the colors that match keepColors produce no paths. Нищо не беше трасирано: цветовете, които съвпадат с keepColors, не създават пътища. +@msg keepColors: none of the colors the trace found matches {c}, so nothing of it is traced. keepColors: нито един от цветовете, намерени при трасирането, не съвпада с {c}, затова нищо от него не се трасира. +@msg `colorGroup` needs `library: "document"` `colorGroup` изисква `library: "document"` +@msg `colorGroup` needs `palette: "documentLibrary"` `colorGroup` изисква `palette: "documentLibrary"` +@msg `colorGroup` needs `mode: "color"` `colorGroup` изисква `mode: "color"` +@msg no color group `{name}` in the document (see swatch.list) в документа няма цветова група `{name}` (вижте swatch.list) +@msg Flat Logo traced the image at {_1} × {_2} pixels, averaged down from {_3} × {_4}. Режимът „Плоско лого“ трасира изображението при {_1} × {_2} пиксела, осреднено от {_3} × {_4}. Enable Guides for 9-Slice Scaling Включване на водачи за 9-slice мащабиране Persistent Постоянна Locate Library… Намиране на библиотека… @@ -6599,10 +7011,269 @@ theme Appearance Външен вид @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest библиотеката с променливи на файла беше прочетена частично (пропуснати записи: {_1}): панелът „Променливи“ показва останалите @msg the file's variable library couldn't be read: the Variables panel doesn't list it библиотеката с променливи на файла не можа да бъде прочетена: панелът „Променливи“ не я показва @msg a variable of unknown kind can't be bound to objects променлива от неизвестен вид не може да бъде свързана с обекти +@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` трябва да е grayscale, rgb, hsb, cmyk или websafe +@msg `view` must be wheel or box `view` трябва да е wheel или box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` трябва да е hue, saturation, brightness, red, green или blue # Select by Color (select.color) Select by Color Избиране по цвят Move Anchor Point Преместване на опорна точка @msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} запазва 1 от {n} работни области на документа: файлът се отваря отново с един. Включете „Запазване на възможностите за редактиране“, за да запазите всички. +@msg `spread` must be pad, repeat or reflect `spread` трябва да е pad, repeat или reflect +@msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` трябва да е цяло число от 1 до {MAX_REPEATS} +@msg `spread` applies to linear, radial, conic and diamond gradients `spread` се прилага към линейни, радиални, конични и ромбовидни градиенти +@msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} завърши, но междувременно документът или приставката се промени: изпълнете отново +@msg Running “{name}”… Изпълнява се „{name}“… +@msg a live effect runs while the document is drawn, so it can't be `heavy` динамичният ефект се изпълнява, докато документът се рисува, затова не може да е `heavy` +@msg an exporter always gets an export's budget: leave `budget` out форматът за експортиране винаги получава бюджета на експортиране: пропуснете `budget` +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ иска голям бюджет (всяко изпълнение до {minutes} минути и {times} пъти обичайния брой инструкции): човек трябва да го одобри в настолното приложение или подайте `allowHeavy: true` в сесия, стартирана с --allow-plugin-grants +@msg `name` must be 1-64 printable characters `name` трябва да е от 1 до 64 видими знака +@msg `version`, `description` or `author` is too long `version`, `description` или `author` е твърде дълго +@msg `warnings` must be a list of strings `warnings` трябва да е списък от низове +@msg `{k}` must be one of {_1} `{k}` трябва да е едно от {_1} +@msg `{k}` must be {what} `{k}` трябва да е {what} +@msg an exporter declares 1 to {MAX_EXTENSIONS} `extensions` форматът за експортиране обявява от 1 до {MAX_EXTENSIONS} `extensions` +@msg at most {MAX_UNGROUPED} parameters outside groups: give the others a `group` най-много {MAX_UNGROUPED} параметъра извън групи: задайте `group` на останалите +@msg can't encode the input входните данни не могат да се кодират +@msg expected {{"dataBase64": "…"}} очаква се {{"dataBase64": "…"}} +@msg expected {{"objects": [...]}} очаква се {{"objects": [...]}} +@msg export `{name}`: {e} експортиране `{name}`: {e} +@msg extension {e} is listed twice разширението {e} е изброено два пъти +@msg extension {e}: use 1-16 lower-case letters and digits, without the dot разширение {e}: използвайте от 1 до 16 малки букви и цифри, без точката +@msg invalid id {_1}: use 1-64 characters from A-Z a-z 0-9 . _ - невалиден id {_1}: използвайте от 1 до 64 знака от A-Z a-z 0-9 . _ - +@msg invalid parameter name {k} невалидно име на параметър {k} +@msg manifest is not UTF-8 манифестът не е в UTF-8 +@msg manifest is too long (limit {MAX_MANIFEST_BYTES} bytes) манифестът е твърде дълъг (ограничение {MAX_MANIFEST_BYTES} байта) +@msg manifest is {_1} bytes (limit {MAX_MANIFEST_BYTES}) манифестът е {_1} байта (ограничение {MAX_MANIFEST_BYTES}) +@msg module is {_1} bytes (limit {_2}) модулът е {_1} байта (ограничение {_2}) +@msg needs approval: it asks for {0}, which the user grants when installing it on its own изисква одобрение: иска {0}, което потребителят разрешава, когато я инсталира самостоятелно +@msg not JSON: {e} не е JSON: {e} +@msg not a WebAssembly binary (missing \0asm header) не е двоичен файл WebAssembly (липсва заглавка \0asm) +@msg parameter `{k}`: {what} параметър `{k}`: {what} +@msg parameter `{name}`: {what} параметър `{name}`: {what} +@msg plug-in parameters must be a JSON object параметрите на приставката трябва да са обект JSON +@msg the module must export its linear memory as `memory` модулът трябва да експортира линейната си памет като `memory` +@msg the objects to change are no longer in the document обектите за промяна вече не са в документа +@msg the runtime panicked средата за изпълнение аварира +@msg unexpected host trap неочакван прихванат срив в приложението +@msg vc_abi_version returned {v}; this host implements version {ABI_VERSION} vc_abi_version върна {v}; това приложение реализира версия {ABI_VERSION} +@msg vc_alloc returned 0 (out of memory) vc_alloc върна 0 (няма достатъчно памет) +@msg vc_alloc returned a block outside memory vc_alloc върна блок извън паметта +@msg vc_run returned error code {packed} vc_run върна код на грешка {packed} +@msg {_1} is not a file {_1} не е файл +@msg {_1} is {_2} bytes (limit {_3}) {_1} е {_2} байта (ограничение {_3}) +@msg {_1} objects (limit {MAX_OBJECTS}) {_1} обекта (ограничение {MAX_OBJECTS}) +@msg {at}: {msg} {at}: {msg} +@msg {what} points outside memory {what} сочи извън паметта +@msg `angle` must be a number `angle` трябва да е число +@msg `aspect` must be from 0.01 to 100 `aspect` трябва да е от 0.01 до 100 +@msg `cap` must be "butt", "round" or "square" `cap` трябва да е "butt", "round" или "square" +@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` трябва да е "nonzero" или "evenodd" +@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` трябва да е адрес https:// с най-много {MAX_HELP_URL} байта +@msg `help` must be 1-{MAX_HELP} printable characters `help` трябва да е от 1 до {MAX_HELP} видими знака +@msg `id` must be an effect id of 1-{MAX_EFFECT_ID} bytes `id` трябва да е идентификатор на ефект от 1 до {MAX_EFFECT_ID} байта +@msg `id` must be the id of an input object `id` трябва да е идентификаторът на входен обект +@msg `join` must be "miter", "round" or "bevel" `join` трябва да е "miter", "round" или "bevel" +@msg `label` and `group` must be 1-{MAX_LABEL} printable characters `label` и `group` трябва да са от 1 до {MAX_LABEL} видими знака +@msg `maxLength` must be 1-{MAX_TEXT}, and the default no longer `maxLength` трябва да е от 1 до {MAX_TEXT}, а стойността по подразбиране да не е по-дълга +@msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` и `maxItems` трябва да са от 0 до {MAX_LIST}, `maxItems` поне 1, а стойността по подразбиране да има толкова елемента +@msg `name` must be a string `name` трябва да е низ +@msg `opacity` must be a number `opacity` трябва да е число +@msg `type` must be "path" or "compound" `type` трябва да е "path" или "compound" +@msg `unit` must be 1-{MAX_UNIT} printable characters `unit` трябва да е от 1 до {MAX_UNIT} видими знака +@msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` изброява от 1 до {MAX_CONDITION_VALUES} стойности за `{other}` +@msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` посочва `{other}`, който не е параметър, обявен преди този +@msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` посочва най-много {MAX_CONDITIONS} параметъра +@msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` приема стойностите на `{other}`, които са на отметка или на избор +@msg `visible` must be true or false `visible` трябва да е true или false +@msg `{key}` must be a number from {_1} to {_2} `{key}` трябва да е число от {_1} до {_2} +@msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` трябва да е масив с най-много {MAX_ITEMS} елемента +@msg a color default must be a color object or a hex string such as "#3a7bd5" цветовата стойност по подразбиране трябва да е обект на цвят или шестнадесетичен низ, например "#3a7bd5" +@msg a color object or a hex string such as "#3a7bd5" обект на цвят или шестнадесетичен низ, например "#3a7bd5" +@msg a freeform gradient holds at most {MAX_ITEMS} points and lines свободният градиент съдържа най-много {MAX_ITEMS} точки и линии +@msg a freeform gradient line names a point it doesn't have линия на свободен градиент посочва точка, която той няма +@msg a gradient needs 1-{MAX_ITEMS} stops градиентът изисква от 1 до {MAX_ITEMS} спирки +@msg a list of numbers списък от числа +@msg a list of {min_items} to {max_items} numbers списък от {min_items} до {max_items} числа +@msg a new object needs a `path` нов обект изисква `path` +@msg a number число +@msg a painted live effect returns only `objects` рисуващ динамичен ефект връща само `objects` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` частта на рисуващ динамичен ефект има само `path`, `fillRule`, `fills` и `strokes` +@msg a read-only object was left out обект само за четене беше пропуснат +@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given обект само за четене беше пропуснат: върнете го само като {{"id": …}} или такъв, какъвто е зададен +@msg a string низ +@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` щрихът има само `paint`, `width`, `join`, `cap` и `miterLimit` +@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} щрихът трябва да е {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} +@msg an effect must be {{"id", "params"?, "visible"?}} ефектът трябва да е {{"id", "params"?, "visible"?}} +@msg an effect on a fill returns only `fills` ефект върху запълване връща само `fills` +@msg an effect on a stroke returns only `strokes` ефект върху щрих връща само `strokes` +@msg an object must be a JSON object обектът трябва да е обект JSON +@msg bad range невалиден диапазон +@msg choices must be 1-64 non-empty, printable strings изборите трябва да са от 1 до 64 непразни низа от видими знаци +@msg coordinate out of range (limit ±{MAX_COORD} pt) координатата е извън диапазона (ограничение ±{MAX_COORD} pt) +@msg default is not one of the options стойността по подразбиране не е от опциите +@msg each piece needs a `path` всяка част изисква `path` +@msg is listed twice е изброено два пъти +@msg pattern transform out of range трансформацията на мострата е извън диапазона +@msg read-only field '{field}' changed полето само за четене '{field}' е променено +@msg stops must be in order of `offset` спирките трябва да са подредени по `offset` +@msg the document has no pattern {pattern} документът няма мостра {pattern} +@msg the document has no swatch {n} документът няма образец {n} +@msg `plates` requires a stop linked to a spot swatch `plates` изисква спирка, свързана със спот образец +@msg the output изходът +@msg the path has no anchor points пътят няма опорни точки +@msg too many anchor points (limit {MAX_ANCHORS}) твърде много опорни точки (ограничение {MAX_ANCHORS}) +@msg true or false true или false +@msg a number >= {_1} число >= {_1} +@msg a number > {_1} число > {_1} +@msg a number <= {_1} число <= {_1} +@msg a number < {_1} число < {_1} +@msg a number {_1} to {_2} число от {_1} до {_2} +@msg a number >= {_1} and < {_2} число >= {_1} и < {_2} +@msg a number > {_1} and <= {_2} число > {_1} и <= {_2} +@msg a number > {_1} and < {_2} число > {_1} и < {_2} +@msg a number ({_1}) число ({_1}) +@msg a number >= {_1} ({_2}) число >= {_1} ({_2}) +@msg a number > {_1} ({_2}) число > {_1} ({_2}) +@msg a number <= {_1} ({_2}) число <= {_1} ({_2}) +@msg a number < {_1} ({_2}) число < {_1} ({_2}) +@msg a number {_1} to {_2} ({_3}) число от {_1} до {_2} ({_3}) +@msg a number >= {_1} and < {_2} ({_3}) число >= {_1} и < {_2} ({_3}) +@msg a number > {_1} and <= {_2} ({_3}) число > {_1} и <= {_2} ({_3}) +@msg a number > {_1} and < {_2} ({_3}) число > {_1} и < {_2} ({_3}) +@msg an integer цяло число +@msg an integer >= {_1} цяло число >= {_1} +@msg an integer <= {_1} цяло число <= {_1} +@msg an integer {_1} to {_2} цяло число от {_1} до {_2} +@msg one of {_1} едно от {_1} +@msg an object id (a non-negative integer) идентификатор на обект (неотрицателно цяло число) +@msg a list of object ids списък от идентификатори на обекти +@msg a color (a string, [r, g, b] or an object) цвят (низ, [r, g, b] или обект) +@msg [x, y] (two numbers) [x, y] (две числа) +@msg an object обект +@msg a list списък +@msg unknown key `{k}`; the keys here are {_1} неизвестен ключ `{k}`; ключовете тук са {_1} +@msg {_1} is listed twice {_1} е изброен два пъти +@msg {_1} is not the id of an input object {_1} не е идентификаторът на входен обект +@msg {_1} is read-only {_1} е само за четене +@msg {what} must be from {lo} to {hi} {what} трябва да е от {lo} до {hi} +@msg a color component цветови компонент +@msg a plate печатна плака +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Автоматизацията поиска да инсталира тази приставка. За да я инсталирате, изберете сами Обект › Приставки › Инсталиране на приставка…. +@msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees „{name}“ е различен модул от приставката с id {_1} и би получил запазените за нея настройки и кеш: инсталирайте го с `replace: true`, след като потребителят се съгласи +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ изброява `{id}` в `commandAllowlist`, а приставка не може да я извиква +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: не е изброена в `commandAllowlist` на манифеста +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: идентификаторът или аргументите са извън паметта на модула +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: идентификаторът или аргументите не са в UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: аргументите не са обект JSON +@msg only a filter with the usual budget declares `commandAllowlist` само филтър с обичайния бюджет обявява `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) извиквания на команди ({MAX_CALLS} извиквания и {MAX_CALL_BYTES} байта на изпълнение) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) размер на извикване на команда (vc_call `{shown}`: {len} байта, ограничение {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` най-много {MAX_ALLOWED_COMMANDS} команди в `commandAllowlist` +@msg a plug-in may not call this command приставка не може да извиква тази команда +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` изисква разрешението `commands`, а `commands` изисква `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` посочва `{shown}`, който не е идентификатор на команда или е изброен два пъти +@msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} разрешението `{permission}` изисква ниво {PROGRESS_API} на API за приставки: задайте `api` {PROGRESS_API} +@msg the module imports `env.{name}` with another type than the host's: it is {signature} модулът импортира `env.{name}` с тип, различен от този на приложението: той е {signature} +@msg the module imports `env.{name}`, which a plug-in may use only at plug-in API level {PROGRESS_API} (`api` {PROGRESS_API}) and with the permission `{permission}` модулът импортира `env.{name}`, която приставка може да използва само при ниво {PROGRESS_API} на API за приставки (`api` {PROGRESS_API}) и с разрешението `{permission}` +@msg the module imports `{from}.{name}`, which the host doesn't offer: a plug-in may import only the `env.vc_*` functions that docs/plugins.md lists (plug-in API level 2), and no WASI, files or network модулът импортира `{from}.{name}`, която приложението не предлага: приставка може да импортира само функциите `env.vc_*`, изброени в docs/plugins.md (ниво 2 на API за приставки), и никакви WASI, файлове или мрежа +@msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` е {_1}; това приложение реализира нива от 1 до {API_LEVEL} на API за приставки +@msg `paintOutput` may only be true `paintOutput` може да е само true +@msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` е само за динамичен ефект (`kind` "effect") при `api` 2 +@msg `grant` must be a list of permission names `grant` трябва да е списък от имена на разрешения +@msg `grant` names an unknown permission `{shown}` `grant` посочва неизвестно разрешение `{shown}` +@msg a plug-in of kind `{_1}` needs the permission `{_2}` приставка от вид `{_1}` изисква разрешението `{_2}` +@msg at most {MAX_PERMISSIONS} `permissions` най-много {MAX_PERMISSIONS} `permissions` +@msg permission `{shown}` doesn't apply to a plug-in of kind `{_1}` разрешението `{shown}` не се отнася за приставка от вид `{_1}` +@msg permission `{shown}` is listed twice разрешението `{shown}` е изброено два пъти +@msg only a filter declares `inputs` само филтър обявява `inputs` +@msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` посочва неизвестен вид обект `{shown}`: използвайте type, image или symbolInstance +@msg `inputs` lists `{shown}` twice `inputs` изброява `{shown}` два пъти +@msg `inputs` needs `api` 2 or later `inputs` изисква `api` 2 или по-ново +@msg `inputs` needs the permission `doc.read` `inputs` изисква разрешението `doc.read` +@msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет на паметта (обект {_1} изисква {size} байта входни данни, остават {left}) +@msg object budget (more than {MAX_OBJECTS} read-only objects) бюджет на обектите (повече от {MAX_OBJECTS} обекта само за четене) +@msg instruction budget бюджет на инструкциите +@msg time budget бюджет на времето +@msg memory budget (the selection is too large to hand over) бюджет на паметта (селекцията е твърде голяма за предаване) +@msg output size ({what} is {len} bytes, limit {max}) размер на изхода ({what} е {len} байта, ограничение {max}) +@msg the plug-in's grant can't be removed from the plug-in store разрешението на приставката не може да се премахне от хранилището на приставки +@msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it разрешението `{shown}` е запазено за по-късен API за приставки; това приложение не го дава +@msg unknown permission `{shown}` неизвестно разрешение `{shown}` +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants „{name}“ иска разрешенията {asked}: човек трябва да ги одобри в настолното приложение или подайте `grant` в сесия, стартирана с --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` и `allowHeavy` действат само в сесия, стартирана с --allow-plugin-grants: одобрете приставката в настолното приложение +@msg Only the person at the keyboard can approve installing a plug-in Само човекът на клавиатурата може да одобри инсталирането на приставка +@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed на „{name}“ не е дадено `{p}`, което е нужно за изхода ѝ: нищо не беше променено +@msg a heavy filter runs in the background, so it can't declare `commands` тежък филтър се изпълнява във фонов режим, затова не може да обявява `commands` +@msg at most {MAX_COMMANDS} `commands` най-много {MAX_COMMANDS} `commands` +@msg command {name} is declared twice командата {name} е обявена два пъти +@msg command {name}: `label` must be 1-64 printable characters команда {name}: `label` трябва да е от 1 до 64 видими знака +@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter команда {name}: използвайте id от 1 до {MAX_COMMAND_ID} знака от a-z 0-9 _, който започва с буква +@msg command {name}: {e} команда {name}: {e} +@msg manifest: {e} манифест: {e} +@msg manifest: {e} at line {line} column {column} манифест: {e} на ред {line}, колона {column} +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` трябва да е списък от команди, всяка с `id` и `label` +@msg command {name} must be an object with an `id` and a `label` командата {name} трябва да е обект с `id` и `label` +@msg missing field `{key}` липсва поле `{key}` +@msg duplicate field `{key}` повтарящо се поле `{key}` +@msg only a filter or a live effect declares `commands` само филтър или динамичен ефект обявява `commands` +@msg “{name}” › {label}: {e} „{name}“ › {label}: {e} +@msg the module doesn't have the SHA-256 `hash` gives: nothing was installed модулът няма SHA-256, зададен в `hash`: нищо не беше инсталирано +@msg select one object изберете един обект +@msg Global Edit is off Глобалното редактиране е изключено +@msg only an object of the Global Edit other than the one it started from can be left out може да се пропусне само обект от глобалното редактиране, различен от този, от който то е започнало +@msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all или диапазон, например 1, 3-5, а не {v} +@msg `{_1}` has no symbols to place `{_1}` няма символи за поставяне +@msg missing `library` (see symbol.libraries) липсва `library` (вижте symbol.libraries) +@msg no symbol `{n}` няма символ `{n}` +@msg no symbol `{n}` in `{_1}` няма символ `{n}` в `{_1}` +@msg no symbol library `{key}` (see symbol.libraries) няма библиотека със символи `{key}` (вижте symbol.libraries) +@msg the document has no symbols to save документът няма символи за запазване +@msg `{_1}` has no brushes to apply `{_1}` няма четки за прилагане +@msg missing `library` (see brush.libraries) липсва `library` (вижте brush.libraries) +@msg no brush `{n}` няма четка `{n}` +@msg no brush `{n}` in `{_1}` няма четка `{n}` в `{_1}` +@msg no brush library `{key}` (see brush.libraries) няма библиотека с четки `{key}` (вижте brush.libraries) +@msg the document has no brushes to save документът няма четки за запазване +@msg a {width}×{height} screenshot's byte count overflows броят байтове на екранна снимка {width}×{height} препълва +@msg the window's {what} ({points} points × {scale} DPI) cannot size a screenshot {what} на прозореца ({points} точки × {scale} DPI) не може да определи размера на екранна снимка +@msg {label} must be a number {label} трябва да е число +@msg {label} must be a number of at least 0.1 {label} трябва да е число не по-малко от 0.1 +@msg {label} must be a number from {min} to {max} {label} трябва да е число от {min} до {max} +@msg {label} must be a whole number from {min} to {max} {label} трябва да е цяло число от {min} до {max} +@msg features lists at most {max} tags features изброява най-много {max} етикета +@msg unknown OpenType feature `{t}` неизвестна функция на OpenType `{t}` +@msg {label} must be a number above 0 and at most {max} {label} трябва да е число над 0 и най-много {max} +@msg {label} must be at most {max} characters {label} трябва да е най-много {max} знака +@msg {label} must be one character {label} трябва да е един знак +@msg at most {max} tab stops най-много {max} табулатора +@msg unknown align `{other}` неизвестно подравняване `{other}` +@msg no character style `{name}` няма стил на знаци `{name}` +@msg {_1} is an importer (File › Open With) {_1} е формат за импортиране (Файл › Отваряне с) +@msg missing `importer` (see document.formats) липсва `importer` (вижте document.formats) +@msg `importer` must be a plug-in format id (see document.formats) `importer` трябва да е идентификатор на формат на приставка (вижте document.formats) +@msg “{shown}” opens {_1} files, not `{_2}` „{shown}“ отваря файлове {_1}, а не `{_2}` +@msg `{_1}` is a plug-in of kind `{_2}`, not an importer `{_1}` е приставка от вид `{_2}`, а не формат за импортиране +@msg `{_1}` is a plug-in of kind `{_2}`, not an exporter `{_1}` е приставка от вид `{_2}`, а не формат за експортиране +@msg `{_1}` is an importer: open a file with document.open {{"importer": "{_2}"}} `{_1}` е формат за импортиране: отворете файл с document.open {{"importer": "{_2}"}} +@msg `{_1}` is an exporter: export with document.export {{"format": "{_2}"}} `{_1}` е формат за експортиране: експортирайте с document.export {{"format": "{_2}"}} +@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` е динамичен ефект: приложете го с effect.apply {{"effect": "{_2}"}} +@msg the importer returned no objects форматът за импортиране не върна обекти +@msg an importer returns `objects` and `warnings`, not `{key}` форматът за импортиране връща `objects` и `warnings`, а не `{key}` +@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads файлът е по-голям от {MAX_INPUT_BYTES} байта, които чете форматът за импортиране +@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` форматът за импортиране обявява от 1 до {MAX_EXTENSIONS} `extensions` +@msg only an exporter or an importer declares `extensions` само формат за експортиране или за импортиране обявява `extensions` +@msg an importer always gets an import's budget: leave `budget` out форматът за импортиране винаги получава бюджета на импортиране: пропуснете `budget` +@msg only paths and compound paths can be aligned to the pixel grid само пътища и съставни пътища могат да се подравняват към пикселната мрежа +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` и `last` трябва да са номера на редове в конзолата, като first е преди last +@msg no plug-in effect is deferred няма отложен ефект на приставка +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Отворено с {n} отложен ефект на приставка. Ефект › Обновяване на отложените ефекти го изпълнява.|Отворено с {n} отложени ефекта на приставки. Ефект › Обновяване на отложените ефекти ги изпълнява. +@msg The selected art has no islands to bridge Избраната графика няма острови за свързване с мостове +@msg No bridge of this width fits across the selected art Нито един мост с тази ширина не се побира през избраната графика +@msg Some islands could not be joined to the area around the art Някои острови не можаха да се свържат с областта около графиката +@msg `width` must be from {lo} to {hi} pt `width` трябва да е от {lo} до {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` трябва да е цяло число от 1 до {MAX_BRIDGES_PER_ISLAND} +@msgplural Loaded “{name}”: {n} step has an unknown command and was kept: “{action}”, step {step}, `{command}`|Loaded “{name}”: {n} steps have unknown commands and were kept; the first: “{action}”, step {step}, `{command}` Зареден е „{name}“: {n} стъпка има неизвестна команда и беше запазена: „{action}“, стъпка {step}, `{command}`|Зареден е „{name}“: {n} стъпки имат неизвестни команди и бяха запазени; първата: „{action}“, стъпка {step}, `{command}` Chalk & Charcoal… Креда и въглен… Chalk & Charcoal Креда и въглен Graphic Pen… Графична писалка… @@ -8035,7 +8706,349 @@ breakText Glyphs Глифи Pulse Stroke Пулсиращ щрих Round Flow Кръгъл поток Chisel Flow Скосен поток +@msg Script file access denied: {path} Достъпът до файла на скрипта е отказан: {path} +@msg Script file access to the app's own folders is not allowed Достъпът от скрипт до собствените папки на приложението не е разрешен +@msg Script file cannot encode the text Файлът на скрипта не може да кодира текста +@msg Script file could not be written Файлът на скрипта не можа да се запише +@msg Script file dialogs need a person to answer them Файловите диалогови прозорци за скриптове изискват човек, който да им отговори +@msg Script file is not open for writing Файлът на скрипта не е отворен за запис +@msg Script file name is already in use Името на файла на скрипта вече се използва +@msg Script file name must be a name without a folder Името на файла на скрипта трябва да е име без папка +@msg Script file permission can be kept only for a script run from a file Разрешението за файлове може да се запази само за скрипт, изпълнен от файл +@msg Script file permission could not be saved Разрешението за файлове на скрипта не можа да се запази +@msg Script folder is not empty Папката на скрипта не е празна +@msg Script files cannot make aliases Файловете на скриптове не могат да създават псевдоними +@msg Script file hidden setting cannot be changed Настройката за скриване на файла на скрипта не може да се променя +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: файлов диалогов прозорец не може да се отвори в обратно извикване на вградена функция, в getter, в преобразуване или във файл, изпълнен от $.evalFile; извикайте го от собствения код на скрипта +@msg the script wrote more file data than one run may write (32 MiB) скриптът записа повече файлови данни, отколкото е разрешено за едно изпълнение (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` за файлов диалогов прозорец на скрипт трябва да е едно от: once, always, deny, stop +@msg choose a file or folder first, or deny първо изберете файл или папка или откажете +@msg the script file permissions could not be saved: {e} разрешенията за файлове на скрипта не можаха да се запазят: {e} +@msg this script's file access can be allowed only once достъпът до файлове на този скрипт може да се разреши само веднъж +@msg Only the person at the keyboard can allow a script's file access Само човекът на клавиатурата може да разреши достъпа на скрипт до файлове +@msg A script is given at most 2,048 files: the files picked after them were left out На скрипт се дават най-много 2,048 файла: файловете, избрани след тях, бяха пропуснати +@msg assignment to a constant binding присвояване на константна връзка +@msg invalid array length невалидна дължина на масив +@msg array literal too long литералът на масив е твърде дълъг +@msg the value is not a function стойността не е функция +@msg apply was called on a value that is not a function apply беше извикан за стойност, която не е функция +@msg the argument list is not an object списъкът с аргументи не е обект +@msg too many arguments твърде много аргументи +@msg the value is not a constructor стойността не е конструктор +@msg cannot convert the object to a primitive value обектът не може да се преобразува в примитивна стойност +@msg cannot convert undefined or null to an object undefined или null не може да се преобразува в обект +@msg the right side of 'in' is not an object дясната страна на 'in' не е обект +@msg the right side of 'instanceof' is not a function дясната страна на 'instanceof' не е функция +@msg the function's prototype is not an object прототипът на функцията не е обект +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} не е дефиниран +@msg cannot read property '{key}' of {base} свойството '{key}' на {base} не може да се прочете +@msg cannot set property '{key}' of {base} свойството '{key}' на {base} не може да се зададе +@msg cannot read a property of {base} свойство на {base} не може да се прочете +@msg cannot set a property of {base} свойство на {base} не може да се зададе +@msg cannot define property '{key}': {why} свойството '{key}' не може да се дефинира: {why} +@msg cannot assign to property '{key}': {why} на свойството '{key}' не може да се присвои: {why} +@msg cannot delete property '{key}' свойството '{key}' не може да се изтрие +@msg cannot declare function {ident} функцията {ident} не може да се декларира +@msg invalid assignment target невалидна цел на присвояване +@msg the array's length is read-only дължината на масива е само за четене +@msg the property cannot be redefined свойството не може да се предефинира +@msg the object is not extensible обектът не е разширяем +@msg the length cannot be redefined дължината не може да се предефинира +@msg it is read-only то е само за четене +@msg an element cannot be deleted елемент не може да се изтрие +@msg it has only a getter то има само getter +@msg the value is a primitive стойността е примитивна +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` има {n} отговор, който скриптът не използва|`answers` има {n} отговора, които скриптът не използва +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} остави {n} обект под четката непроменен ({_2}): променя формата само на пътища|{_1} остави {n} обекта под четката непроменени ({_2}): променя формата само на пътища +liquify-tool Warp Изкривяване +liquify-tool Twirl Въртене +liquify-tool Pucker Свиване +liquify-tool Bloat Надуване +liquify-tool Scallop Назъбване +liquify-tool Crystallize Кристализация +liquify-tool Wrinkle Набръчкване +liquify-kind graphs диаграми +liquify-kind type текст +liquify-kind symbols символи +liquify-kind images изображения +liquify-kind meshes мрежи +liquify-kind envelopes пликове +liquify-kind repeats повторения +liquify-kind placed documents поставени документи +liquify-kind blends преливания +liquify-list-two {0}, {1} {0} и {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} и {1} +@msg give one element задайте един елемент +@msg the element needs an id, the filter's name елементът изисква id, името на филтъра +@msg an SVG filter's id is at most {MAX_NAME} characters id на SVG филтър е най-много {MAX_NAME} знака +@msg <{_1}> isn't an element of an SVG filter <{_1}> не е елемент на SVG филтър +@msg an SVG filter has no event attributes such as {_1} SVG филтърът няма атрибути за събития като {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs изображенията на SVG филтър са data: URL адреси на PNG, JPEG, GIF или WebP +@msg the SVG filter isn't valid XML: {e} SVG филтърът не е валиден XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves на feTurbulence е най-много {MAX_OCTAVES} +@msg {what} is at most {max} {what} е най-много {max} +@msg feConvolveMatrix's order order на feConvolveMatrix +@msg feMorphology's radius radius на feMorphology +@msg a blur's stdDeviation stdDeviation на размазване +@msg the SVG filter has no primitives SVG филтърът няма примитиви +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives SVG филтърът има най-много {MAX_PRIMITIVES} примитива +@msg the SVG filter is too large once its attributes are written out SVG филтърът е твърде голям, след като атрибутите му бъдат изписани +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all изображенията на SVG филтър имат общо най-много {MAX_IMAGE_PIXELS} пиксела +@msg the SVG filter can't be drawn: check its primitives and their inputs SVG филтърът не може да се нарисува: проверете примитивите му и техните входове +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep елементите на SVG филтър се влагат най-много на {MAX_DEPTH} нива +@msg an SVG filter is at most {_1} KB SVG филтърът е най-много {_1} KB +@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` трябва да е [a, b, c, d], всяко от -1000 до 1000, като a·d - b·c е на поне 0.001 от 0 +@msg `angle` must be from -180 to 180 degrees `angle` трябва да е от -180 до 180 градуса +@msg `roundness` must be from 0 to 100% `roundness` трябва да е от 0 до 100% +@msg `fidelity` must be from 0.01 to 100 pt `fidelity` трябва да е от 0.01 до 100 pt +@msg style must be "pencil" or "brush" style трябва да е "pencil" или "brush" +@msg extend end must be "start" or "end" end за удължаване трябва да е "start" или "end" +@msg connect end must be "start" or "end" end за свързване трябва да е "start" или "end" +@msg `roundness` must be from 1 to 100% `roundness` трябва да е от 1 до 100% +@msg 3D effects require finite coordinates within 100 million points 3D ефектите изискват крайни координати в рамките на 100 милиона точки +@msg 3D effects require one to ten lights 3D ефектите изискват от един до десет източника на светлина +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel дълбочина на BMP {_1}: 1, 4, 8, 16, 24 или 32 бита на пиксел +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer кодирането в BMP е неуспешно: {width} × {height} пиксела не се побират във формата или в буфера на пикселите +@msg GIF encoding failed: the palette image is malformed кодирането в GIF е неуспешно: изображението с палитра е неправилно оформено +@msg GIF encoding failed: {e} кодирането в GIF е неуспешно: {e} +@msg JPEG colour profile: {e} цветови профил на JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size кодирането в JPEG е неуспешно: буферът на пикселите не съответства на размера на изображението +@msg JPEG encoding failed: {e} кодирането в JPEG е неуспешно: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size кодирането в PNG е неуспешно: буферът на пикселите не съответства на размера на изображението +@msg PNG encoding failed: the palette image is malformed кодирането в PNG е неуспешно: изображението с палитра е неправилно оформено +@msg PNG encoding failed: {e} кодирането в PNG е неуспешно: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size кодирането в PNG е неуспешно: {width} × {height} пиксела не е валиден размер на изображение +@msg PSD colour profile: {e} цветови профил на PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size кодирането в PSD е неуспешно: буферът на пикселите не съответства на размера на изображението +@msg Revolve profile contains invalid coordinates профилът за завъртане около ос съдържа невалидни координати +@msg Revolve profile is too complex профилът за завъртане около ос е твърде сложен +@msg Revolve projection is not finite проекцията на завъртането около ос не е крайна +@msg Revolve requires finite profile coordinates within 100 million points завъртането около ос изисква крайни координати на профила в рамките на 100 милиона точки +@msg Revolve surface is too complex; reduce Segments or simplify the profile повърхността на завъртането около ос е твърде сложна; намалете Сегменти или опростете профила +@msg Revolve surface is too complex; simplify the profile повърхността на завъртането около ос е твърде сложна; опростете профила +@msg Revolve visibility cannot split the projected boundary изчисляването на видимостта при завъртане около ос не може да раздели проектираната граница +@msg Revolve visibility creates too many fragments изчисляването на видимостта при завъртане около ос създава твърде много фрагменти +@msg Revolve visibility creates too many vector anchors изчисляването на видимостта при завъртане около ос създава твърде много векторни опорни точки +@msg Revolve visibility exceeds its geometry work limit изчисляването на видимостта при завъртане около ос надхвърля ограничението си за геометрична работа +@msg Revolve visibility exceeds its spatial index limit изчисляването на видимостта при завъртане около ос надхвърля ограничението си за пространствен индекс +@msg Revolve visibility has too many boundary crossings изчисляването на видимостта при завъртане около ос има твърде много пресичания на граници +@msg Revolve visibility has too many input anchors изчисляването на видимостта при завъртане около ос има твърде много входни опорни точки +@msg Revolve visibility requires convex cap sectors изчисляването на видимостта при завъртане около ос изисква изпъкнали сектори на капачката +@msg Revolve visibility requires finite projected faces изчисляването на видимостта при завъртане около ос изисква крайни проектирани страни +@msg SVG options: {e} опции за SVG: {e} +@msg Save for Web settings: {e} настройки за запис за уеб: {e} +@msg TIFF colour profile: {e} цветови профил на TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size кодирането в TIFF е неуспешно: буферът на пикселите не съответства на размера на изображението +@msg TIFF encoding failed: {e} кодирането в TIFF е неуспешно: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel дълбочина на Targa {_1}: 16, 24 или 32 бита на пиксел +@msg Targa encoding failed: the pixel buffer doesn't match the image size кодирането в Targa е неуспешно: буферът на пикселите не съответства на размера на изображението +@msg The 3D projection is not finite 3D проекцията не е крайна +@msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D сянката е твърде сложна; изключете Сенки или опростете графиката +@msg The shape contains invalid coordinates Формата съдържа невалидни координати +@msg Too many Revolve faces for visibility evaluation Твърде много страни на завъртането около ос за изчисляване на видимостта +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft чете най-много {ASE_MAX_ENTRIES} цвята и групи от файл за обмен на образци, а тази библиотека има {entries} +@msg WebP encoding failed: {e} кодирането в WebP е неуспешно: {e} +@msg WebP encoding failed: the image is too large for lossy WebP: lower the resolution or choose Lossless кодирането в WebP е неуспешно: изображението е твърде голямо за WebP със загуба: намалете разделителната способност или изберете Без загуба +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` трябва да е "document", {{artboards: [index, …]}} или {{layers: [id, …]}} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` е smallThumb, mediumThumb, largeThumb, smallList или largeList +@msg `{file}` has no swatches of its own `{file}` няма собствени образци +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` има образци на мостри, които файл .vcswatches не може да съдържа +@msg a line can't run from a point to itself линия не може да минава от точка до самата нея +@msg a line needs at least two points линията изисква поне две точки +@msg a linked image file is outside the read roots свързан файл на изображение е извън корените за четене +@msg a linked file's export folder is outside the read roots папката за експортиране на свързан файл е извън корените за четене +@msg a number cannot be read число не може да се прочете +@msg a swatch exchange block is too long блок за обмен на образци е твърде дълъг +@msg a swatch exchange name is too long име за обмен на образци е твърде дълго +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels изображение {sw} × {sh} не може да се преоразмери до {width} × {height} пиксела +@msg a {width} × {height} image is too large изображение {width} × {height} е твърде голямо +@msg a {width} × {height} image: {e} изображение {width} × {height}: {e} +@msg an image could not be written: {e} изображение не можа да се запише: {e} +@msg an image that couldn't be read was left out изображение, което не можа да се прочете, беше пропуснато +@msg can't open “{name}”: {e} „{name}“ не може да се отвори: {e} +@msg cannot align zip entries to {align} bytes елементите на zip не могат да се подравнят на {align} байта +@msg cannot open the automation {kind} root `{_1}`: {e} коренът {kind} за автоматизация `{_1}` не може да се отвори: {e} +@msg cannot read profile: {0} профилът не може да се прочете: {0} +@msg color book version {version} isn't supported (only 1) версия {version} на цветова книга не се поддържа (само 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) цветови книги в цветово пространство {other} не се поддържат (само RGB, CMYK и Lab) +@msg file name too long to zip: {_1} името на файла е твърде дълго за zip: {_1} +@msg file name too long to zip: {name} името на файла е твърде дълго за zip: {name} +@msg freeform line {i}: {e} свободна линия {i}: {e} +@msg freeform point {i}: {e} свободна точка {i}: {e} +@msg give `{key}` or `{other}`, not both задайте `{key}` или `{other}`, но не и двете +@msg grayscale profiles can't be working spaces yet профилите в нива на сивото все още не могат да бъдат работни пространства +@msg input contains NaN or infinite coordinates входните данни съдържат NaN или безкрайни координати +@msg input path could not be closed входният път не можа да се затвори +@msg invalid ICC profile: {0} невалиден профил ICC: {0} +@msg invalid scale {scale} невалиден мащаб {scale} +@msg its localized names take more than {_1} KB локализираните му имена заемат повече от {_1} KB +@msg its objects are nested too deep ({e}) обектите му са вложени твърде дълбоко ({e}) +@msg its tag table lists the `{_1}` tag more than once таблицата му с тагове изброява тага `{_1}` повече от веднъж +@msg no similar objects found (reflected copies are not matched); change the Global Edit Options and try again не са намерени подобни обекти (отразените копия не се съпоставят); променете опциите за глобално редактиране и опитайте отново +@msg not a graphic style library: {e} не е библиотека с графични стилове: {e} +@msg not a swatch library (.vcswatches or .gpl) не е библиотека с образци (.vcswatches или .gpl) +@msg not a swatch library (format `{_1}`) не е библиотека с образци (формат `{_1}`) +@msg not a swatch library: {e} не е библиотека с образци: {e} +@msg not an action set file ({e}) не е файл с набор от действия ({e}) +@msg numbers out of order in {{}} quantifier числата в квантора {{}} не са в правилния ред +@msg profile colour space {other} is not RGB, CMYK or Gray цветовото пространство на профила {other} не е RGB, CMYK или Gray +@msg regular expression too large регулярният израз е твърде голям +@msg script file is not UTF-8 text: {value} файлът на скрипта не е текст в UTF-8: {value} +@msg step {step} of “{action}” runs the unknown command `{command}` стъпка {step} от „{action}“ изпълнява неизвестната команда `{command}` +@msg stop {i}: {e} спирка {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) версия {major}.{minor} на обмена на образци не се поддържа (само 1.x) +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: използвайте "{_1}" или "{_2}" +@msg the SVG's style sheets take too long to match съпоставянето на стиловете на SVG отнема твърде дълго +@msg the SVG's styles expand to more than {0} MB стиловете на SVG се разширяват до повече от {0} MB +@msg the color book holds more than {ASE_MAX_ENTRIES} colors цветовата книга съдържа повече от {ASE_MAX_ENTRIES} цвята +@msg the color book is cut short цветовата книга е прекъсната +@msg the color book's names take more than {_1} MB имената в цветовата книга заемат повече от {_1} MB +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution изображението би било {w} × {h} пиксела; растерното експортиране е ограничено до {MAX_RASTER_SIDE} пиксела на страна и {_1} мегапиксела: намалете мащаба или разделителната способност +@msg the optimised image can't be read back: {e} оптимизираното изображение не може да се прочете обратно: {e} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) боята не е свободен градиент (приложете такъв с paint.editGradient {{kind: "freeform"}}) +@msg the pixel buffer doesn't match the image size буферът на пикселите не съответства на размера на изображението +@msg the preview: {e} визуализацията: {e} +@msg the request may not read the New Document profiles folder заявката не може да чете папката с профили за нов документ +@msg the shapes are too degenerate to combine формите са твърде дегенерирали за комбиниране +@msg the shapes cross themselves and each other too often to combine формите пресичат себе си и една друга твърде често за комбиниране +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups файлът за обмен на образци съдържа повече от {ASE_MAX_ENTRIES} цвята и групи +@msg the swatch exchange file is cut short файлът за обмен на образци е прекъснат +@msg the {_1} plate can't be read: {e} плаката {_1} не може да се прочете: {e} +@msg this binary DXF file is damaged or cut short този двоичен файл DXF е повреден или прекъснат +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that това е DWG чертеж, който не може да бъде прочетен: запазете го от CAD приложението като DXF и го отворете +@msg too many classes твърде много класове +@msg too many groups твърде много групи +@msg too many layers for PSD (at most 32767) твърде много слоеве за PSD (най-много 32767) +@msg too many swatch exchange blocks твърде много блокове за обмен на образци +@msg unknown colour profile: {0} неизвестен цветови профил: {0} +@msg {_1} clashes with a built-in profile name {_1} съвпада с име на вграден профил +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} пиксела е твърде голямо за GIF (най-много 65535 пиксела на страна): намалете разделителната способност +@msg {_1}: no usable transform to/from sRGB {_1}: няма използваемо преобразуване към или от sRGB +@msg {name} is not a CMYK profile {name} не е профил CMYK +@msg {name} is not an RGB profile {name} не е профил RGB +@msg {path}: could not be read {path}: не можа да се прочете +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} пиксела е твърде голямо за JPEG (най-много 65535 пиксела на страна): намалете разделителната способност +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} пиксела е твърде голямо за Targa (най-много 65535 пиксела на страна): намалете разделителната способност +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пиксела е твърде голямо за PSD (най-много {MAX_SIDE} пиксела на страна): намалете разделителната способност +@msg the template name can't be empty името на шаблона не може да е празно +@msg the template name isn't usable as a file name името на шаблона не може да се използва като име на файл +@msg no metadata templates folder here тук няма папка с шаблони за метаданни +@msg give `name` or `path`, not both задайте `name` или `path`, но не и двете +@msg give one of `path`, `name` and `data` задайте едно от `path`, `name` и `data` +@msg mode must be replace, keep or append mode трябва да е replace, keep или append +@msg the file is not an XMP metadata template файлът не е шаблон за метаданни XMP +@msg no path painted with a brush is selected не е избран път, нарисуван с четка +@msg the selected paths are painted with brushes of different types избраните пътища са нарисувани с четки от различни типове +@msg give `params` or `reset`, not both задайте `params` или `reset`, но не и двете +@msg a bristle brush has no options of its own on a path четката с косъм няма собствени опции върху път +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all някои растерни ефекти не бяха превърнати в изображения: биха заели общо повече от 1,024 изображения или 256 мегапиксела +@msg Shape Builder: select all paths you want to merge Инструмент за създаване на форми: изберете всички пътища, които искате да обедините +@msg action step {_1} (`{id}`) failed: {reason} стъпката на действие {_1} (`{id}`) е неуспешна: {reason} +@msg `points` must be three [x, y] pairs of numbers `points` трябва да са три двойки числа [x, y] +@msg direct-select three anchor points, or give `points` изберете директно три опорни точки или задайте `points` +@msg no circle passes through these points: two are the same or all three lie on one line никоя окръжност не минава през тези точки: две от тях съвпадат или и трите лежат на една линия +@msg `{panel}` has no display sizes to cycle `{panel}` няма размери на показване за превключване +@msg the panels are not shown панелите не са показани +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first линия или друг отворен път, който не огражда площ, не променя формата на резултата; за да го включите, първо приложете към него Обект › Път › Преобразуване на щриха в контур +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} даде празен резултат: линия или друг отворен път не огражда площ; за да го включите, първо приложете към него Обект › Път › Преобразуване на щриха в контур +@msg a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first линия или друг отворен път, който не огражда площ, не добавя площ към съставната форма; за да го включите, първо приложете към него Обект › Път › Преобразуване на щриха в контур +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Извадено е {n} вградено изображение в {folder}|Извадени са {n} вградени изображения в {folder} +@msg every numbered name for {name} is taken in that folder всяко номерирано име за {name} вече е заето в тази папка +@msg Import reads a data source file ending in .csv, .tsv, .txt or .xml Импортирането чете файл с източник на данни, завършващ на .csv, .tsv, .txt или .xml +variable-kind Visibility Видимост +variable-kind Linked File Свързан файл +variable-kind Graph Data Данни за диаграма +variable-kind Unknown Непознат +variable-list-two {0}, {1} {0} и {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} и {1} +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Минимум не трябва да надхвърля Желано, нито Желано да надхвърля Максимум +@msg side is left or right, not `{v}` side е left или right, а не `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order е цяло число от 0 до {others}, а не `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (името на лента с инструменти) трябва да е низ +@msg no toolbar named `{name}` няма лента с инструменти с име `{name}` +@msg toolbar name can't be empty името на лентата с инструменти не може да е празно +@msg a toolbar name has at most {MAX_NAME} characters името на лента с инструменти има най-много {MAX_NAME} знака +@msg there is already a toolbar named `{name}` вече има лента с инструменти с име `{name}` +@msg there is already a toolbar named `{to}` вече има лента с инструменти с име `{to}` +@msg a workspace keeps at most {MAX} toolbars работното пространство съдържа най-много {MAX} ленти с инструменти +@msg name (a toolbar's name) must be a string name (името на лента с инструменти) трябва да е низ +@msg name (a toolbar's name) is required name (името на лента с инструменти) е задължително +@msg to (the new name) is required to (новото име) е задължително +@msg name must be a toolbar's name name трябва да е името на лента с инструменти # #5804 native-picked raster editor (draft translations; native review welcome). Edit Original with: Редактиране на оригинала с: file-filter Applications Приложения +@msg CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out текстът, растерните изображения, преливанията, контурите, щрихите на четки и другите обекти от CDR, които VectorCraft все още не чете, бяха пропуснати +@msg CDR fountain, pattern, texture and PostScript fills were left out запълванията от CDR с преход, мостра, текстура и PostScript бяха пропуснати +@msg colors in CDR color models VectorCraft doesn't read were opened as black цветовете в цветови модели на CDR, които VectorCraft не чете, бяха отворени като черно +@msg CDR library colors that the drawing stores only by number were opened as black spot colors цветовете от библиотеки на CDR, които чертежът съхранява само по номер, бяха отворени като черни спот цветове +@msg CDR outline arrowheads were left out върховете на стрелки на контурите от CDR бяха пропуснати +@msg CDR envelopes were not applied, and the shapes under them keep their outlines пликовете от CDR не бяха приложени и формите под тях запазват очертанията си +@msg CDR lenses and object transparency were not applied, and the objects they are on show opaque лещите и прозрачността на обекти от CDR не бяха приложени и обектите, върху които са, се показват непрозрачни +@msg parts of the drawing nested too deeply, or past the import limits, were left out части от чертежа, вложени твърде дълбоко или извън ограниченията за импортиране, бяха пропуснати +@msg damaged parts of the drawing were left out повредените части от чертежа бяха пропуснати +@msg CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard страниците от CDR, по-дълги от 163,830 pt, бяха отворени с тази дължина и графиката близо до ръбовете им е извън работната област +@msg CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out текстът, изображенията, правоъгълниците, елипсите, изрязващите пътища и другите обекти от CMX, които VectorCraft все още не чете, бяха пропуснати +@msg CMX fills other than uniform colors were left out запълванията от CMX, различни от еднородни цветове, бяха пропуснати +@msg colors in CMX color models VectorCraft doesn't read were opened as black цветовете в цветови модели на CMX, които VectorCraft не чете, бяха отворени като черно +@msg CMX library colors that the file stores only by number were opened as black spot colors цветовете от библиотеки на CMX, които файлът съхранява само по номер, бяха отворени като черни спот цветове +@msg CMX outline arrowheads were left out върховете на стрелки на контурите от CMX бяха пропуснати +@msg CMX lenses were not applied лещите от CMX не бяха приложени +@msg CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard страниците от CMX, по-дълги от 163,830 pt, бяха отворени с тази дължина и графиката близо до ръбовете им е извън работната област +@msg the file is no longer loaded файлът вече не е зареден +@msg 1 type layer came in as pixels: the text isn't editable 1 текстов слой беше импортиран като пиксели: текстът не може да се редактира +@msg {n} type layers came in as pixels: the text isn't editable {n} текстови слоя бяха импортирани като пиксели: текстът не може да се редактира +@msg 1 adjustment layer was not applied 1 коригиращ слой не беше приложен +@msg {n} adjustment layers were not applied {n} коригиращи слоя не бяха приложени +@msg 1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) 1 слой за запълване не беше нарисуван (запълване с градиент или мостра, цвят, който не може да се прочете, или форма, която не съхранява пиксели) +@msg {n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels) {n} слоя за запълване не бяха нарисувани (запълване с градиент или мостра, цвят, който не може да се прочете, или форма, която не съхранява пиксели) +@msg the layer effects of 1 layer weren't drawn ефектите на слоя на 1 слой не бяха нарисувани +@msg the layer effects of {n} layers weren't drawn ефектите на слоевете на {n} слоя не бяха нарисувани +@msg the vector masks of 1 layer weren't applied векторните маски на 1 слой не бяха приложени +@msg the vector masks of {n} layers weren't applied векторните маски на {n} слоя не бяха приложени +@msg the knockout of 1 layer wasn't applied избиването на 1 слой не беше приложено +@msg the knockout of {n} layers wasn't applied избиването на {n} слоя не беше приложено +@msg 1 layer was left out (hidden layers and the layers clipped to them) 1 слой беше пропуснат (скрити слоеве и слоевете, изрязани по тях) +@msg {n} layers were left out (hidden layers and the layers clipped to them) {n} слоя бяха пропуснати (скрити слоеве и слоевете, изрязани по тях) +@msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 слой, изрязан по слой за запълване, който не беше нарисуван, беше пропуснат +@msg {n} layers clipped to fill layers that weren't drawn were left out {n} слоя, изрязани по слоеве за запълване, които не бяха нарисувани, бяха пропуснати +@msg layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them слоевете в режими на смесване, които VectorCraft няма ({modes}), бяха обединени със слоевете под тях +@msg 1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed 1 слой в режими на смесване, които VectorCraft няма, беше импортиран като Нормално: обединяването изисква повече памет от разрешеното +@msg {n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed {n} слоя в режими на смесване, които VectorCraft няма, бяха импортирани като Нормално: обединяването изисква повече памет от разрешеното +@msg 1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed 1 слой, изрязан по слоя отдолу, беше импортиран без изрязване: обединяването изисква повече памет от разрешеното +@msg {n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed {n} слоя, изрязани по слоя отдолу, бяха импортирани без изрязване: обединяването изисква повече памет от разрешеното +@msg hiddenLayers applies to a PSD file placed with layers: true hiddenLayers се прилага към файл PSD, поставен с layers: true +@msg importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices importSlices: свързан файл PSD се поставя като плоското си изображение; задайте link: false, за да го вградите с отрязъците му +@msg layers: a linked PSD file is placed as its flat image; leave link out or give link: false layers: свързан файл PSD се поставя като плоското си изображение; пропуснете link или задайте link: false +@msg 1 slice lies outside the canvas or has no size and was left out 1 отрязък е извън платното или няма размер и беше пропуснат +@msg {n} slices lie outside the canvas or have no size and were left out {n} отрязъка са извън платното или нямат размер и бяха пропуснати +@msg 1 slice would lie outside the canvas and was left out 1 отрязък би бил извън платното и беше пропуснат +@msg {n} slices would lie outside the canvas and were left out {n} отрязъка биха били извън платното и бяха пропуснати +@msg the slices' descriptor holds too many values дескрипторът на отрязъците съдържа твърде много стойности +@msg the slices' descriptor has a version other than 16 дескрипторът на отрязъците има версия, различна от 16 +@msg the slices' descriptor has no list of slices дескрипторът на отрязъците няма списък с отрязъци +@msg the slices' descriptor lists something other than a slice дескрипторът на отрязъците изброява нещо, което не е отрязък +@msg a slice in the slices' descriptor has no bounds отрязък в дескриптора на отрязъците няма граници +@msg a slice's bounds in the slices' descriptor aren't numbers границите на отрязък в дескриптора на отрязъците не са числа +@msg the slices' descriptor nests too deep дескрипторът на отрязъците е вложен твърде дълбоко +@msg the slices can't be read ({e}) and were left out отрязъците не могат да се прочетат ({e}) и бяха пропуснати +@msg the slices are stored in version {v}, which isn't read отрязъците са съхранени във версия {v}, която не се чете +@msg the file has {count} slices, more than the {MAX_SLICES} read файлът има {count} отрязъка, повече от {MAX_SLICES}, които се четат +@msg a text in the slices has more than the {MAX_TEXT} characters read текст в отрязъците има повече от {MAX_TEXT} знака, които се четат +@msg the slices' descriptor has a reference of an unknown kind ({_1}) дескрипторът на отрязъците има препратка от неизвестен вид ({_1}) +@msg the slices' descriptor has a value of an unknown type ({_1}) дескрипторът на отрязъците има стойност от неизвестен тип ({_1}) +@msg the layers can't be read ({e}): the file was placed as its merged image слоевете не могат да се прочетат ({e}): файлът беше поставен като обединеното си изображение +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on обектът {_1} е изображение, променено с Перспективно изкривяване или Свободно изкривяване, с което тази команда не работи +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape изображението {_1} не може да се изкриви така: ъглите му не биха образували изпъкнала форма +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon изображението {_1} не може да се изкриви така: ъглите му биха пресекли хоризонта на деформацията +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map изображението {_1} не може да се изкриви така: ъглите му биха били твърде близо един до друг за перспективно преобразуване diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..35d8b2c4de 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1374,6 +1374,30 @@ fn bundled_catalogs_are_consistent() { } } +/// A translated message starts and ends with whitespace only where its English does, so a status +/// message is not shown with a stray space. +#[test] +fn message_translations_keep_their_english_edges() { + let mut wrong = Vec::new(); + for l in &LANGUAGES { + let (entries, _) = parse_entries(l.source); + for (ctx, src, tr) in entries.iter().filter(|(ctx, _, _)| ctx == "@msg" || ctx == "@msgplural") { + let plural = ctx == "@msgplural"; + let sources: Vec<&str> = if plural { src.split('|').collect() } else { vec![src.as_str()] }; + let forms: Vec<&str> = if plural { tr.split('|').collect() } else { vec![tr.as_str()] }; + for (i, form) in forms.into_iter().enumerate() { + let english = sources.get(i).or(sources.last()).copied().unwrap_or_default(); + let lead = form.starts_with(char::is_whitespace) && !english.starts_with(char::is_whitespace); + let trail = form.ends_with(char::is_whitespace) && !english.ends_with(char::is_whitespace); + if lead || trail { + wrong.push(format!("{}: {src:?} -> {form:?}", l.code)); + } + } + } + } + assert!(wrong.is_empty(), "{} message translations add whitespace at an edge:\n{}", wrong.len(), wrong.join("\n")); +} + /// A catalog that doesn't claim complete menus may still only hold strings the UI shows (menu /// labels, command labels, `tl!` literals), so labels from other apps don't creep in. #[test] @@ -6859,7 +6883,7 @@ fn translated_messages_keep_the_field_names_and_values_their_english_lists() { /// the messages each one lacks. const COMPLETE_MESSAGES: &[&str] = &[ "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", "ca", - "nl", "da", "id", + "nl", "da", "id", "bg", ]; /// Crates whose error and status messages reach the status bar, the crates whose errors the diff --git a/docs/development.md b/docs/development.md index fb30fad2bb..99c4ff4b7e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -308,7 +308,7 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE ``[{j}] `{_1}`: {why}``, so its reason is translated while a JSON array stays as it is. A literal brace in a row is written `{{` or `}}`, in the English and in the translation: a message made with `format!` keeps the doubled braces of its format string, and a plain string literal has each of its braces doubled, so the row for - `"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan, Dutch, Danish and Indonesian + `"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan, Dutch, Danish, Indonesian and Bulgarian translate status and error messages (`COMPLETE_MESSAGES` in `i18n::tests`); the untranslated report lists the message literals the scan finds, and the phrases a parameter schema's error builds at run time (`SCHEMA_PHRASES`), that one of them has no row for. The scan covers the crates in `MESSAGE_CRATES`, the diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 95ed33bf76..08a6962fc0 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -17,7 +17,7 @@ translation never fails a test or a build: the interface shows the English text `cargo xtask ci` prints the untranslated report (`cargo xtask i18n-report` alone), which lists per language the strings missing from each catalog with the `complete_menus` flag and the messages missing from each language in the `COMPLETE_MESSAGES` list. Every non-English language marked "full" has the flag, and all of them except -Bosnian and Bulgarian are in the list. No language has help content: there is no translated (or +Bosnian are in the list. No language has help content: there is no translated (or English) in-app help, and the docs are English. **Native review:** every catalog was written clean-room from the English meaning, most of it by agents @@ -66,7 +66,7 @@ plus review. Native-speaker review is human work and isn't in the hours. | Czech | `cs` | 9,761 rows, 3,742 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`): the untranslated report lists 222 missing Czech messages, and 15 messages that no checked language has a row for | catalog complete; render-site gaps reduced; native review pending | | Bosnian | `bs` | 7,227 rows, 1,205 of them `@msg` and 47 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`): the untranslated report lists 113 missing menu strings, 66 `tl!` literals and 30 undo labels for it; not in `COMPLETE_MESSAGES`, so the report does not check its messages; one/few/other plurals | full; AI-assisted, native review pending | | Swedish | `sv` | 9,498 rows, 3,311 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`): the untranslated report lists 647 missing messages for it, and 31 menu strings, 14 `tl!` literals and 6 undo labels; one/other plurals | full; native review welcome | -| Bulgarian | `bg` | 7,133 rows, 1,111 of them `@msg` and 47 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`): the untranslated report lists 76 menu strings, 48 `tl!` literals, 16 undo labels and 45 swatch names for it; its messages are partial | full; AI-drafted, native review pending | +| Bulgarian | `bg` | 8,939 rows, 2,143 of them `@msg` and 56 `@msgplural` (counted 2026-11-20 on `main` at `5b52369187`): in `COMPLETE_MESSAGES`, and the untranslated report lists 71 menu strings, 43 `tl!` literals, 13 undo labels, 45 swatch names and 1,947 messages for it; its messages are partial | full; AI-drafted, native review pending | | Greek | `el` | 8,003 rows, 1,972 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`): the untranslated report lists 1,974 missing messages for it | full; native review welcome | | Georgian | `ka` | 9,758 rows, 3,740 of them `@msg` and 49 `@msgplural` (counted 2026-11-15): menus, panels, dialogs and plurals (one count-neutral form); the untranslated report lists 1 missing Georgian message; reviewed by a native speaker | full | | Turkish | `tr` | 9,784 rows, 3,746 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`); 235 messages, 79 menu strings, 39 `tl!` literals, 16 undo labels and the default swatch names still fall back to English | full | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8f1d0547b4..918fc9bdb2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1836,7 +1836,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a drag on the Tabs panel's ruler or a value typed in its X field moves a tab stop past another stop, the moved stop stays selected. With the Selection tool, the Tabs panel shows the ruler and stops of the first paragraph of the first selected text object, also when the text is inside a selected group or a shape is selected before it; a selection without text shows "No text selected". A stop set on that ruler is set on every selected text object and the text in selected groups, and other objects are left as they were. This is VectorCraft's own rule. Tests `panels::tabs::tests::the_ruler_shows_text_selected_after_an_object_that_is_not_text`, `the_ruler_shows_text_inside_a_selected_group`, `a_stop_added_on_a_mixed_selection_sets_every_selected_text` and `a_selection_without_text_shows_no_ruler`. The Tabs panel menu's Clear All Tabs (`text.tabs.clear`), Delete Tab and Repeat Tab (`text.tabs.set`) can be chosen while the panel's ruler shows tab stops. Delete Tab removes the stop selected on the ruler. Repeat Tab replaces the stops after the selected stop with up to 20 copies of it. The copies are spaced by the selected stop's distance from the stop before it, or from the paragraph's left indent (18 pt further in for each list level past the first) when it is the first stop, and no copy is placed at 2,000 pt or beyond. Clear All Tabs removes every stop, so the default stops every ½ inch apply again. -- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Finnish, Turkish, Catalan, Dutch, Danish and Indonesian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them (with Skew, 3D Ribbon and Stair Step only on a path that runs to the right), in one column that Align to Path Baseline or Center centers on the path and that the caret and selection span); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). +- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Finnish, Turkish, Catalan, Dutch, Danish, Indonesian and Bulgarian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them (with Skew, 3D Ribbon and Stair Step only on a path that runs to the right), in one column that Align to Path Baseline or Center centers on the path and that the caret and selection span); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). The Russian catalog (`crates/ui-egui/src/i18n/ru.tsv`) has 1,811 more `@msg` rows, for status and error messages of commands, scripts and file import and export, 3,444 `@msg` rows in all counted on 2026-11-13 (`russian_translates_command_script_and_file_messages` in `crates/ui-egui/src/i18n/tests.rs`). Scores and estimates are unchanged. With Line-end Punctuation Half Width, both composers measure a line with its last character set as narrow as Mojikumi sets it ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-mojikumi-for-japanese-text-composition.html)): a closing bracket, comma or full stop that fits at half width ends the line, and the character before it no longer goes to the next line with it. A mark that already lost its half to the punctuation after it and a line that ends in a hyphen take nothing more off, and the quarter em between Japanese and Latin text counts only where the line ends there. Kinsoku Shori Type and Burasagari Regular measure lines the same way; right-to-left lines and Mojikumi None break as before. In a frame that is not a rectangle, or with text wrap, a line's first word is measured as it is set (an opening bracket at its start flush, its last character narrowed) when layout looks for a line wide enough for it, and it ends only where the line may break, so kinsoku keeps an opening bracket with the character after it and a No Break run counts whole (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/vertical.rs`). Scores and estimates are unchanged. Burasagari ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)) leaves a right-to-left paragraph's comma or full stop inside its line, which then ends at a break where it fits with the mark, and in a left-to-right line with right-to-left text and a tab it hangs a mark only when the mark is drawn at the line's right end and the rest of the line fits as drawn; otherwise the line ends at the latest break that fits as drawn. Both are VectorCraft's own rules (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/hang.rs`). Scores and estimates are unchanged. From 8a878f0ebebbf6aa87d2e9597bab6d215294e494 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:41:10 -0800 Subject: [PATCH 33/78] Artboards: a finger press that only navigates does not place Rearrange's waiting artboards Once a pen has been seen, a finger press on the canvas navigates the view. Rearrange's waiting placement took that press as its click and moved the artboards. The placement now skips it, and the press pans as before. --- crates/ui-egui/src/canvas/tests.rs | 35 +++++++++++++++++++ .../src/dialogs/rearrange_artboards.rs | 4 ++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 8e56795605..fae39555f3 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -12660,6 +12660,41 @@ fn rearrange_places_the_selected_artboards_with_enter_and_lets_space_pan() { assert_eq!(undo(&app), steps + 1); } +/// Once a pen has been seen, a finger press on the canvas navigates and does not place a waiting +/// Rearrange; a mouse press then places it. +#[test] +fn rearrange_is_not_placed_by_a_finger_once_a_pen_was_seen() { + use crate::touch::{Source, set_pen_seen, set_source}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([1])); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let (before, steps) = (boards(&app), undo(&app)); + crate::panels::artboards::open_rearrange_selected(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(app.ui.rearrange_placement.is_some()); + let at = app.canvas_rect.unwrap().center() + vec2(40.0, 30.0); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + set_source(Source::Pen); + set_source(Source::Finger); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(true)]); + frame(&mut app, &ctx, vec![button(false)]); + let finger = (app.ui.rearrange_placement.is_some(), boards(&app), undo(&app)); + set_source(Source::Mouse); + set_pen_seen(false); + assert_eq!(finger, (true, before.clone(), steps), "the finger navigates"); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(true)]); + frame(&mut app, &ctx, vec![button(false)]); + assert!(app.ui.rearrange_placement.is_none(), "the mouse places it"); + assert_ne!(boards(&app), before); + assert_eq!(undo(&app), steps + 1); +} + /// A waiting Rearrange is dropped when its artboards change places in the list before the click, /// so the click moves no artboard the tool did not select. #[test] diff --git a/crates/ui-egui/src/dialogs/rearrange_artboards.rs b/crates/ui-egui/src/dialogs/rearrange_artboards.rs index 42c31efa7e..c8ef10df6d 100644 --- a/crates/ui-egui/src/dialogs/rearrange_artboards.rs +++ b/crates/ui-egui/src/dialogs/rearrange_artboards.rs @@ -140,7 +140,9 @@ pub(crate) fn placement_input(app: &mut VectorcraftApp, ui: &egui::Ui, resp: &eg ui.ctx().request_repaint(); } let xf = Xf::at(rect, app.view().unwrap_or(&View::default()), app.canvas_ui_zoom); - let pressed = pointer.interact_pos().filter(|p| pointer.primary_pressed() && resp.hovered() && rect.contains(*p)); + // A finger press once a pen has been seen navigates the view and places nothing. + let navigates = crate::touch::finger_navigates_only(); + let pressed = pointer.interact_pos().filter(|p| pointer.primary_pressed() && !navigates && resp.hovered() && rect.contains(*p)); // Enter belongs to the control that has the keyboard focus, when another one has it. let free_keys = ui.memory(|m| m.focused().is_none_or(|id| id == resp.id)); let entered = armed && free_keys && ui.input(|i| i.key_pressed(egui::Key::Enter)); From 2efe8814da093334841b14fd4dd8b79cbaa6c163 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:31:53 -0800 Subject: [PATCH 34/78] Tests: drive the finger Rearrange check with touch events and check the view pans The finger case of rearrange_is_not_placed_by_a_finger_once_a_pen_was_seen now sends touch Start, Move and End events with the first finger pressing as the pointer, adds a second finger and drags both, and checks that the view pans while the waiting placement, the artboards and the history stay as they were. The mouse placement check is unchanged. rearrange_refuses_bad_indices_and_at also checks that an `at` that would put an artboard past the canvas is refused and leaves the artboards and the history as they were. --- crates/engine/src/tests/newdoc.rs | 5 ++++- crates/ui-egui/src/canvas/tests.rs | 26 +++++++++++++++++++++----- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index b60f40f023..53838c9bd7 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -601,7 +601,8 @@ fn rearrange_of_listed_artboards_starts_at_the_first_and_keeps_locked_ones() { } /// Rearrange refuses `indices` that are not a non-empty list of artboards, and an `at` that is not -/// [x, y], before anything moves; a listed index given twice counts once. +/// [x, y], before anything moves, and leaves the document as it was when `at` would put an +/// artboard past the canvas; a listed index given twice counts once. #[test] fn rearrange_refuses_bad_indices_and_at() { let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3})); @@ -616,6 +617,8 @@ fn rearrange_refuses_bad_indices_and_at() { (json!({"indices": [0, 1], "at": [1]}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"), (json!({"indices": [0, 1], "at": "0,0"}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"), (json!({"at": [0, "1"]}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"), + (json!({"indices": [0], "at": [1e20, 0]}), "result would exceed the canvas (coordinates out of range)"), + (json!({"at": [0, -4.000001e6]}), "result would exceed the canvas (coordinates out of range)"), ] { let err = s.execute("artboard.rearrange", &p).unwrap_err().to_string(); assert_eq!(err, msg, "{p}"); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index fae39555f3..736f00632c 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -12661,10 +12661,12 @@ fn rearrange_places_the_selected_artboards_with_enter_and_lets_space_pan() { } /// Once a pen has been seen, a finger press on the canvas navigates and does not place a waiting -/// Rearrange; a mouse press then places it. +/// Rearrange: the first finger presses as the pointer, a second lands and both drag, and the view +/// pans while the artboards and the history stay as they were. A mouse press then places it. #[test] fn rearrange_is_not_placed_by_a_finger_once_a_pen_was_seen() { use crate::touch::{Source, set_pen_seen, set_source}; + use egui::TouchPhase::{End, Move, Start}; let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); app.select_tool("artboard"); @@ -12680,14 +12682,28 @@ fn rearrange_is_not_placed_by_a_finger_once_a_pen_was_seen() { assert!(app.ui.rearrange_placement.is_some()); let at = app.canvas_rect.unwrap().center() + vec2(40.0, 30.0); let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let center = |app: &VectorcraftApp| app.view().unwrap().center; + let view_before = center(&app); + // The platform says a finger drives the pointer once a pen has been seen, and egui makes the + // first finger the pointer too. set_source(Source::Pen); set_source(Source::Finger); - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(true)]); - frame(&mut app, &ctx, vec![button(false)]); - let finger = (app.ui.rearrange_placement.is_some(), boards(&app), undo(&app)); + let second = at + vec2(80.0, 0.0); + frame(&mut app, &ctx, vec![finger(0, Start, at), egui::Event::PointerMoved(at), button(true)]); + let pressed = app.ui.rearrange_placement.is_some(); + frame(&mut app, &ctx, vec![finger(1, Start, second)]); + for k in 1..=3 { + let d = vec2(0.0, 20.0 * k as f32); + frame(&mut app, &ctx, vec![finger(0, Move, at + d), finger(1, Move, second + d), egui::Event::PointerMoved(at + d)]); + } + let d = vec2(0.0, 60.0); + frame(&mut app, &ctx, vec![finger(0, End, at + d), finger(1, End, second + d), finger_button(at + d, false), egui::Event::PointerGone]); + let touched = (pressed, app.ui.rearrange_placement.is_some(), boards(&app), undo(&app)); + let panned = center(&app) != view_before; set_source(Source::Mouse); set_pen_seen(false); - assert_eq!(finger, (true, before.clone(), steps), "the finger navigates"); + assert_eq!(touched, (true, true, before.clone(), steps), "the finger navigates"); + assert!(panned, "two fingers pan the view"); frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(true)]); frame(&mut app, &ctx, vec![button(false)]); assert!(app.ui.rearrange_placement.is_none(), "the mouse places it"); From e50cc27abd314b6a63e32e0419ae08bb054d3f61 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 08:18:11 -0800 Subject: [PATCH 35/78] Tool icons: every tool gets an icon of its own instead of sharing its group's The nine graph tools showed the same column chart, the eight symbolism tools the same spray can, and Perspective Selection, Slice Selection, Enclosing Lasso, Polygonal Lasso, the Corner Tool, Slide Anchor Along Path and Shared Edge Merge each reused the icon of another tool. The 3D Box Tool asked for an icon that does not exist and showed the dashed placeholder. Each of these tools now has an original icon drawn in the dc-* style (24x24, 1.5 stroke, round caps) that shows what the tool does: - Each graph tool draws its own chart type. - The symbolism tools show symbols being moved, pulled together, resized, turned, tinted, faded or styled. - The Lasso and Slice tools get dc-* icons too, so the three lasso tools and the two slice tools each read as one family. The Enclosing Lasso adds a filled square inside the Lasso's loop, and the Polygonal Lasso draws the loop with straight sides and keeps the same knot and tail. The Slice and Slice Selection tools both show a dashed slice outline with a corner tag, the Slice Tool with a knife beside it and Slice Selection with a pointer. - Perspective Selection shows a smaller perspective grid with a pointer. - The 3D Box Tool uses the cube icon that the 3D and Materials panel uses. Each new file has an ASSETS.md row. every_tool_has_an_icon_no_other_tool_uses checks that every cataloged tool, the add-ons' included, maps to an existing icon that is not the placeholder and that no other tool uses. --- ASSETS.md | 25 +++++++++++++++ assets/icons/dc-corner-tool.svg | 1 + assets/icons/dc-graph-area.svg | 1 + assets/icons/dc-graph-bar.svg | 1 + assets/icons/dc-graph-column.svg | 1 + assets/icons/dc-graph-line.svg | 1 + assets/icons/dc-graph-pie.svg | 1 + assets/icons/dc-graph-radar.svg | 1 + assets/icons/dc-graph-scatter.svg | 1 + assets/icons/dc-graph-stacked-bar.svg | 1 + assets/icons/dc-graph-stacked-column.svg | 1 + assets/icons/dc-lasso-enclosing.svg | 1 + assets/icons/dc-lasso-polygonal.svg | 1 + assets/icons/dc-lasso.svg | 1 + assets/icons/dc-perspective-select.svg | 1 + assets/icons/dc-shared-edge.svg | 1 + assets/icons/dc-slice-select.svg | 1 + assets/icons/dc-slice.svg | 1 + assets/icons/dc-slide-anchor.svg | 1 + assets/icons/dc-symbol-screener.svg | 1 + assets/icons/dc-symbol-scruncher.svg | 1 + assets/icons/dc-symbol-shifter.svg | 1 + assets/icons/dc-symbol-sizer.svg | 1 + assets/icons/dc-symbol-spinner.svg | 1 + assets/icons/dc-symbol-stainer.svg | 1 + assets/icons/dc-symbol-styler.svg | 1 + crates/tools/src/addons.rs | 13 ++++---- crates/tools/src/catalog.rs | 34 ++++++++++----------- crates/ui-egui/src/icon_data.rs | 25 +++++++++++++++ crates/ui-egui/src/icons.rs | 39 +++++++++++++++++++++--- 30 files changed, 134 insertions(+), 27 deletions(-) create mode 100644 assets/icons/dc-corner-tool.svg create mode 100644 assets/icons/dc-graph-area.svg create mode 100644 assets/icons/dc-graph-bar.svg create mode 100644 assets/icons/dc-graph-column.svg create mode 100644 assets/icons/dc-graph-line.svg create mode 100644 assets/icons/dc-graph-pie.svg create mode 100644 assets/icons/dc-graph-radar.svg create mode 100644 assets/icons/dc-graph-scatter.svg create mode 100644 assets/icons/dc-graph-stacked-bar.svg create mode 100644 assets/icons/dc-graph-stacked-column.svg create mode 100644 assets/icons/dc-lasso-enclosing.svg create mode 100644 assets/icons/dc-lasso-polygonal.svg create mode 100644 assets/icons/dc-lasso.svg create mode 100644 assets/icons/dc-perspective-select.svg create mode 100644 assets/icons/dc-shared-edge.svg create mode 100644 assets/icons/dc-slice-select.svg create mode 100644 assets/icons/dc-slice.svg create mode 100644 assets/icons/dc-slide-anchor.svg create mode 100644 assets/icons/dc-symbol-screener.svg create mode 100644 assets/icons/dc-symbol-scruncher.svg create mode 100644 assets/icons/dc-symbol-shifter.svg create mode 100644 assets/icons/dc-symbol-sizer.svg create mode 100644 assets/icons/dc-symbol-spinner.svg create mode 100644 assets/icons/dc-symbol-stainer.svg create mode 100644 assets/icons/dc-symbol-styler.svg diff --git a/ASSETS.md b/ASSETS.md index 2812067e00..703b19e35b 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -134,6 +134,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | | +| `assets/icons/dc-corner-tool.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-curvature-circle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (an arch with the circle that touches it at its top, and that circle's center) | MIT OR Apache-2.0 | | @@ -172,6 +173,15 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-grad-stroke-along.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-grad-stroke-within.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-gradient.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-area.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-bar.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-column.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-line.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-pie.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-radar.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-scatter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-stacked-bar.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-graph-stacked-column.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-graphic-styles.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-grid-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-group-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -180,6 +190,9 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-join-round.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-join.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-knife.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-lasso-enclosing.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-lasso-polygonal.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-lasso.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-line-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-line.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-list-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -207,6 +220,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-para-rtl.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-path-eraser.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-pathfinder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-perspective-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-perspective.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-pf-crop.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-pf-divide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -239,7 +253,11 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-screen-mode.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-selection.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-shape-builder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-shared-edge.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-shear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-slice-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-slice.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-slide-anchor.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-smooth.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-stroke-center.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-stroke-inside.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -247,7 +265,14 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-stroke.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-swap.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-swatch-kinds.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-screener.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-scruncher.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-shifter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-sizer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-spinner.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-symbol-sprayer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-stainer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-symbol-styler.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-touch-type.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-transform-panel.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-transparency.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/assets/icons/dc-corner-tool.svg b/assets/icons/dc-corner-tool.svg new file mode 100644 index 0000000000..7b467ce306 --- /dev/null +++ b/assets/icons/dc-corner-tool.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-area.svg b/assets/icons/dc-graph-area.svg new file mode 100644 index 0000000000..4aae0a6663 --- /dev/null +++ b/assets/icons/dc-graph-area.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-bar.svg b/assets/icons/dc-graph-bar.svg new file mode 100644 index 0000000000..ee08f9eba3 --- /dev/null +++ b/assets/icons/dc-graph-bar.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-column.svg b/assets/icons/dc-graph-column.svg new file mode 100644 index 0000000000..bf896fe563 --- /dev/null +++ b/assets/icons/dc-graph-column.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-line.svg b/assets/icons/dc-graph-line.svg new file mode 100644 index 0000000000..46a2ef7ecd --- /dev/null +++ b/assets/icons/dc-graph-line.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-pie.svg b/assets/icons/dc-graph-pie.svg new file mode 100644 index 0000000000..a406bf7b7a --- /dev/null +++ b/assets/icons/dc-graph-pie.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-radar.svg b/assets/icons/dc-graph-radar.svg new file mode 100644 index 0000000000..82fe72d29e --- /dev/null +++ b/assets/icons/dc-graph-radar.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-scatter.svg b/assets/icons/dc-graph-scatter.svg new file mode 100644 index 0000000000..c674fc8cd1 --- /dev/null +++ b/assets/icons/dc-graph-scatter.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-stacked-bar.svg b/assets/icons/dc-graph-stacked-bar.svg new file mode 100644 index 0000000000..989dfaaf58 --- /dev/null +++ b/assets/icons/dc-graph-stacked-bar.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-stacked-column.svg b/assets/icons/dc-graph-stacked-column.svg new file mode 100644 index 0000000000..f7f234f280 --- /dev/null +++ b/assets/icons/dc-graph-stacked-column.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-lasso-enclosing.svg b/assets/icons/dc-lasso-enclosing.svg new file mode 100644 index 0000000000..c15d730f97 --- /dev/null +++ b/assets/icons/dc-lasso-enclosing.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-lasso-polygonal.svg b/assets/icons/dc-lasso-polygonal.svg new file mode 100644 index 0000000000..4f69572878 --- /dev/null +++ b/assets/icons/dc-lasso-polygonal.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-lasso.svg b/assets/icons/dc-lasso.svg new file mode 100644 index 0000000000..5143e0d447 --- /dev/null +++ b/assets/icons/dc-lasso.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-perspective-select.svg b/assets/icons/dc-perspective-select.svg new file mode 100644 index 0000000000..e31fa0b254 --- /dev/null +++ b/assets/icons/dc-perspective-select.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-shared-edge.svg b/assets/icons/dc-shared-edge.svg new file mode 100644 index 0000000000..7301265544 --- /dev/null +++ b/assets/icons/dc-shared-edge.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-slice-select.svg b/assets/icons/dc-slice-select.svg new file mode 100644 index 0000000000..9cdce42a1e --- /dev/null +++ b/assets/icons/dc-slice-select.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-slice.svg b/assets/icons/dc-slice.svg new file mode 100644 index 0000000000..5a1791b428 --- /dev/null +++ b/assets/icons/dc-slice.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-slide-anchor.svg b/assets/icons/dc-slide-anchor.svg new file mode 100644 index 0000000000..0107876985 --- /dev/null +++ b/assets/icons/dc-slide-anchor.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-screener.svg b/assets/icons/dc-symbol-screener.svg new file mode 100644 index 0000000000..cbb9aa899f --- /dev/null +++ b/assets/icons/dc-symbol-screener.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-scruncher.svg b/assets/icons/dc-symbol-scruncher.svg new file mode 100644 index 0000000000..4b4203acba --- /dev/null +++ b/assets/icons/dc-symbol-scruncher.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-shifter.svg b/assets/icons/dc-symbol-shifter.svg new file mode 100644 index 0000000000..bd3c2b67d2 --- /dev/null +++ b/assets/icons/dc-symbol-shifter.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-sizer.svg b/assets/icons/dc-symbol-sizer.svg new file mode 100644 index 0000000000..771627cf72 --- /dev/null +++ b/assets/icons/dc-symbol-sizer.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-spinner.svg b/assets/icons/dc-symbol-spinner.svg new file mode 100644 index 0000000000..c5a3ab7423 --- /dev/null +++ b/assets/icons/dc-symbol-spinner.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-stainer.svg b/assets/icons/dc-symbol-stainer.svg new file mode 100644 index 0000000000..79f2541d28 --- /dev/null +++ b/assets/icons/dc-symbol-stainer.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-styler.svg b/assets/icons/dc-symbol-styler.svg new file mode 100644 index 0000000000..b81ffaa5e7 --- /dev/null +++ b/assets/icons/dc-symbol-styler.svg @@ -0,0 +1 @@ + diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index c0223aedb9..66eb645369 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -29,9 +29,9 @@ pub const PATH_TOOLS: &[ToolInfo] = &[ ToolInfo { id: extend_path::ID, label: "Extend Path Tool", shortcut: None, icon: "dc-arrow-extend" }, ToolInfo { id: measure_inspect::ID, label: "Measure & Inspect Tool", shortcut: None, icon: "ruler" }, ToolInfo { id: parametric_shape::ID, label: "Parametric Shape Tool", shortcut: None, icon: "hexagon" }, - ToolInfo { id: corner_tool::ID, label: "Corner Tool", shortcut: None, icon: "dc-rounded-rect" }, - ToolInfo { id: slide_anchor::ID, label: "Slide Anchor Along Path", shortcut: None, icon: "dc-anchor" }, - ToolInfo { id: shared_edge::ID, label: "Shared Edge Merge Tool", shortcut: None, icon: "dc-join" }, + ToolInfo { id: corner_tool::ID, label: "Corner Tool", shortcut: None, icon: "dc-corner-tool" }, + ToolInfo { id: slide_anchor::ID, label: "Slide Anchor Along Path", shortcut: None, icon: "dc-slide-anchor" }, + ToolInfo { id: shared_edge::ID, label: "Shared Edge Merge Tool", shortcut: None, icon: "dc-shared-edge" }, ToolInfo { id: tangent_circle::ID, label: "Tangent Circle Tool", shortcut: None, icon: "circle" }, ]; @@ -40,9 +40,10 @@ pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart pub const CONTOUR: &[ToolInfo] = &[ToolInfo { id: contour::ID, label: "Contour Tool", shortcut: None, icon: "tool-contour" }]; -pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "box" }]; +pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "dc-cube" }]; -pub const POLYGONAL_LASSO: &[ToolInfo] = &[ToolInfo { id: polygonal_lasso::ID, label: "Polygonal Lasso Tool", shortcut: None, icon: "tool-lasso" }]; +pub const POLYGONAL_LASSO: &[ToolInfo] = + &[ToolInfo { id: polygonal_lasso::ID, label: "Polygonal Lasso Tool", shortcut: None, icon: "dc-lasso-polygonal" }]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the /// heading the All Tools drawer lists it under (its add-on's name). @@ -128,7 +129,7 @@ mod tests { let ids: Vec<_> = groups[0].iter().map(|t| t.id).collect(); assert_eq!(ids, ["lasso", id]); let info = crate::tool_info(id).expect("catalogued"); - assert_eq!((info.label, info.shortcut, info.icon), ("Enclosing Lasso Tool", None, "tool-lasso")); + assert_eq!((info.label, info.shortcut, info.icon), ("Enclosing Lasso Tool", None, "tool-lasso-enclosing")); assert_eq!(crate::tool_info("lasso").and_then(|t| t.shortcut), Some("Q"), "the Lasso keeps its shortcut"); assert_eq!(create(id).map(|tool| tool.id()), Some(id)); assert!(heading(id).is_none(), "not listed again under the add-on"); diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 2dc0774aa2..54b50f0aa6 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -27,7 +27,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ &[ t("lasso", "Lasso Tool", Some("Q"), "tool-lasso"), // Enclosing Lasso's tool, kept out of `addons::GROUPS` so that `all_tools` lists it once. - t(crate::addons::enclosing_lasso::ID, "Enclosing Lasso Tool", None, "tool-lasso"), + t(crate::addons::enclosing_lasso::ID, "Enclosing Lasso Tool", None, "tool-lasso-enclosing"), ], &[ t("pen", "Pen Tool", Some("P"), "tool-pen"), @@ -117,29 +117,29 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ &[t("dimension", "Dimension Tool", None, "tool-dimension")], &[ t("symbolSprayer", "Symbol Sprayer Tool", Some("Shift+S"), "tool-symbol"), - t("symbolShifter", "Symbol Shifter Tool", None, "tool-symbol"), - t("symbolScruncher", "Symbol Scruncher Tool", None, "tool-symbol"), - t("symbolSizer", "Symbol Sizer Tool", None, "tool-symbol"), - t("symbolSpinner", "Symbol Spinner Tool", None, "tool-symbol"), - t("symbolStainer", "Symbol Stainer Tool", None, "tool-symbol"), - t("symbolScreener", "Symbol Screener Tool", None, "tool-symbol"), - t("symbolStyler", "Symbol Styler Tool", None, "tool-symbol"), + t("symbolShifter", "Symbol Shifter Tool", None, "tool-symbol-shifter"), + t("symbolScruncher", "Symbol Scruncher Tool", None, "tool-symbol-scruncher"), + t("symbolSizer", "Symbol Sizer Tool", None, "tool-symbol-sizer"), + t("symbolSpinner", "Symbol Spinner Tool", None, "tool-symbol-spinner"), + t("symbolStainer", "Symbol Stainer Tool", None, "tool-symbol-stainer"), + t("symbolScreener", "Symbol Screener Tool", None, "tool-symbol-screener"), + t("symbolStyler", "Symbol Styler Tool", None, "tool-symbol-styler"), ], &[ t("columnGraph", "Column Graph Tool", Some("J"), "tool-graph"), - t("stackedColumnGraph", "Stacked Column Graph Tool", None, "tool-graph"), - t("barGraph", "Bar Graph Tool", None, "tool-graph"), - t("stackedBarGraph", "Stacked Bar Graph Tool", None, "tool-graph"), - t("lineGraph", "Line Graph Tool", None, "tool-graph"), - t("areaGraph", "Area Graph Tool", None, "tool-graph"), - t("scatterGraph", "Scatter Graph Tool", None, "tool-graph"), - t("pieGraph", "Pie Graph Tool", None, "tool-graph"), - t("radarGraph", "Radar Graph Tool", None, "tool-graph"), + t("stackedColumnGraph", "Stacked Column Graph Tool", None, "tool-graph-stacked-column"), + t("barGraph", "Bar Graph Tool", None, "tool-graph-bar"), + t("stackedBarGraph", "Stacked Bar Graph Tool", None, "tool-graph-stacked-bar"), + t("lineGraph", "Line Graph Tool", None, "tool-graph-line"), + t("areaGraph", "Area Graph Tool", None, "tool-graph-area"), + t("scatterGraph", "Scatter Graph Tool", None, "tool-graph-scatter"), + t("pieGraph", "Pie Graph Tool", None, "tool-graph-pie"), + t("radarGraph", "Radar Graph Tool", None, "tool-graph-radar"), ], &[ t("artboard", "Artboard Tool", Some("Shift+O"), "tool-artboard"), t("slice", "Slice Tool", Some("Shift+K"), "tool-slice"), - t("sliceSelection", "Slice Selection Tool", None, "tool-slice"), + t("sliceSelection", "Slice Selection Tool", None, "tool-slice-select"), ], &[ t("hand", "Hand Tool", Some("H"), "tool-hand"), diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 41f93d18df..1e030909b4 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -63,6 +63,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-clear", include_bytes!("../../../assets/icons/dc-clear.svg")), ("dc-color-guide", include_bytes!("../../../assets/icons/dc-color-guide.svg")), ("dc-contour", include_bytes!("../../../assets/icons/dc-contour.svg")), + ("dc-corner-tool", include_bytes!("../../../assets/icons/dc-corner-tool.svg")), ("dc-crystallize", include_bytes!("../../../assets/icons/dc-crystallize.svg")), ("dc-cube", include_bytes!("../../../assets/icons/dc-cube.svg")), ("dc-curvature-circle", include_bytes!("../../../assets/icons/dc-curvature-circle.svg")), @@ -102,6 +103,15 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-grad-stroke-along", include_bytes!("../../../assets/icons/dc-grad-stroke-along.svg")), ("dc-grad-stroke-within", include_bytes!("../../../assets/icons/dc-grad-stroke-within.svg")), ("dc-gradient", include_bytes!("../../../assets/icons/dc-gradient.svg")), + ("dc-graph-area", include_bytes!("../../../assets/icons/dc-graph-area.svg")), + ("dc-graph-bar", include_bytes!("../../../assets/icons/dc-graph-bar.svg")), + ("dc-graph-column", include_bytes!("../../../assets/icons/dc-graph-column.svg")), + ("dc-graph-line", include_bytes!("../../../assets/icons/dc-graph-line.svg")), + ("dc-graph-pie", include_bytes!("../../../assets/icons/dc-graph-pie.svg")), + ("dc-graph-radar", include_bytes!("../../../assets/icons/dc-graph-radar.svg")), + ("dc-graph-scatter", include_bytes!("../../../assets/icons/dc-graph-scatter.svg")), + ("dc-graph-stacked-bar", include_bytes!("../../../assets/icons/dc-graph-stacked-bar.svg")), + ("dc-graph-stacked-column", include_bytes!("../../../assets/icons/dc-graph-stacked-column.svg")), ("dc-graphic-styles", include_bytes!("../../../assets/icons/dc-graphic-styles.svg")), ("dc-grid-view", include_bytes!("../../../assets/icons/dc-grid-view.svg")), ("dc-group-select", include_bytes!("../../../assets/icons/dc-group-select.svg")), @@ -110,6 +120,9 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-join-miter", include_bytes!("../../../assets/icons/dc-join-miter.svg")), ("dc-join-round", include_bytes!("../../../assets/icons/dc-join-round.svg")), ("dc-knife", include_bytes!("../../../assets/icons/dc-knife.svg")), + ("dc-lasso", include_bytes!("../../../assets/icons/dc-lasso.svg")), + ("dc-lasso-enclosing", include_bytes!("../../../assets/icons/dc-lasso-enclosing.svg")), + ("dc-lasso-polygonal", include_bytes!("../../../assets/icons/dc-lasso-polygonal.svg")), ("dc-line", include_bytes!("../../../assets/icons/dc-line.svg")), ("dc-line-cut", include_bytes!("../../../assets/icons/dc-line-cut.svg")), ("dc-list-view", include_bytes!("../../../assets/icons/dc-list-view.svg")), @@ -138,6 +151,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-path-eraser", include_bytes!("../../../assets/icons/dc-path-eraser.svg")), ("dc-pathfinder", include_bytes!("../../../assets/icons/dc-pathfinder.svg")), ("dc-perspective", include_bytes!("../../../assets/icons/dc-perspective.svg")), + ("dc-perspective-select", include_bytes!("../../../assets/icons/dc-perspective-select.svg")), ("dc-pf-crop", include_bytes!("../../../assets/icons/dc-pf-crop.svg")), ("dc-pf-divide", include_bytes!("../../../assets/icons/dc-pf-divide.svg")), ("dc-pf-exclude", include_bytes!("../../../assets/icons/dc-pf-exclude.svg")), @@ -169,7 +183,11 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-screen-mode", include_bytes!("../../../assets/icons/dc-screen-mode.svg")), ("dc-selection", include_bytes!("../../../assets/icons/dc-selection.svg")), ("dc-shape-builder", include_bytes!("../../../assets/icons/dc-shape-builder.svg")), + ("dc-shared-edge", include_bytes!("../../../assets/icons/dc-shared-edge.svg")), ("dc-shear", include_bytes!("../../../assets/icons/dc-shear.svg")), + ("dc-slice", include_bytes!("../../../assets/icons/dc-slice.svg")), + ("dc-slice-select", include_bytes!("../../../assets/icons/dc-slice-select.svg")), + ("dc-slide-anchor", include_bytes!("../../../assets/icons/dc-slide-anchor.svg")), ("dc-smooth", include_bytes!("../../../assets/icons/dc-smooth.svg")), ("dc-stroke", include_bytes!("../../../assets/icons/dc-stroke.svg")), ("dc-stroke-center", include_bytes!("../../../assets/icons/dc-stroke-center.svg")), @@ -177,7 +195,14 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-stroke-outside", include_bytes!("../../../assets/icons/dc-stroke-outside.svg")), ("dc-swap", include_bytes!("../../../assets/icons/dc-swap.svg")), ("dc-swatch-kinds", include_bytes!("../../../assets/icons/dc-swatch-kinds.svg")), + ("dc-symbol-screener", include_bytes!("../../../assets/icons/dc-symbol-screener.svg")), + ("dc-symbol-scruncher", include_bytes!("../../../assets/icons/dc-symbol-scruncher.svg")), + ("dc-symbol-shifter", include_bytes!("../../../assets/icons/dc-symbol-shifter.svg")), + ("dc-symbol-sizer", include_bytes!("../../../assets/icons/dc-symbol-sizer.svg")), + ("dc-symbol-spinner", include_bytes!("../../../assets/icons/dc-symbol-spinner.svg")), ("dc-symbol-sprayer", include_bytes!("../../../assets/icons/dc-symbol-sprayer.svg")), + ("dc-symbol-stainer", include_bytes!("../../../assets/icons/dc-symbol-stainer.svg")), + ("dc-symbol-styler", include_bytes!("../../../assets/icons/dc-symbol-styler.svg")), ("dc-touch-type", include_bytes!("../../../assets/icons/dc-touch-type.svg")), ("dc-transform-panel", include_bytes!("../../../assets/icons/dc-transform-panel.svg")), ("dc-transparency", include_bytes!("../../../assets/icons/dc-transparency.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index ef24ddb5e0..a5a2074c0d 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -23,7 +23,8 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-direct" => "dc-direct", "tool-group-select" => "dc-group-select", "tool-magic-wand" => "wand-sparkles", - "tool-lasso" => "lasso", + "tool-lasso" => "dc-lasso", + "tool-lasso-enclosing" => "dc-lasso-enclosing", "tool-pen" => "pen-tool", "tool-pen-add" => "pen-tool-add", "tool-pen-delete" => "pen-tool-delete", @@ -84,7 +85,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-fill-area" => "dc-fill-area", "tool-live-select" => "dc-live-select", "tool-perspective" => "dc-perspective", - "tool-perspective-select" => "dc-perspective", + "tool-perspective-select" => "dc-perspective-select", "tool-mesh" => "dc-mesh", "tool-gradient" => "dc-gradient", "tool-eyedropper" => "pipette", @@ -94,9 +95,25 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-blend" => "dc-blend", "tool-objects-on-path" => "dc-objects-on-path", "tool-symbol" => "dc-symbol-sprayer", - "tool-graph" => "chart-column", + "tool-symbol-shifter" => "dc-symbol-shifter", + "tool-symbol-scruncher" => "dc-symbol-scruncher", + "tool-symbol-sizer" => "dc-symbol-sizer", + "tool-symbol-spinner" => "dc-symbol-spinner", + "tool-symbol-stainer" => "dc-symbol-stainer", + "tool-symbol-screener" => "dc-symbol-screener", + "tool-symbol-styler" => "dc-symbol-styler", + "tool-graph" => "dc-graph-column", + "tool-graph-stacked-column" => "dc-graph-stacked-column", + "tool-graph-bar" => "dc-graph-bar", + "tool-graph-stacked-bar" => "dc-graph-stacked-bar", + "tool-graph-line" => "dc-graph-line", + "tool-graph-area" => "dc-graph-area", + "tool-graph-scatter" => "dc-graph-scatter", + "tool-graph-pie" => "dc-graph-pie", + "tool-graph-radar" => "dc-graph-radar", "tool-artboard" => "frame", - "tool-slice" => "slice", + "tool-slice" => "dc-slice", + "tool-slice-select" => "dc-slice-select", "tool-hand" => "hand", "tool-rotate-view" => "dc-rotate-view", "tool-print-tiling" => "printer", @@ -234,6 +251,20 @@ mod tests { } } + /// Every cataloged tool, the add-ons' included, maps to an existing icon that is not the + /// dashed placeholder and that no other tool uses. + #[test] + fn every_tool_has_an_icon_no_other_tool_uses() { + let mut users: std::collections::BTreeMap<&str, Vec<&str>> = std::collections::BTreeMap::new(); + for tool in vectorcraft_tools::catalog::all_tools() { + let name = tool_icon(tool.icon); + assert!(exists(name) && name != "square-dashed", "{} maps to {name}, which isn't an icon of its own", tool.id); + users.entry(name).or_default().push(tool.id); + } + let shared: Vec<_> = users.iter().filter(|(_, tools)| tools.len() > 1).collect(); + assert!(shared.is_empty(), "tools that share an icon: {shared:?}"); + } + #[test] fn shared_catalog_preserves_fallback_and_tool_aliases() { let ImageSource::Bytes { uri, bytes } = source("missing-icon") else { panic!("expected SVG bytes") }; From dcff4edc3d61ba43eb8d0c3c76b5eacab4c34bb8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:55:41 -0800 Subject: [PATCH 36/78] Selection: Cmd/Ctrl lends Direct Selection until it is released With the Selection tool chosen, holding Cmd (Ctrl on Windows and Linux) now lends Direct Selection, or Group Selection when that was chosen last, for each press; the Selection tool is back on the release. With Group Selection chosen, Cmd lends the Selection tool, as it already did with Direct Selection. Selection & Anchor Display > Command Click to Select Objects Behind keeps a Cmd press on a selected object, away from its anchors, handles, mesh points and spine, for selecting the object behind it. A wide stroke's painted area counts as on the object there. - The double-click or triple-click after Cmd-clicks goes to the tool the clicks went to. - Cmd pressed once a drag is under way lends nothing, and the pointer stays the active tool's. - While Cmd is held, the status bar's Current Tool and the help bar name the lent tool, and the canvas shows the lent tool's marks and widgets (blend, Shaper, mirror, trace divider and repeat handles) for the pointer's position in the same frame. - The help bar has hints for Group Selection. The helper that finds a selected object's editable parts under the pointer follows the one in pull request 6597 by SofiaAFigueredo. Docs: docs/ui-parity.md, docs/control-protocol.md (ui.pointer). Co-authored-by: SofiaAFigueredo <223278896+SofiaAFigueredo@users.noreply.github.com> --- crates/engine/src/lib.rs | 10 ++ crates/engine/src/session/documents.rs | 3 + crates/engine/src/tests/draw2.rs | 155 ++++++++++++++++++ crates/engine/src/tooling.rs | 107 ++++++++++-- crates/tools/src/direct.rs | 69 +++++++- crates/tools/src/direct/tests.rs | 27 +++ crates/tools/src/select.rs | 34 ++++ crates/ui-egui/src/canvas.rs | 34 ++-- crates/ui-egui/src/canvas/drag.rs | 8 +- crates/ui-egui/src/canvas/input.rs | 4 +- crates/ui-egui/src/canvas/overlays.rs | 42 +++-- .../src/canvas/selection_marks/tests.rs | 4 +- crates/ui-egui/src/canvas/tests.rs | 38 +++++ crates/ui-egui/src/canvas/tool_overlays.rs | 34 ++-- crates/ui-egui/src/chrome/hints.rs | 12 +- crates/ui-egui/src/chrome/status_bar.rs | 10 +- crates/ui-egui/src/chrome/tests.rs | 13 +- docs/control-protocol.md | 2 +- docs/ui-parity.md | 2 +- 19 files changed, 532 insertions(+), 76 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..e2e329dae1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -106,6 +106,16 @@ pub struct Session { /// The selection tool chosen last (Selection, Direct Selection or Group Selection): the one Cmd /// lends the other tools. None until one is chosen. pub(crate) last_selection_tool: Option<&'static str>, + /// Direct Selection or Group Selection, whichever was chosen last: the one Cmd lends the + /// Selection tool. None until one is chosen. + pub(crate) last_part_selection_tool: Option<&'static str>, + /// The selection tool Cmd lent the last press, which also takes the double-click or + /// triple-click that follows it. None when the press was not lent. + pub(crate) press_lent: Option<&'static str>, + /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] + /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none). None when it was last asked + /// without Cmd. + pub(crate) hover_lent: Option>, pub(crate) last_view: ViewInfo, /// The selection tools' measurements for the active document as it is: a pointer move or a /// cursor asked for again over an unchanged document and selection measures nothing again. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..7930095b6e 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -65,6 +65,9 @@ impl Session { selection_at_lend: None, lent_selection: None, last_selection_tool: None, + last_part_selection_tool: None, + press_lent: None, + hover_lent: None, last_view: ViewInfo::default(), preview_memo: Default::default(), depth: 0, diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 75d7d081d9..f53a55e1e4 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4698,6 +4698,161 @@ fn cmd_alt_lends_group_selection_while_direct_selection_is_active() { s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 80.0).with_mods(cmd_alt), v).unwrap(); } +#[test] +fn cmd_lends_the_selection_tool_direct_selection_or_group_selection_chosen_last() { + // Cmd held with the Selection tool: Direct Selection takes the press until the release, so a + // Cmd-click picks one path inside a group where a plain click picks the group. + let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() }); + let v = view(); + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.lent_tool_id(&none), None); + assert_eq!(s.lent_tool_id(&cmd), Some("directSelection")); + assert_eq!(s.shown_tool_id(&cmd), "directSelection"); + assert_eq!(s.shown_tool_id(&none), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(a) && !picked.contains(group), "the Cmd-click picks the path, not its group"); + s.execute("select.none", &json!({})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0), v).unwrap(); + assert!(s.active().unwrap().selection.contains(group), "a plain click picks the group"); + // Cmd pressed once a drag is under way lends nothing: the pointer and the named tool stay. + s.pointer(&PointerEvent::new(PointerKind::Down, 600.0, 500.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 650.0, 550.0), v).unwrap(); + assert_eq!(s.cursor(Point::new(650.0, 550.0), cmd, v), s.cursor(Point::new(650.0, 550.0), none, v)); + assert_eq!(s.shown_tool_id(&cmd), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 650.0, 550.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + // Group Selection lends the Selection tool, and once chosen, is what the Selection tool borrows. + s.select_tool("groupSelection", v).unwrap(); + assert_eq!(s.lent_tool_id(&cmd), Some("selection")); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.lent_tool_id(&cmd), Some("groupSelection")); + s.select_tool("directSelection", v).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.lent_tool_id(&cmd), Some("directSelection")); +} + +#[test] +fn a_cmd_double_click_goes_to_the_tool_the_clicks_went_to() { + // With the Selection tool, Cmd-clicks go to Direct Selection, and so does the double-click + // after them: it does not isolate the group as the Selection tool's double-click would. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap(); + } + assert_eq!(s.tool_id(), "selection"); + assert_eq!(s.doc().unwrap().isolation, None, "Direct Selection's double-click does not isolate the group"); + // With Group Selection chosen last, the second click selects the group, and the double-click + // still goes to Group Selection, as both clicks did. + s.select_tool("groupSelection", v).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap(); + } + assert_eq!(s.doc().unwrap().isolation, None, "Group Selection's double-click does not isolate the group"); + s.execute("select.none", &json!({})).unwrap(); + // A plain double-click is the Selection tool's: it isolates the group. + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0), v).unwrap(); + } + assert!(s.doc().unwrap().isolation.is_some()); +} + +#[test] +fn a_cmd_press_on_a_selected_object_keeps_select_behind() { + // Over a selected object, a Cmd-click with the Selection tool selects the object behind it; + // with Select Behind off, Direct Selection takes the press there too. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + // The canvas shows the marks of the tool a press at the pointer takes. + s.cursor(Point::new(200.0, 200.0), cmd, v); + assert_eq!(s.hover_tool_id(&cmd), "selection"); + s.cursor(Point::new(500.0, 500.0), cmd, v); + assert_eq!(s.hover_tool_id(&cmd), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); + // On a selected object's anchor, Direct Selection takes the press. + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 250.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 250.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.prefs.ctrl_click_selects_behind = false; + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); +} + +#[test] +fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() { + // Without Use Preview Bounds the bounding box leaves out the outer half of a wide stroke, which + // the Selection tool still hits: a Cmd press there selects the object behind. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + assert!(!s.prefs.use_preview_bounds); + let back = rect(&mut s, 50.0, 50.0, 300.0, 300.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.execute("stroke.set", &json!({"ids": [front.0], "weight": 40})).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + // 15 pt outside the path, on its stroke. + let at = Point::new(200.0, 135.0); + assert_eq!(s.hover_tool_at(Some(at), &cmd, v), "selection", "the press selects behind"); + s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); +} + +#[test] +fn the_marks_follow_this_frames_pointer_with_cmd_held() { + // The canvas asks which tool's marks to draw before it asks for the cursor: the answer is for + // the pointer where it is now, and with the pointer off the canvas, the tool Cmd lends. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.cursor(Point::new(200.0, 200.0), cmd, v); + assert_eq!(s.hover_tool_id(&cmd), "selection"); + assert_eq!(s.hover_tool_at(Some(Point::new(500.0, 500.0)), &cmd, v), "directSelection", "away from the selection"); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection", "over the selection"); + assert_eq!(s.hover_tool_at(None, &cmd, v), "directSelection", "off the canvas"); + assert_eq!(s.hover_tool_id(&cmd), "directSelection", "kept while the view moves"); + assert_eq!(s.hover_tool_at(None, &Mods::default(), v), "selection", "without Cmd"); +} + #[test] fn cmd_lends_the_selection_tool_and_its_bounding_box_to_direct_selection() { // #3901: with Direct Selection, Cmd held gives the Selection tool for the press: its cursor, diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 7c1af811ed..ba4f4089e4 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -204,6 +204,9 @@ impl Session { } if vectorcraft_tools::catalog::is_selection_tool(id) { self.last_selection_tool = Some(self.tool.id()); + if id != "selection" { + self.last_part_selection_tool = Some(self.tool.id()); + } self.select_whole_instance(id); } Ok(()) @@ -247,8 +250,10 @@ impl Session { /// selection tool from other tools (Alt on the lent Direct Selection gesture stays copy/subtract). /// Cmd alone lends Direct Selection the Selection tool, whose bounding box transforms the /// object (#3901; ). + /// Group Selection lends the Selection tool, and the Selection tool lends Direct Selection or + /// Group Selection, whichever was chosen last (Direct Selection until one is). /// Perspective Selection keeps Cmd+Alt drags to copy objects on their perspective plane. - /// None for the other selection tools and the view tools. + /// None for the view tools. fn lent_tool(&self, id: &str, mods: &Mods) -> Option<&'static str> { use vectorcraft_tools::catalog::{edits_anchors, is_selection_tool}; if matches!(id, "hand" | "zoom" | "rotateView") { @@ -257,6 +262,12 @@ impl Session { if id == "directSelection" && mods.cmd { return Some(if mods.alt { "groupSelection" } else { "selection" }); } + if id == "groupSelection" && mods.cmd { + return Some("selection"); + } + if id == "selection" && mods.cmd { + return Some(self.last_part_selection_tool.unwrap_or("directSelection")); + } if id == "perspectiveSelection" && mods.cmd && mods.alt { return None; } @@ -276,15 +287,80 @@ impl Session { self.lent_tool(self.tool.id(), mods) } - /// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the - /// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click, - /// not Select Behind). The tool lent to stays as it was, unaware, until the release. → the event - /// for the tool, and the warnings of a preview that keeping the typing applied. - fn lend_selection_tool(&mut self, ev: &PointerEvent) -> Result<(PointerEvent, Vec)> { - if ev.kind != PointerKind::Down || !ev.mods.cmd || self.lender.is_some() { + /// The tool the status bar and the help bar name with `mods` held: the selection tool Cmd + /// lends ([`Self::lent_tool_id`]) while the button is up, Space does not lend a view tool and + /// the active tool is not computing an edit, else the active tool. Over a selected object where + /// a Cmd press selects behind, it still names the tool Cmd lends elsewhere. + pub fn shown_tool_id(&self, mods: &Mods) -> &'static str { + match self.lent_tool_id(mods) { + Some(id) if !mods.space && !self.tool_editing() && !self.pointer_held => id, + _ => self.tool.id(), + } + } + + /// The tool whose marks the canvas shows with `mods` held: the selection tool a Cmd press at + /// the pointer would borrow, as [`Self::hover_tool_at`] or [`Self::cursor`] last found it + /// (before either has, the one [`Self::lent_tool_id`] names), else the active tool. The canvas + /// asks this while the view moves, when it does not hit-test the art under the pointer. + pub fn hover_tool_id(&self, mods: &Mods) -> &'static str { + let lent = self.hover_lent.unwrap_or_else(|| self.lent_tool_id(mods)); + match lent { + Some(id) if mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held => id, + _ => self.tool.id(), + } + } + + /// The tool whose marks and widgets the canvas draws this frame with `mods` held and the + /// pointer at `p` (None off the canvas): the selection tool a Cmd press there would borrow + /// ([`Self::lent_tool_at`]; off the canvas, the one [`Self::lent_tool_id`] names), else the + /// active tool. [`Self::hover_tool_id`] then answers the same until the pointer or the keys move. + pub fn hover_tool_at(&mut self, p: Option, mods: &Mods, view: ViewInfo) -> &'static str { + let lends = mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; + let lent = match p { + _ if !lends => None, + Some(p) => self.lent_tool_at(p, mods, view), + None => self.lent_tool_id(mods), + }; + self.hover_lent = lends.then_some(lent); + lent.unwrap_or(self.tool.id()) + } + + /// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when + /// the Selection tool keeps a Cmd press on a selected object to select the object behind it + /// (Selection & Anchor Display › Command Click to Select Objects Behind). + fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> { + let id = self.lent_tool(self.tool.id(), mods)?; + let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p)); + (!behind).then_some(id) + } + + /// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks + /// before the press, to tell a gesture of the tool in hand from one of a lent tool. + pub fn press_lends_tool(&mut self, ev: &PointerEvent, view: ViewInfo) -> bool { + ev.kind == PointerKind::Down && ev.mods.cmd && self.lender.is_none() && self.lent_tool_at(ev.pos, &ev.mods, view).is_some() + } + + /// A press with Cmd held (Ctrl elsewhere): the selection tool [`Self::lent_tool_at`] names + /// takes the gesture, pressing without Cmd (a plain click, not Select Behind). The tool lent to + /// stays as it was, unaware, until the release. With a selection tool active, the double-click + /// or triple-click that follows Cmd-clicks goes to the tool the clicks went to, with Cmd kept + /// (Cmd+Shift releases a guide), and that tool is given back after it. → the event for the tool, + /// and the warnings of a preview that keeping the typing applied. + fn lend_selection_tool(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result<(PointerEvent, Vec)> { + let follow_up = + matches!(ev.kind, PointerKind::DoubleClick | PointerKind::TripleClick) && vectorcraft_tools::catalog::is_selection_tool(self.tool.id()); + if ev.kind == PointerKind::Down { + self.press_lent = None; + } + if (ev.kind != PointerKind::Down && !follow_up) || !ev.mods.cmd || self.lender.is_some() { return Ok((*ev, vec![])); } - let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return Ok((*ev, vec![])) }; + // A follow-up goes where the press before it went, whatever that press selected. + let id = if follow_up { self.press_lent } else { self.lent_tool_at(ev.pos, &ev.mods, view) }; + let Some(id) = id else { return Ok((*ev, vec![])) }; + if !follow_up { + self.press_lent = Some(id); + } // Typing in progress is kept as its own step first: the lent tool's drag previews from the // document its interaction started from, which would drop the typing (#1881). When it // can't be kept, the press is not lent. @@ -312,7 +388,8 @@ impl Session { } self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); - Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled)) + let cmd = follow_up && ev.mods.cmd; + Ok((PointerEvent { mods: Mods { cmd, ..ev.mods }, ..*ev }, settled)) } /// The lent selection tool's gesture is over: the tool it was lent to is back as it was (the @@ -331,6 +408,9 @@ impl Session { let r = self.deactivate_tool(view); self.keep_tool_settings(); self.tool = lender; + // Back with the Selection or Group Selection tool, a symbol part the lent Direct + // Selection picked gives way to its instance, as choosing the tool does. + self.select_whole_instance(self.tool.id()); if let Some(points) = mesh_points { self.tool.set_option("meshPoints", &points); } @@ -754,7 +834,7 @@ impl Session { } self.leave_draw_inside(ev, view)?; self.tell_tool_history_moved(); - let (ev, settled) = self.lend_selection_tool(ev)?; + let (ev, settled) = self.lend_selection_tool(ev, view)?; let ev = &ev; let lent = self.lender.is_some(); let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); @@ -778,7 +858,7 @@ impl Session { PointerKind::Up => self.press_point = None, _ => {} } - if ev.kind == PointerKind::Up { + if ev.kind == PointerKind::Up || (lent && matches!(ev.kind, PointerKind::DoubleClick | PointerKind::TripleClick)) { self.give_back_tool(view)?; } r @@ -1321,7 +1401,10 @@ impl Session { /// press would borrow ([`Self::lend_selection_tool`]). pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor { // While an edit is computed, a Cmd press is held for the active tool, which shows it is busy. - let lent = if mods.cmd && self.lender.is_none() && !self.tool_editing() { self.lent_tool(self.tool.id(), &mods) } else { None }; + // Cmd pressed once a drag is under way lends nothing, so the tool keeps its pointer. + let lends = mods.cmd && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; + let lent = if lends { self.lent_tool_at(p, &mods, view) } else { None }; + self.hover_lent = lends.then_some(lent); let c = match lent { Some(id) => { let lent = self.make_tool(id); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index c889671a6e..7b224e0717 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -385,23 +385,26 @@ pub(crate) fn in_scope(doc: &vectorcraft_doc::Document, scope: Option, i /// shapes, its first child, are left out unless they are the isolated object (Construction mode), /// as clicks leave them out. fn walk_pickable<'a>(doc: &'a vectorcraft_doc::Document, scope: Option, mut f: impl FnMut(&'a Node)) { - fn walk<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { - f(n); - for c in n.children().into_iter().flatten().skip(usize::from(n.extras().shaper.is_some())) { - walk(c, f); - } - } if let Some(id) = scope && let Some(n) = doc.node(id) { - walk(n, &mut f); + walk_pickable_from(n, &mut f); } else if scope.is_none() { for l in &doc.layers { - walk(l, &mut f); + walk_pickable_from(l, &mut f); } } } +/// Visit `n` and the nodes inside it that Direct Selection may pick: a Shaper Group's original +/// shapes are left out ([`walk_pickable`]). +fn walk_pickable_from<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { + f(n); + for c in n.children().into_iter().flatten().skip(usize::from(n.extras().shaper.is_some())) { + walk_pickable_from(c, f); + } +} + /// The spines of the editable blends, topmost first: (blend, spine). pub(crate) fn spines(cx: &ToolContext) -> Vec<(NodeId, PathData)> { let mut v = vec![]; @@ -594,6 +597,56 @@ fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, us }) } +/// Is `p` on a part of a selected object that Direct Selection edits: a gradient mesh point, a +/// blend's spine point or segment, an anchor, the end of a direction handle or a segment, within +/// the selection tolerance? A selected group or compound path counts through the editable paths +/// inside it. +pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { + if cx.selection.objects.is_empty() { + return false; + } + let tol = cx.point_tol(); + let seg_tol = cx.pick_tol(); + if hit_handle(cx, p, tol).is_some() + || MeshEdit::default().hit(cx, &cx.selection.objects, p).is_some() + || selected_spines(cx).iter().any(|(_, path)| path.anchors().any(|(_, _, a)| a.p.distance(p) <= tol)) + || hit_spine_segment(cx, p, seg_tol).is_some() + { + return true; + } + // The editable paths' control bounds are listed once per document state and selection; a + // hover measures only the paths whose bounds it is near. + let boxes = crate::select::selected_part_boxes(cx, || { + let editable = cx.doc.editable(); + let mut v = vec![]; + for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) { + walk_pickable_from(root, &mut |n| { + if editable(n.id) + && let Some(b) = editable_path(n).and_then(|pd| pd.control_bounds()) + { + v.push((n.id, b)); + } + }); + } + v.into() + }); + let reach = tol.max(seg_tol); + boxes.iter().any(|&(id, b)| { + b.inflate(reach, reach).contains(p) + && cx.doc.node(id).and_then(editable_path).is_some_and(|pd| { + #[cfg(test)] + MEASURED_PARTS.set(MEASURED_PARTS.get() + 1); + nearest_anchor(&pd, p, tol, None).is_some() || pd.nearest(p).is_some_and(|(.., d)| d <= seg_tol) + }) + }) +} + +#[cfg(test)] +thread_local! { + /// How many paths [`over_selected_part`] has measured on this thread. + static MEASURED_PARTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Is `p` within a press's reach of an anchor of type on a path's path? The anchor wins over a /// bracket standing on it (the end bracket on the last anchor, #3980); the bracket's stem above it /// still drags the bracket. diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 4f3b795921..3cef62fab1 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2794,3 +2794,30 @@ fn a_marquee_skips_the_anchors_and_segments_of_guides_that_cannot_be_picked() { assert!(!crossed(&marquee(false, (140.0, 80.0), (160.0, 120.0))), "locked or hidden: no segment"); assert!(crossed(&marquee(true, (140.0, 80.0), (160.0, 120.0))), "shown and unlocked"); } + +/// A hover over a large selected group measures only the paths near the pointer when it asks +/// whether a Cmd press there lands on a part Direct Selection edits. +#[test] +fn over_selected_part_measures_only_the_paths_near_the_pointer() { + use vectorcraft_doc::{Appearance, Node}; + let mut d = vectorcraft_doc::Document::new(2000.0, 2000.0); + let l = d.layers[0].id; + let squares: Vec> = (0..400) + .map(|i| { + let (x, y) = (f64::from(i % 20) * 50.0, f64::from(i / 20) * 50.0); + let r = vectorcraft_geom::shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)); + std::sync::Arc::new(Node::path(d.alloc_id(), r, Appearance::default_art())) + }) + .collect(); + let g = d.alloc_id(); + d.insert(Some(l), 0, Node::group(g, squares)).unwrap(); + let p = paint(); + let mut picked = Selection::default(); + picked.add(g); + let c = cx(&d, &picked, &p); + let before = MEASURED_PARTS.get(); + assert!(over_selected_part(&c, Point::new(520.0, 520.0)), "on a square's corner"); + assert!(!over_selected_part(&c, Point::new(535.0, 535.0)), "between the squares"); + let measured = MEASURED_PARTS.get() - before; + assert!(measured < 10, "{measured} of 400 paths measured"); +} diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index eee6600591..458ac68232 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -518,6 +518,10 @@ struct Measured { bounds: Option>, oriented: Option>, by_object: HashMap>>, + /// [`painted_bounds`]. + painted: Option>, + /// [`selected_part_boxes`]. + part_boxes: Option>, } impl Measured { @@ -549,6 +553,8 @@ impl PreviewMemo { bounds: None, oriented: None, by_object: HashMap::new(), + painted: None, + part_boxes: None, }; if !st.entry.as_ref().is_some_and(|m| m.is_for(cx)) { st.entry = Some(fresh()); @@ -594,6 +600,19 @@ pub fn selection_box(cx: &ToolContext) -> Option { remembered(cx, |m| &mut m.oriented, || vectorcraft_effects::preview::oriented_bounds_with(cx.doc, &cx.selection.objects, cx.bounds_measure())) } +/// The selection's visual bounds as drawn, its strokes and effects included, whatever Use Preview +/// Bounds says: every point where a hit test finds a selected object is inside them. +fn painted_bounds(cx: &ToolContext) -> Option { + remembered(cx, |m| &mut m.painted, || vectorcraft_effects::preview::bounds_of(cx.doc, &cx.selection.objects, true)) +} + +/// `measure`'s list of the selected objects' editable paths with their control bounds, kept in the +/// session's [`PreviewMemo`] while the document and the selection stay as they are +/// ([`crate::direct::over_selected_part`]). +pub(crate) fn selected_part_boxes(cx: &ToolContext, measure: impl FnOnce() -> std::sync::Arc<[(NodeId, Rect)]>) -> std::sync::Arc<[(NodeId, Rect)]> { + remembered(cx, |m| &mut m.part_boxes, measure) +} + /// [`selection_box`] while the canvas shows it (View › Show Bounding Box, and no anchors selected /// on their own): its handles take a press only then. A path the Pen is drawing keeps its end /// anchor selected, so Cmd/Ctrl lending the Selection tool doesn't scale it by hidden handles (#4980). @@ -1499,6 +1518,21 @@ impl Tool for SelectionTool { } } +/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and a +/// selected object under the pointer, away from the anchors, handles and segments Direct +/// Selection edits ([`crate::direct::over_selected_part`])? Elsewhere Cmd lends the press to +/// Direct Selection or Group Selection. +pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { + let tol = cx.pick_tol(); + // The selection's painted bounds come first: away from them, no document walk is needed. They + // take in a wide stroke's outer half, which the bounding box leaves out without Use Preview + // Bounds. + cx.select_behind + && painted_bounds(cx).is_some_and(|b| b.inflate(tol, tol).contains(p)) + && objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation).iter().any(|id| cx.selection.contains(*id)) + && !crate::direct::over_selected_part(cx, p) +} + /// Select Behind: of the objects under `p` (topmost first), the one below the lowest selected /// one, back to the topmost after the bottom one; the topmost when none is selected. fn object_behind(cx: &ToolContext, p: Point) -> Option { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b366665d4..cd375d0952 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -43,7 +43,7 @@ pub use cursor::{HOVER_STILL_SECS, STILL_SECS, ViewKey}; use cursor::{cursor_icon, hover_cursor, hover_wait, still_wait}; use drag::drag_id; pub use drag::{apply_requests, dispatch, mods}; -pub(crate) use drag::{art_out, end_art_move, end_document_drag, pose_on_page, release_art_in_window, release_over_panel}; +pub(crate) use drag::{art_out, end_art_move, end_document_drag, held_mods, pose_on_page, release_art_in_window, release_over_panel}; #[cfg(test)] use drag::{frame_moves, tool_drag_doc_id, tool_drag_moved, tool_frame_moves, tool_press_doc_id}; pub use fill::Fill; @@ -413,6 +413,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // 600% zoom, a line at every document pixel over the art, so the pixels it rasterizes to show. let revolve_edit = app.ui.dialog.as_ref().is_some_and(crate::dialogs::revolve_gizmo::active); let view_info = app.view_info(); + let shown_tool = marks_tool(app, ui.ctx(), hover_still, view_info); if !presenting { if app.ui.view.pixel_preview && v.zoom >= PIXEL_GRID_ZOOM && app.session.prefs.show_pixel_grid { grid(&painter, &xf, 1.0, 1, LineLook { color: PIXEL_GRID, dots: false }); @@ -431,7 +432,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } original_path_overlay(app, &painter, &xf); - let overlays = selection_visuals(app, &painter, &xf, (hidden_chars, selection_marks, hover_still), revolve_edit, view_info); + let overlays = selection_visuals(app, &painter, &xf, (hidden_chars, selection_marks, hover_still), revolve_edit, (view_info, shown_tool)); draw_overlays(&painter, &xf, &overlays, &t, HandleLook::of(&app.session.prefs), &mut shared_paths); app.canvas.shared_paths = shared_paths; crate::panels::tabs::paint_stop_guide(app, &painter, &xf); @@ -441,7 +442,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let quiet = space || ui.data(|d| d.get_temp::(drag_id())).is_some(); overlay_hover_text(ui, &xf, &overlays, quiet, |p| artboards::artboard_name_at(app, ui, &xf, p).is_some()); if !revolve_edit { - shaper_widget_overlay(app, &painter, &xf); + shaper_widget_overlay(app, &painter, &xf, shown_tool); crate::panels::three_d::paint_graphic_handles(app, &painter, &xf); } } @@ -1647,14 +1648,23 @@ pub(super) fn guide_labels(doc: &vectorcraft_doc::Document) -> std::collections: .collect() } -/// The selection's visuals and the tools' overlays, to be drawn. +/// The tool whose marks and widgets the canvas draws this frame: while Cmd is held, the selection +/// tool a press at the pointer borrows. While the view moves (`hover_still` false), the art under +/// the pointer is not hit-tested again (#2452), and the last answer stays. +fn marks_tool(app: &mut VectorcraftApp, ctx: &egui::Context, hover_still: bool, view: vectorcraft_engine::ViewInfo) -> &'static str { + let held = held_mods(app, ctx); + if hover_still { app.session.hover_tool_at(app.hover_doc, &held, view) } else { app.session.hover_tool_id(&held) } +} + +/// The selection's visuals and the tools' overlays, to be drawn. `tool` is the tool whose marks +/// and widgets show ([`vectorcraft_engine::Session::hover_tool_at`]). fn selection_visuals( app: &mut VectorcraftApp, painter: &egui::Painter, xf: &Xf, (hidden_chars, mut marks, hover_still): (HiddenChars, SelectionMarks, bool), revolve_edit: bool, - view_info: vectorcraft_engine::ViewInfo, + (view_info, tool): (vectorcraft_engine::ViewInfo, &str), ) -> Vec { // View → Hide Gradient Annotator hides the Gradient tool's annotator. let mut overlays = if !revolve_edit && (app.session.tool_id() != "gradient" || app.ui.view.gradient_annotator) { @@ -1670,15 +1680,15 @@ fn selection_visuals( overlays.extend(crate::dialogs::live_paint_gaps::overlays(app)); if app.ui.view.edges && !revolve_edit { if hover_still { - hover_highlight(app, painter, xf); + hover_highlight(app, painter, xf, tool); } - selection_overlay(app, painter, xf, overlays.iter().any(|o| matches!(o, Overlay::CurvePoint { .. })), &mut marks); + selection_overlay(app, painter, xf, (tool, overlays.iter().any(|o| matches!(o, Overlay::CurvePoint { .. }))), &mut marks); app.canvas.selection_marks = marks; draw_inside_overlay(app, painter, xf); - mirror_axis_overlay(app, painter, xf); - grid_repeat_overlay(app, painter, xf); - radial_repeat_overlay(app, painter, xf); - trace_split_overlay(app, painter, xf); + mirror_axis_overlay(app, painter, xf, tool); + grid_repeat_overlay(app, painter, xf, tool); + radial_repeat_overlay(app, painter, xf, tool); + trace_split_overlay(app, painter, xf, tool); if app.ui.view.text_threads { // Under the tools' overlays: a selected frame's own ports are drawn over its thread's. let mut threads = thread_overlays(app, xf.zoom); @@ -1694,7 +1704,7 @@ fn selection_visuals( } } if !revolve_edit { - blend_widgets_overlay(app, painter, xf); + blend_widgets_overlay(app, painter, xf, tool); } // Edit › Spelling › Auto Spell Check: shown with the edges hidden too, as it marks the type // rather than the selection. diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 512df6e9a9..953bb29b51 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -272,6 +272,12 @@ pub fn mods(m: egui::Modifiers, space: bool) -> Mods { Mods { shift: m.shift, alt: m.alt, cmd: m.command, ctrl: m.ctrl, space } } +/// The keys held now, with `space` set while Space lends a view tool ([`space_lends_view_tools`]). +pub(crate) fn held_mods(app: &VectorcraftApp, ctx: &egui::Context) -> Mods { + let (m, space) = ctx.input(|i| (i.modifiers, i.key_down(egui::Key::Space))); + mods(m, space_lends_view_tools(app, m, space)) +} + /// Whether Space, held with the modifiers `m`, lends the Hand, Rotate View or Zoom tool. While the /// Type tool edits text, Space types a space, and only Cmd+Space still lends the Zoom tool. pub(super) fn space_lends_view_tools(app: &VectorcraftApp, m: egui::Modifiers, space: bool) -> bool { @@ -384,7 +390,7 @@ pub fn dispatch(app: &mut VectorcraftApp, ev: &PointerEvent, view: vectorcraft_e return; } // A press lent to a selection tool (Cmd/Ctrl held) does not use the tool of a held key. - if ev.kind == PointerKind::Down && app.session.lent_tool_id(&ev.mods).is_none() { + if ev.kind == PointerKind::Down && !app.session.press_lends_tool(ev, view) { crate::shortcuts::note_tool_use(app); } let r = app.session.pointer(ev, view); diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index a6a0509de5..eebc036716 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -709,8 +709,10 @@ fn double_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { // the type was clicked, so typing edits it at once. if before != "type" && app.session.tool_id() == "type" { app.session.set_tool_option("prevTool", &json!(before)); + // Without Cmd, so the Type tool takes the click instead of lending a selection tool. + let mods = Mods { cmd: false, ..ev.mods }; for kind in [PointerKind::Down, PointerKind::Up] { - dispatch(app, &PointerEvent { kind, ..ev }, view); + dispatch(app, &PointerEvent { kind, mods, ..ev }, view); } } } diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b4d2d44aac..02318ad688 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -10,18 +10,19 @@ use super::outline::{KEY_OUTLINE, c32, node_outline, selection_hit_at, stroke_pa use super::selection_marks::{MarkOptions, SelectionMarks}; use super::{BezPath, Color32, CornerRadius, NodeKind, Overlay, Pos2, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, vec2}; -pub(super) fn hover_highlight(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { +/// Object Highlighting for `tool`, the tool whose marks the canvas shows. +pub(super) fn hover_highlight(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { let Some(h) = app.hover_doc else { return }; // Smart Guides › Object Highlighting: a Smart Guides display option, so it needs them on and Snap to Grid and Pixel Preview off. if !app.ui.view.smart_guides || !app.session.prefs.object_highlighting || app.ui.view.snap_to_grid || app.ui.view.pixel_preview { return; } - if app.session.tool_busy() || !matches!(app.session.tool_id(), "selection" | "directSelection" | "groupSelection") { + if app.session.tool_busy() || !matches!(tool, "selection" | "directSelection" | "groupSelection") { return; } let Some(st) = app.session.active() else { return }; let Some(hit) = selection_hit_at(app, h, xf.zoom) else { return }; - let id = if app.session.tool_id() == "selection" { hit.top_object(st.isolation) } else { hit.leaf }; + let id = if tool == "selection" { hit.top_object(st.isolation) } else { hit.leaf }; if st.selection.contains(id) { return; } @@ -105,9 +106,8 @@ pub(super) fn curve_point(p: &egui::Painter, c: Pos2, color: Color32, filled: bo p.circle(c, size / 2.0, if filled { color } else { Color32::WHITE }, Stroke::new(1.0, color)); } -/// How the current tool and preferences draw the selection's marks. -pub(super) fn mark_options(app: &VectorcraftApp, curve_points_from_tool: bool) -> MarkOptions<'_> { - let tool = app.session.tool_id(); +/// How `tool` and the preferences draw the selection's marks. +pub(super) fn mark_options<'a>(app: &'a VectorcraftApp, tool: &str, curve_points_from_tool: bool) -> MarkOptions<'a> { MarkOptions { direct: vectorcraft_tools::catalog::edits_anchors(tool), curvature: tool == "curvature", @@ -118,7 +118,15 @@ pub(super) fn mark_options(app: &VectorcraftApp, curve_points_from_tool: bool) - } /// Draw selection marks and widgets, keeping the box but hiding dot marks during Halftone Preview. -pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf, curve_points_from_tool: bool, marks: &mut SelectionMarks) { +/// `shown` is the tool whose marks show: while Cmd is held, the selection tool a press at the +/// pointer borrows ([`vectorcraft_engine::Session::hover_tool_at`]). +pub(super) fn selection_overlay( + app: &mut VectorcraftApp, + p: &egui::Painter, + xf: &Xf, + (shown, curve_points_from_tool): (&str, bool), + marks: &mut SelectionMarks, +) { // The Selection tool's bounding box (rotated with the objects after a rotation), also shown by // the shape tools that keep a shape just drawn ready to adjust while they draw none (#5477). It // hides while a drag moves, rotates or resizes the selection, so only the art is seen going with @@ -134,11 +142,11 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: let shape_tool = vectorcraft_tools::shape::shows_shape_widgets(app.session.tool_id()); // A shape tool drawing a shape shows none of its widgets; adjusting a widget, it shows the widgets. let drawing = shape_tool && app.session.tool_busy() && !app.session.tool_transforming(); - // Cmd held lends the Selection tool to a press (Direct Selection's included, #3901): its box - // shows while the key is down, where its handles take that press. - let held = super::drag::mods(p.ctx().input(|i| i.modifiers), false); - let lends_selection = !app.session.tool_busy() && app.session.lent_tool_id(&held) == Some("selection"); - let show_box = (app.session.tool_id() == "selection" || lends_selection || (shape_tool && (!app.session.tool_busy() || follows))) + // Cmd held lends a selection tool to a press (Direct Selection's included, #3901): while the + // key is down, the marks are the lent tool's, so the Selection tool's box shows only when it is + // the Selection tool whose handles take that press. + let own = shown == app.session.tool_id(); + let show_box = (shown == "selection" || (shape_tool && own && (!app.session.tool_busy() || follows))) && (follows || !app.session.tool_transforming()) && app.ui.view.bounding_box; let selected_whole = app.session.active().is_some_and(|st| !st.selection.is_empty() && st.selection.anchors.is_empty()); @@ -166,11 +174,11 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: let app = &*app; let Some(st) = app.session.active() else { return }; let symbols = st.doc.symbol_boxes(); - let tool = app.session.tool_id(); + let tool = shown; let direct = vectorcraft_tools::catalog::edits_anchors(tool); // Selection & Anchor Display › Size (1–7, 3 the default): anchors, handles and the bounding // box's handles a point bigger or smaller per step. - let options = mark_options(app, curve_points_from_tool); + let options = mark_options(app, tool, curve_points_from_tool); let grow = options.look.grow; let anchor = |direct: bool| grow + if direct { 5.0 } else { 4.0 }; // The temporary halftone selects its dots; their marks obscure the art (#6369). @@ -286,10 +294,10 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: /// by a line to the spine's halfway point: the Appearance widget hollow above it, the Easing widget /// filled below it. For a blend without a spine the line goes to the halfway point of the straight /// lines between its key centers, which are not drawn. Drawn with the edges hidden too, as they are -/// controls. -pub(super) fn blend_widgets_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { +/// controls. `tool` is the tool whose widgets the canvas shows. +pub(super) fn blend_widgets_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { use vectorcraft_tools::blendwidget::{BlendControl, BlendWidget, RADIUS_PX}; - if !matches!(app.session.tool_id(), "selection" | "blend") { + if !matches!(tool, "selection" | "blend") { return; } let Some(st) = app.session.active() else { return }; diff --git a/crates/ui-egui/src/canvas/selection_marks/tests.rs b/crates/ui-egui/src/canvas/selection_marks/tests.rs index 98ef0fdfbc..73dacfd8f0 100644 --- a/crates/ui-egui/src/canvas/selection_marks/tests.rs +++ b/crates/ui-egui/src/canvas/selection_marks/tests.rs @@ -42,7 +42,7 @@ const VIEW: (f64, f64) = (200.0, 150.0); /// The marks drawn one shape at a time, as a frame draws them with nothing kept. fn plain(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, curve_points_from_tool: bool) { let st = app.session.active().unwrap(); - let MarkOptions { direct, curvature, look, all_handles, .. } = mark_options(app, curve_points_from_tool); + let MarkOptions { direct, curvature, look, all_handles, .. } = mark_options(app, app.session.tool_id(), curve_points_from_tool); let symbols = st.doc.symbol_boxes(); let anchor = |direct: bool| look.grow + if direct { 5.0 } else { 4.0 }; let (mut handles, mut with_handles) = (vec![], 0); @@ -264,7 +264,7 @@ fn assert_same(a: &Picture, b: &Picture, what: &str, allowed_per_mille: usize) { fn paint(marks: &mut SelectionMarks, app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, curve_points_from_tool: bool) { let st = app.session.active().unwrap(); let key = st.selection.key; - marks.paint(st, p, xf, &mark_options(app, curve_points_from_tool), key, &st.selection.objects); + marks.paint(st, p, xf, &mark_options(app, app.session.tool_id(), curve_points_from_tool), key, &st.selection.objects); } /// Kept marks, marks built from nothing and plain shapes all draw the same pixels. Kept marks may diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..508ccb03a0 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -7121,6 +7121,44 @@ fn hidden_shape_widgets_leave_the_bounding_box() { assert_eq!(app.session.cursor(at, Mods::default(), view), Cursor::CornerRadius); } +/// With the Selection tool, Cmd held lends Direct Selection away from the selection, and a selected +/// blend's widgets, which only the Selection and Blend tools press, hide while the key is down. +#[test] +fn blend_widgets_hide_while_cmd_lends_direct_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let a = id(app.session.execute("shape.rectangle", &json!({"x": 90, "y": 190, "width": 20, "height": 20})).unwrap()); + let b = id(app.session.execute("shape.rectangle", &json!({"x": 290, "y": 190, "width": 20, "height": 20})).unwrap()); + app.session.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let blend = id(app.session.execute("object.blend.make", &json!({})).unwrap()); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [blend]})).unwrap(); + let ctx = egui::Context::default(); + let widgets = |app: &mut VectorcraftApp, modifiers: egui::Modifiers| { + app.canvas.selection_marks = Default::default(); + let events = vec![egui::Event::ModifiersChanged(modifiers)]; + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let r = vectorcraft_tools::blendwidget::RADIUS_PX; + let mut n = 0; + let mut count = |s: &Shape| n += usize::from(matches!(s, Shape::Circle(c) if c.radius == r)); + for c in &out.shapes { + match &c.shape { + Shape::Vec(v) => v.iter().for_each(&mut count), + s => count(s), + } + } + n + }; + let plain = widgets(&mut app, egui::Modifiers::NONE); + assert!(plain >= 2, "the Appearance and Easing widgets: {plain}"); + let held = widgets(&mut app, egui::Modifiers::COMMAND); + assert!(held + 2 <= plain, "hidden while Cmd lends Direct Selection: {held} of {plain}"); + assert_eq!(widgets(&mut app, egui::Modifiers::NONE), plain, "back when the key is let go"); +} + /// A selected Objects on Path group shows its Rotate All widget with the Selection and Objects on /// Path tools. #[test] diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index 958872d6b0..c6d3855403 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -619,10 +619,11 @@ pub(super) fn print_tiling_overlay(app: &mut VectorcraftApp, p: &egui::Painter, const PRINT_TILING: Color32 = Color32::from_gray(96); /// A Shaper Group's mode widget (Shaper and Selection tools), drawn with selection edges shown or -/// hidden: an arrow pointing right in Face Selection mode and left in Construction mode. -pub(super) fn shaper_widget_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { +/// hidden: an arrow pointing right in Face Selection mode and left in Construction mode. `tool` is +/// the tool whose widgets the canvas shows. +pub(super) fn shaper_widget_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { let Some(st) = app.session.active() else { return }; - if matches!(app.session.tool_id(), "shaper" | "selection") + if matches!(tool, "shaper" | "selection") && let Some(w) = vectorcraft_tools::shaperwidget::ShaperWidget::of(&st.doc, &st.selection, st.isolation, xf.zoom) { let (c, r) = (xf.to_screen(w.at), vectorcraft_tools::shaperwidget::RADIUS_PX); @@ -635,9 +636,10 @@ pub(super) fn shaper_widget_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: } } -/// High-contrast live controls, using the same geometry as the Selection tool's hit testing. -pub(super) fn mirror_axis_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { - if app.session.tool_id() != "selection" || !app.ui.view.bounding_box { +/// High-contrast live controls, using the same geometry as the Selection tool's hit testing, while +/// `tool`, the tool whose widgets the canvas shows, is the Selection tool. +pub(super) fn mirror_axis_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { + if tool != "selection" || !app.ui.view.bounding_box { return; } let Some(st) = app.session.active() else { return }; @@ -664,9 +666,9 @@ pub(super) fn mirror_axis_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: & /// The Split view's divider of the selected Image Trace object, where the Selection tool's hit /// testing finds it: a line across the source image with a grip in its middle, at its place in the /// zoomed, scrolled or turned view. Hidden with the bounding box and in Outline mode, as the hit -/// testing is. -pub(super) fn trace_split_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { - if app.session.tool_id() != "selection" || !app.ui.view.bounding_box || app.outline_view() { +/// testing is. Drawn while `tool`, the tool whose widgets the canvas shows, is the Selection tool. +pub(super) fn trace_split_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { + if tool != "selection" || !app.ui.view.bounding_box || app.outline_view() { return; } let Some(st) = app.session.active() else { return }; @@ -691,10 +693,11 @@ pub(super) fn trace_split_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: & } /// A selected grid repeat's row, column and corner handles and its spacing sliders (#2691), at -/// the places the Selection tool's hit testing finds them. -pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { +/// the places the Selection tool's hit testing finds them, while `tool`, the tool whose widgets the +/// canvas shows, is the Selection tool. +pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { use vectorcraft_tools::repeat_grid::{GridHandles, GridPart, HANDLE_RADIUS, SLIDER_HALF}; - if app.session.tool_id() != "selection" || !app.ui.view.bounding_box { + if tool != "selection" || !app.ui.view.bounding_box { return; } let frame = app.selection_box(); @@ -722,10 +725,11 @@ pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, x /// A selected radial repeat's circle with its radius handle and its splitter on it, and its /// instances handle below it, at the places the Selection tool's hit testing finds them. The -/// splitter also has a short line across the circle. -pub(super) fn radial_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { +/// splitter also has a short line across the circle. Drawn while `tool`, the tool whose widgets +/// the canvas shows, is the Selection tool. +pub(super) fn radial_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { use vectorcraft_tools::repeat_radial::{HANDLE_RADIUS, RadialHandles, RadialPart}; - if app.session.tool_id() != "selection" || !app.ui.view.bounding_box { + if tool != "selection" || !app.ui.view.bounding_box { return; } let frame = app.selection_box(); diff --git a/crates/ui-egui/src/chrome/hints.rs b/crates/ui-egui/src/chrome/hints.rs index 2c679c72a1..99dc7fdc25 100644 --- a/crates/ui-egui/src/chrome/hints.rs +++ b/crates/ui-egui/src/chrome/hints.rs @@ -27,6 +27,14 @@ fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> { ("Shift+Click", true), (" to add", false), ], + "groupSelection" => &[ + ("Click", true), + (" an object in a group to select it | ", false), + ("Click again", true), + (" to add the group it is in | ", false), + ("Shift+Click", true), + (" to add", false), + ], "pen" => &[ ("Click", true), (" to add a corner point | ", false), @@ -252,7 +260,9 @@ pub fn hint_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let segments = if let Some(d) = app.ui.dialog.as_ref().filter(|d| crate::dialogs::revolve_gizmo::active(d)) { vec![(crate::dialogs::revolve_gizmo::hint(d).into(), false)] } else { - let tool = app.session.tool_id(); + // While Cmd is held, the hints of the selection tool it lends. + let held = crate::canvas::held_mods(app, ui.ctx()); + let tool = app.session.shown_tool_id(&held); let hint = if tool == "zoom" && crate::canvas::animated_zoom(&app.session.prefs) { ANIMATED_ZOOM_HINT } else { tool }; hint_segments(hint) }; diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 126cc956f3..3f42999f87 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -73,7 +73,8 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { app.status(e); } ui.separator(); - let (info, next) = info_text(app); + let held = crate::canvas::held_mods(app, ui.ctx()); + let (info, next) = info_text(app, &held); if let Some(secs) = next { ui.ctx().request_repaint_after(std::time::Duration::from_secs(secs)); } @@ -183,12 +184,13 @@ pub fn set_status_bar_show(app: &mut VectorcraftApp, p: &serde_json::Value) -> R } /// The info field's text for the choice in the Show menu, and for Date and Time the seconds until -/// the minute it shows ends (when the bar draws again). -pub(super) fn info_text(app: &VectorcraftApp) -> (String, Option) { +/// the minute it shows ends (when the bar draws again). Current Tool names the selection tool Cmd +/// lends while it is held (`held`). +pub(super) fn info_text(app: &VectorcraftApp, held: &vectorcraft_tools::Mods) -> (String, Option) { let st = app.session.active(); match app.ui.status_bar_show { StatusBarShow::CurrentTool => { - let tool = vectorcraft_tools::tool_info(app.session.tool_id()) + let tool = vectorcraft_tools::tool_info(app.session.shown_tool_id(held)) .map(|t| { // The catalog keys carry the full label ("Selection Tool"); only English drops the suffix. let shown = tl!(t.label); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..dd83a691b6 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1099,6 +1099,17 @@ fn text_center(texts: &[StatusText], text: &str) -> egui::Pos2 { at.clip.intersect(at.bounds).center() } +/// While Cmd/Ctrl is held, Current Tool names the selection tool a press would borrow: Direct +/// Selection with the Selection tool chosen, and the Selection tool again once the key is let go. +#[test] +fn current_tool_names_the_selection_tool_cmd_lends() { + let (app, _ctx) = status_readout_app(); + let cmd = vectorcraft_tools::Mods { cmd: true, ..Default::default() }; + assert_eq!(app.session.tool_id(), "selection"); + assert_eq!(super::status_bar::info_text(&app, &cmd).0, "Direct Selection"); + assert_eq!(super::status_bar::info_text(&app, &Default::default()).0, "Selection"); +} + /// The status bar's info field shows the readout `view.statusBarShow` chooses: the navigator's /// artboard name, the tool in use, the date and time, the undo and redo counts, or the document's /// color profile. @@ -1130,7 +1141,7 @@ fn the_status_bar_info_field_shows_the_chosen_readout() { // The labels take the UI language's colon (#7991). let fr = crate::i18n::Lang::from_code("fr").unwrap(); crate::i18n::set_current(fr); - let (french, _) = super::status_bar::info_text(&app); + let (french, _) = super::status_bar::info_text(&app, &Default::default()); crate::i18n::set_current(crate::i18n::Lang::EN); assert_eq!(french, format!("{}\u{a0}: {before} {}\u{a0}: 1", crate::i18n::tr(fr, "Undos"), crate::i18n::tr(fr, "Redos"))); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dafab93a58..58c13dbe9b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -96,7 +96,7 @@ the two can still win that race. | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | | `ui.tool.select` / `ui.tool.list` | `{tool}` | | -| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is), and the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | +| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is); with Direct Selection or Group Selection it drags with the Selection tool, and with the Selection tool it drags with Direct Selection or Group Selection, whichever was chosen last, except on a selected object away from its anchors, handles and segments while `ctrlClickSelectsBehind` is on, where the press selects the object behind; the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | | `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | synthetic keyboard input | | `ui.move` | `{x, y}` | screen-point pointer move | | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..f9f140fc76 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -366,7 +366,7 @@ tools, never checked side by side) isn't captured row by row. | Space: Hand; Cmd+Space / Cmd+Alt+Space: zoom in/out; middle button pans | done | Space pressed after a tool takes a drag keeps the view still and shows that tool's cursor. Shape and anchor tools may use Space to move the geometry being drawn. Cmd+Space pressed mid-drag likewise keeps the active tool cursor. Space held before a press starts a view gesture, and its view cursor returns after release. `space_during_a_pencil_drag_keeps_the_pencil_cursor`, `cmd_space_mid_tool_drag_keeps_the_active_tool_cursor` | | Document window scroll bars along the right and bottom edges (Normal and Full Screen Mode with Menu Bar; none in Full Screen and Presentation Mode): a thumb as long as the view against the art and the artboards; dragging it scrolls, a click on the track pages, the wheel over a bar scrolls along it; in a rotated view they follow the screen's axes | partial | #2322. The span is the art and the artboards with half a window around them, not Illustrator's 227 in canvas: VectorCraft has no bounded drawing area (#2284). A track click pages rather than jumping to the click; the page size and the rotated-view behaviour are our own choice (the public documentation gives neither) | | A tool drag held near an edge of the canvas scrolls the view (#8551): zoomed in, a selection moved, a shape drawn or a marquee dragged towards the panels goes on past what shows | partial | Within 24 points of the canvas edge, once the pointer has moved 3 points from the press, the view scrolls away from that edge, faster nearer it (up to 900 points a second at the edge, and no faster in a corner, where it scrolls both ways), and keeps scrolling while the pointer stays still; the tool gets the pointer's new place in the document, so moved art stays under the pointer. Back away from the edge it stops. A click near the edge, the Hand, Zoom and Rotate View drags and Space panning do not scroll. The pointer past the canvas edge does not scroll: over a panel the Selection tools hand the art to the panels (#2826). The zone and speeds are VectorCraft's own (the public documentation gives none). Tests: `canvas::tests_edge_scroll` | -| Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); engine pointer and canvas regressions | +| Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); Cmd lends Group Selection the Selection tool, and the Selection tool Direct Selection or Group Selection, whichever was chosen last, except that a Cmd press on a selected object, away from its anchors, handles and segments, still selects the object behind it while Command Click to Select Objects Behind is on; Cmd pressed once a drag is under way lends nothing; while Cmd is held, the status bar's Current Tool and the help bar name the tool it lends ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Work with selections"); engine pointer and canvas regressions | | Eyedropper copies effective character dimensions between transformed text objects | done | Point/area and grouped text, highlighted ranges, reverse/remembered sampling, opt-outs and atomic invalid-transform rejection; `scaled_type_pick_*` (#6404) | | Eyedropper styles highlighted characters only and preserves ranges across Type switches | done | Font/paint, Shift color-only, Unicode, Undo/Redo and stale-range regression tests; enabled non-neutral source or target object transparency is refused atomically; disable Transparency to sample supported attributes | | Gradient mesh: a solid color dropped from the Color or Swatches panel or a Fill proxy on a selected mesh recolors the mesh point under the pointer, else the patch's four points; with the mesh selected, an Eyedropper click applies the fill color the same way | done | [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); `object.mesh.setPointColor`, one undo step, none when the color is unchanged. The 5-pixel reach for a point is VectorCraft's own. Tests `a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it`, `a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color`, `a_click_on_an_object_over_a_selected_mesh_copies_that_object` | From 555b6192283c61fd23e2a9e3faad39c3ddf286ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:34:20 -0800 Subject: [PATCH 37/78] Selection: Cmd Select Behind works on grouped art and line art A Cmd press with the Selection tool now selects behind on a group that holds a selected member, as it does on a selected object, so repeated Cmd-clicks on grouped art reach the object behind the group. A path's segments no longer keep the press for Direct Selection, so a Cmd-click on a selected stroke-only path selects behind it. Select Behind needs another object under the pointer: on a lone object the press is lent. The bounding box's handles and rotate zones also lend the press. - A double-click that follows a Cmd-click selecting behind keeps what that click selected, without isolating or editing, also when the press and the double-click come in one frame. After an edit or a selection change, or after a press that drags or is released away from where it began, it is an ordinary double-click. - Whether a press selects behind is kept for the pointer's position while the document, the selection, the live inputs and the hit-test settings stay as they are, so the cursor, the canvas marks and the press do not walk the document again. A layer or group effect that draws art widens the area checked; raster effects and color adjustments do not. - The selected blends' spines are built once per check. - The status bar and the help bar name the tool a press at the pointer takes, which is the Selection tool where the press selects behind, and they are drawn again when it changes. The canvas drops a hover's decision once the tool, the selection or a preference it depends on changes. Docs: docs/mcp.md (pointer_gesture, and Cmd+Alt with Direct Selection), docs/control-protocol.md, docs/ui-parity.md, docs/target-app-parity.md. --- crates/doc/src/hit.rs | 2 +- crates/engine/src/lib.rs | 5 +- crates/engine/src/tests/draw2.rs | 192 +++++++++++++++- crates/engine/src/tests/dynamic_symbols.rs | 20 ++ crates/engine/src/tooling.rs | 49 ++++- crates/tools/src/direct.rs | 32 +-- crates/tools/src/direct/tests.rs | 27 +++ crates/tools/src/select.rs | 245 +++++++++++++++++++-- crates/ui-egui/src/canvas.rs | 12 +- crates/ui-egui/src/canvas/tests.rs | 105 +++++++++ docs/control-protocol.md | 2 +- docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 14 files changed, 654 insertions(+), 50 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 7c0de44cab..8f96d46df2 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -189,7 +189,7 @@ pub fn set_live_art(f: LiveArt, inputs: LiveInputs) { } /// The registered [`LiveInputs`] now, 0 while nothing is registered. -fn live_inputs() -> u64 { +pub fn live_inputs() -> u64 { LIVE_ART.get().map_or(0, |(_, inputs)| inputs()) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e329dae1..bbcba38fff 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -113,9 +113,10 @@ pub struct Session { /// triple-click that follows it. None when the press was not lent. pub(crate) press_lent: Option<&'static str>, /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] - /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none). None when it was last asked + /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with + /// the document state, active tool and keys it was found for. None when it was last asked /// without Cmd. - pub(crate) hover_lent: Option>, + pub(crate) hover_lent: Option<(tooling::HoverKey, Option<&'static str>)>, pub(crate) last_view: ViewInfo, /// The selection tools' measurements for the active document as it is: a pointer move or a /// cursor asked for again over an unchanged document and selection measures nothing again. diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index f53a55e1e4..3ffd8e4576 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4786,11 +4786,21 @@ fn a_cmd_press_on_a_selected_object_keeps_select_behind() { let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); s.select_tool("selection", v).unwrap(); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); - // The canvas shows the marks of the tool a press at the pointer takes. + // The canvas shows the marks of the tool a press at the pointer takes, and the status bar and + // the help bar name it. s.cursor(Point::new(200.0, 200.0), cmd, v); assert_eq!(s.hover_tool_id(&cmd), "selection"); + assert_eq!(s.shown_tool_id(&cmd), "selection", "the press selects behind: nothing is lent"); s.cursor(Point::new(500.0, 500.0), cmd, v); assert_eq!(s.hover_tool_id(&cmd), "directSelection"); + assert_eq!(s.shown_tool_id(&cmd), "directSelection"); + // The bounding box's top middle handle, on the middle of the top segment: the press is lent. + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 150.0)), &cmd, v), "directSelection", "on a box handle"); + // Turning Select Behind off changes what the bars name over the selection. + s.cursor(Point::new(200.0, 200.0), cmd, v); + s.prefs.ctrl_click_selects_behind = false; + assert_eq!(s.shown_tool_id(&cmd), "directSelection"); + s.prefs.ctrl_click_selects_behind = true; s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); assert_eq!(s.tool_id(), "selection"); s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); @@ -4833,6 +4843,186 @@ fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() { assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); } +#[test] +fn repeated_cmd_clicks_select_behind_a_group_whose_member_is_selected() { + // The first Cmd-click on an unselected group lends Direct Selection, which selects the path + // under the pointer. The group holds that selected path, so the next Cmd-click there selects + // the object behind the group. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0); + let b = rect(&mut s, 210.0, 150.0, 40.0, 40.0); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + let click = |s: &mut Session| { + s.pointer(&PointerEvent::new(PointerKind::Down, 170.0, 170.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 170.0).with_mods(cmd), v).unwrap(); + }; + click(&mut s); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(a) && !picked.contains(group), "the first Cmd-click picks the path"); + assert_eq!(s.hover_tool_at(Some(Point::new(170.0, 170.0)), &cmd, v), "selection", "the next press selects behind"); + click(&mut s); + // Made quickly, the two clicks are also a double-click, which neither isolates the group nor + // changes what the second click selected, also with Cmd let go before it. + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 170.0, 170.0), v).unwrap(); + assert_eq!(s.doc().unwrap().isolation, None); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(a), "the second Cmd-click selects the object behind the group"); +} + +#[test] +fn a_double_click_after_a_selection_change_is_not_kept_for_select_behind() { + // A double-click that follows a Cmd-click selecting behind keeps what it selected, but only + // while the document stays as that click left it. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert!(!s.active().unwrap().selection.contains(front), "the Cmd-click selects behind"); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_after_the_pointer_moved_away_is_not_kept_for_select_behind() { + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert!(!s.active().unwrap().selection.contains(front), "the Cmd-click selects behind"); + s.pointer(&PointerEvent::new(PointerKind::Move, 400.0, 400.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_after_a_select_behind_drag_is_not_kept_for_select_behind() { + // A Cmd press that selects behind and then drags is not a click, also when the drag ends where + // it began and moves nothing, so a double-click there is a double-click of its own. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert!(s.active().unwrap().selection.contains(back), "the Cmd press selects behind"); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_after_a_select_behind_press_released_away_is_not_kept_for_select_behind() { + // The automation interface can send the release far from the press with no drag between. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 270.0, 270.0).with_mods(cmd), v).unwrap(); + assert!(s.active().unwrap().selection.contains(back), "the Cmd press selects behind"); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 270.0, 270.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_in_the_frame_of_a_select_behind_press_keeps_what_it_selected() { + // The second press and the double-click can come in one frame, before the release. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [back.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.doc().unwrap().isolation, None, "the double-click neither isolates nor edits"); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(front) && !picked.contains(back), "the press selects behind, back to the topmost"); +} + +#[test] +fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_behind() { + // The group counts as selected wherever its art is, not only over its selected member. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 300.0, 200.0); + let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0); + let b = rect(&mut s, 300.0, 150.0, 40.0, 40.0); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(320.0, 170.0)), &cmd, v), "selection", "on the unselected member"); + s.pointer(&PointerEvent::new(PointerKind::Down, 320.0, 170.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 170.0).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(b), "the Cmd-click selects the object behind the group"); +} + +#[test] +fn a_cmd_click_on_a_selected_lines_segment_selects_behind() { + // An open, unfilled path is only hit near its segments: a Cmd press there selects the object + // behind it, and a Cmd press on its anchor is Direct Selection's. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = line(&mut s, 150.0, 150.0, 250.0, 250.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(150.0, 150.0)), &cmd, v), "directSelection", "on its anchor"); + // On the segment, away from the anchors and the bounding box's handles. + s.pointer(&PointerEvent::new(PointerKind::Down, 180.0, 180.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 180.0).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); +} + +#[test] +fn a_hovers_lend_decision_holds_only_for_the_tool_and_selection_it_was_found_for() { + // While the view moves, the canvas reads the last hover's decision: it does not carry over to + // another tool or another selection. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection"); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.hover_tool_id(&cmd), "directSelection", "nothing is selected now"); + assert_eq!(s.hover_tool_at(Some(Point::new(500.0, 500.0)), &cmd, v), "directSelection"); + s.select_tool("rectangle", v).unwrap(); + assert_eq!(s.hover_tool_id(&cmd), s.lent_tool_id(&cmd).unwrap(), "the new tool's lend"); +} + #[test] fn the_marks_follow_this_frames_pointer_with_cmd_held() { // The canvas asks which tool's marks to draw before it asks for the cursor: the answer is for diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index e136d9f45b..7365d00c34 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -1032,6 +1032,26 @@ fn select_part_refuses_hidden_and_locked_objects_of_the_art() { s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1, 1]})).unwrap(); } +#[test] +fn a_cmd_click_with_the_selection_tool_keeps_the_instance_selected_whole() { + // Cmd lends Direct Selection the Selection tool: the press picks one object of a dynamic + // instance, and back with the Selection tool after the release, the instance stays selected, + // whole, as choosing the Selection tool leaves it. + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + let cmd = Mods { cmd: true, ..Mods::default() }; + s.select_tool("selection", v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 80.0, 30.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + assert!(s.doc().unwrap().selection.symbol_part.is_some(), "the lent tool picks the object"); + s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 30.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + let sel = &s.doc().unwrap().selection; + assert_eq!((&sel.objects, &sel.symbol_part), (&vec![inst], &None)); +} + #[test] fn choosing_the_selection_tool_again_picks_the_instance_whole() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index ba4f4089e4..d9c2e6e4dc 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -10,6 +10,14 @@ use vectorcraft_tools::{Action, Cursor, ImeSurrounding, Mods, Overlay, PointerEv use crate::{EngineError, Prefs, Result, Session}; +/// What a hover's lend decision holds for ([`Session::hover_tool_at`]): the active document's uid +/// and revision, the active tool, the keys, the selection tools chosen last and the preferences a +/// press's hit test reads (Command Click to Select Objects Behind, Object Selection by Path Only, +/// Type Object Selection by Path Only, Selection Tolerance, anchor Size; Use Preview Bounds, +/// Measure Type by Glyph Bounds, Show Handles When Multiple Anchors Are Selected). +pub(crate) type HoverKey = + (Option<(u64, u64)>, &'static str, Mods, (Option<&'static str>, Option<&'static str>), ((bool, bool, bool, f64, u32), (bool, bool, bool))); + /// The tool whose radius is General › Corner Radius. const ROUNDED_RECTANGLE: &str = "roundedRectangle"; @@ -290,9 +298,9 @@ impl Session { /// The tool the status bar and the help bar name with `mods` held: the selection tool Cmd /// lends ([`Self::lent_tool_id`]) while the button is up, Space does not lend a view tool and /// the active tool is not computing an edit, else the active tool. Over a selected object where - /// a Cmd press selects behind, it still names the tool Cmd lends elsewhere. + /// a Cmd press selects behind, as the cursor last found it, it names the active tool. pub fn shown_tool_id(&self, mods: &Mods) -> &'static str { - match self.lent_tool_id(mods) { + match self.hovered_lent(mods) { Some(id) if !mods.space && !self.tool_editing() && !self.pointer_held => id, _ => self.tool.id(), } @@ -303,13 +311,40 @@ impl Session { /// (before either has, the one [`Self::lent_tool_id`] names), else the active tool. The canvas /// asks this while the view moves, when it does not hit-test the art under the pointer. pub fn hover_tool_id(&self, mods: &Mods) -> &'static str { - let lent = self.hover_lent.unwrap_or_else(|| self.lent_tool_id(mods)); - match lent { + match self.hovered_lent(mods) { Some(id) if mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held => id, _ => self.tool.id(), } } + /// The selection tool a Cmd press with `mods` would borrow at the pointer: the one + /// [`Self::hover_tool_at`] or [`Self::cursor`] last found, while the document, the selection, + /// the active tool and the keys are as they were then (none where the press selects behind), + /// else the one [`Self::lent_tool_id`] names. + fn hovered_lent(&self, mods: &Mods) -> Option<&'static str> { + match self.hover_lent { + Some((key, lent)) if key == self.hover_key(mods) => lent, + _ => self.lent_tool_id(mods), + } + } + + /// What a hover's lend decision holds for: the active document's state (its uid and revision, + /// which moves with the selection), the active tool, the keys, the selection tools chosen last + /// and the preferences a press's hit test reads. + fn hover_key(&self, mods: &Mods) -> HoverKey { + let p = &self.prefs; + let picks = + (p.ctrl_click_selects_behind, p.object_selection_by_path_only, p.type_selection_by_path_only, p.selection_tolerance, p.anchor_size); + let bounds = (p.use_preview_bounds, p.type_glyph_bounds, p.show_handles_multiple_anchors); + ( + self.active().map(|d| (d.uid, d.revision)), + self.tool.id(), + *mods, + (self.last_selection_tool, self.last_part_selection_tool), + (picks, bounds), + ) + } + /// The tool whose marks and widgets the canvas draws this frame with `mods` held and the /// pointer at `p` (None off the canvas): the selection tool a Cmd press there would borrow /// ([`Self::lent_tool_at`]; off the canvas, the one [`Self::lent_tool_id`] names), else the @@ -321,7 +356,8 @@ impl Session { Some(p) => self.lent_tool_at(p, mods, view), None => self.lent_tool_id(mods), }; - self.hover_lent = lends.then_some(lent); + let key = self.hover_key(mods); + self.hover_lent = lends.then_some((key, lent)); lent.unwrap_or(self.tool.id()) } @@ -1404,7 +1440,8 @@ impl Session { // Cmd pressed once a drag is under way lends nothing, so the tool keeps its pointer. let lends = mods.cmd && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; let lent = if lends { self.lent_tool_at(p, &mods, view) } else { None }; - self.hover_lent = lends.then_some(lent); + let key = self.hover_key(&mods); + self.hover_lent = lends.then_some((key, lent)); let c = match lent { Some(id) => { let lent = self.make_tool(id); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 7b224e0717..e4a0d85829 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -444,7 +444,12 @@ fn hit_spine_point(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usiz /// The segment of a selected blend's spine passing within `tol` of `p`: (blend, segment, t, whether /// it is straight). pub(crate) fn hit_spine_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, f64, bool)> { - selected_spines(cx).into_iter().find_map(|(id, path)| { + spine_segment_in(&selected_spines(cx), p, tol) +} + +/// [`hit_spine_segment`] over spines already built. +fn spine_segment_in(spines: &[(NodeId, PathData)], p: Point, tol: f64) -> Option<(NodeId, usize, f64, bool)> { + spines.iter().find_map(|&(id, ref path)| { let (si, seg, t, _, dist) = path.nearest(p)?; (dist <= tol).then(|| (id, seg, t, path.subpaths.get(si).is_some_and(|sp| sp.segment_is_line(seg)))) }) @@ -597,21 +602,23 @@ fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, us }) } -/// Is `p` on a part of a selected object that Direct Selection edits: a gradient mesh point, a -/// blend's spine point or segment, an anchor, the end of a direction handle or a segment, within -/// the selection tolerance? A selected group or compound path counts through the editable paths -/// inside it. +/// Is `p` on a point of a selected object that Direct Selection edits: a gradient mesh point, a +/// blend's spine point or segment, an anchor or the end of a direction handle, within the +/// selection tolerance? A selected group or compound path counts through the editable paths +/// inside it. A path's segments do not count: a Cmd press there with Select Behind on selects +/// the object behind, which a stroke-only path can only be pressed on. pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { if cx.selection.objects.is_empty() { return false; } let tol = cx.point_tol(); let seg_tol = cx.pick_tol(); - if hit_handle(cx, p, tol).is_some() - || MeshEdit::default().hit(cx, &cx.selection.objects, p).is_some() - || selected_spines(cx).iter().any(|(_, path)| path.anchors().any(|(_, _, a)| a.p.distance(p) <= tol)) - || hit_spine_segment(cx, p, seg_tol).is_some() - { + if hit_handle(cx, p, tol).is_some() || MeshEdit::default().hit(cx, &cx.selection.objects, p).is_some() { + return true; + } + // The selected blends' spines are built once for both of their checks. + let spines = selected_spines(cx); + if spines.iter().any(|(_, path)| path.anchors().any(|(_, _, a)| a.p.distance(p) <= tol)) || spine_segment_in(&spines, p, seg_tol).is_some() { return true; } // The editable paths' control bounds are listed once per document state and selection; a @@ -630,13 +637,12 @@ pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { } v.into() }); - let reach = tol.max(seg_tol); boxes.iter().any(|&(id, b)| { - b.inflate(reach, reach).contains(p) + b.inflate(tol, tol).contains(p) && cx.doc.node(id).and_then(editable_path).is_some_and(|pd| { #[cfg(test)] MEASURED_PARTS.set(MEASURED_PARTS.get() + 1); - nearest_anchor(&pd, p, tol, None).is_some() || pd.nearest(p).is_some_and(|(.., d)| d <= seg_tol) + nearest_anchor(&pd, p, tol, None).is_some() }) }) } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 3cef62fab1..a9d5aab0c5 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2821,3 +2821,30 @@ fn over_selected_part_measures_only_the_paths_near_the_pointer() { let measured = MEASURED_PARTS.get() - before; assert!(measured < 10, "{measured} of 400 paths measured"); } + +/// The cursor, the canvas marks and a press each ask whether a Cmd press at the pointer selects +/// behind: while the document and the selection stay as they are, the selection's paths are +/// measured once for a point. +#[test] +fn select_behind_is_measured_once_for_a_point() { + use vectorcraft_doc::{Appearance, Node}; + let mut d = vectorcraft_doc::Document::new(400.0, 400.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let square = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)); + d.insert(Some(l), 0, Node::path(id, square, Appearance::default_art())).unwrap(); + // Below it, an object to select behind. + let back = vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 250.0, 250.0)); + let back_id = d.alloc_id(); + d.insert(Some(l), 0, Node::path(back_id, back, Appearance::default_art())).unwrap(); + let p = paint(); + let mut picked = Selection::default(); + picked.add(id); + let memo = crate::select::PreviewMemo::default(); + let c = ToolContext { preview_memo: Some(&memo), select_behind: true, ..cx(&d, &picked, &p) }; + let at = Point::new(150.0, 150.0); + let before = MEASURED_PARTS.get(); + assert!(crate::select::selects_behind_at(&c, at), "inside the selected square, away from its anchors"); + assert!(crate::select::selects_behind_at(&c, at)); + assert_eq!(MEASURED_PARTS.get() - before, 1, "measured for the first ask only"); +} diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 458ac68232..38040162aa 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -224,6 +224,11 @@ pub struct SelectionTool { /// Where the pointer was at the last press or drag: a widget drag released anywhere else is /// dragged there before it ends. held_at: Option, + /// Where the last press that selected the object behind (Cmd/Ctrl-click) was released: a + /// double-click there that follows it is that press clicked again, not a double-click that + /// isolates or edits. It holds the document's revision at the release too (None until then), + /// and an edit or a selection change after it ends it. + pressed_behind: Option<(Point, Option<(u64, u64)>)>, } /// What Distance Guides measure the selection to. @@ -513,20 +518,67 @@ struct MemoState { /// The measurements for one key; a slot holds `None` until it is measured. struct Measured { revision: (u64, u64), + /// The fonts, hyphenation exceptions and plug-ins live art is drawn and hit with + /// ([`vectorcraft_doc::hit::live_inputs`]). + live: u64, objects: Vec, measure: vectorcraft_effects::preview::Measure, bounds: Option>, oriented: Option>, by_object: HashMap>>, - /// [`painted_bounds`]. - painted: Option>, + /// [`painted_bounds`] in Preview and in Outline view. + painted: [Option>; 2], /// [`selected_part_boxes`]. part_boxes: Option>, + /// [`selection_holders`]. + holders: Option>>, + /// [`selects_behind_at`]'s last answer, with the point and settings it was for. + behind: Option<(BehindKey, bool)>, +} + +/// What [`selects_behind_at`] answers for besides the document and the selection: the point, the +/// tolerances (the zoom and the preferences) and the hit-test settings. +#[derive(Clone, Copy, PartialEq)] +struct BehindKey { + at: Point, + pick_tol: f64, + point_tol: f64, + scope: Option, + outline: bool, + path_only: bool, + type_path_only: bool, + skip_guides: bool, + handles_multiple: bool, + /// The zoom, which sets the mesh points' and the box handles' reach. + zoom: f64, + show_bbox: bool, +} + +impl BehindKey { + fn of(cx: &ToolContext, at: Point) -> Self { + let opt = cx.selection_hit_options(); + Self { + at, + pick_tol: cx.pick_tol(), + point_tol: cx.point_tol(), + scope: cx.isolation, + outline: opt.outline, + path_only: opt.path_only, + type_path_only: opt.type_path_only, + skip_guides: opt.skip_guides, + handles_multiple: cx.handles_multiple, + zoom: cx.zoom, + show_bbox: cx.show_bbox, + } + } } impl Measured { fn is_for(&self, cx: &ToolContext) -> bool { - self.revision == cx.revision && self.measure == cx.bounds_measure() && self.objects == cx.selection.objects + self.revision == cx.revision + && self.live == vectorcraft_doc::hit::live_inputs() + && self.measure == cx.bounds_measure() + && self.objects == cx.selection.objects } } @@ -548,13 +600,16 @@ impl PreviewMemo { st.checks += 1; let fresh = || Measured { revision: cx.revision, + live: vectorcraft_doc::hit::live_inputs(), objects: cx.selection.objects.clone(), measure: cx.bounds_measure(), bounds: None, oriented: None, by_object: HashMap::new(), - painted: None, + painted: [None, None], part_boxes: None, + holders: None, + behind: None, }; if !st.entry.as_ref().is_some_and(|m| m.is_for(cx)) { st.entry = Some(fresh()); @@ -569,10 +624,16 @@ impl PreviewMemo { { return v; } + let live = vectorcraft_doc::hit::live_inputs(); let v = measure(); + // Live inputs that changed while it measured leave the value unkept: only the entry for the + // inputs it was measured with takes it. if let Ok(mut st) = self.0.try_borrow_mut() { st.measurements += 1; - *slot(Self::current(&mut st, cx)) = Some(v.clone()); + let m = Self::current(&mut st, cx); + if m.live == live { + *slot(m) = Some(v.clone()); + } } v } @@ -600,10 +661,39 @@ pub fn selection_box(cx: &ToolContext) -> Option { remembered(cx, |m| &mut m.oriented, || vectorcraft_effects::preview::oriented_bounds_with(cx.doc, &cx.selection.objects, cx.bounds_measure())) } -/// The selection's visual bounds as drawn, its strokes and effects included, whatever Use Preview -/// Bounds says: every point where a hit test finds a selected object is inside them. +/// The bounds a hit test can find the objects in that a click selects for the selected art +/// ([`top_holder`]): their reach (a blend's spine included), their visual bounds as drawn +/// (strokes and effects included, whatever Use Preview Bounds says) and their geometric bounds +/// (where Outline view hits the paths), together, kept for each view mode. fn painted_bounds(cx: &ToolContext) -> Option { - remembered(cx, |m| &mut m.painted, || vectorcraft_effects::preview::bounds_of(cx.doc, &cx.selection.objects, true)) + let outline = cx.selection_hit_options().outline; + remembered( + cx, + |m| &mut m.painted[usize::from(outline)], + || { + let mut seen = std::collections::HashSet::new(); + let tops: Vec = cx.selection.objects.iter().map(|&id| top_holder(cx, id)).filter(|id| seen.insert(*id)).collect(); + // A layer or group above them with visible effects of its own that draw art (not raster + // effects, which a hit test leaves out, nor color adjustments) can draw (and hit) them + // anywhere. Outline view hits the paths where they are. + let moves_art = |e: &vectorcraft_doc::Effect| { + e.visible && !outline && !vectorcraft_effects::is_raster(&e.id) && !vectorcraft_effects::is_adjustment(&e.id) + }; + let above_has_effects = tops.iter().any(|id| { + cx.doc.ancestry(*id).is_some_and(|a| { + a.iter().take_while(|n| *n != id).any(|n| cx.doc.node(*n).is_some_and(|n| n.appearance.effects.iter().any(moves_art))) + }) + }); + if above_has_effects { + return Some(Rect::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY)); + } + let symbols = cx.doc.symbol_boxes(); + let reach = tops.iter().filter_map(|id| cx.doc.node(*id)).filter_map(|n| n.reach_bounds_with(&symbols)); + let drawn = vectorcraft_effects::preview::bounds_of(cx.doc, &tops, true); + let geometric = vectorcraft_effects::preview::bounds_of(cx.doc, &tops, false); + reach.chain(drawn).chain(geometric).reduce(|a, b| a.union(b)) + }, + ) } /// `measure`'s list of the selected objects' editable paths with their control bounds, kept in the @@ -819,6 +909,25 @@ impl SelectionTool { } } + /// Each press, whatever takes it, starts with no Select Behind of its own, and the double-click + /// that follows one comes where that press is released, with the document as the release left + /// it, before the pointer moves away; a press that drags or is released away is not a click + /// ([`Self::pressed_behind`]). + fn note_pressed_behind(&mut self, cx: &ToolContext, ev: &PointerEvent) { + match ev.kind { + PointerKind::Down => self.pressed_behind = None, + PointerKind::Move | PointerKind::Drag => { + if self.pressed_behind.is_some_and(|(at, _)| at.distance(ev.pos) > cx.tol(1.0)) { + self.pressed_behind = None; + } + } + PointerKind::Up => { + self.pressed_behind = self.pressed_behind.filter(|(at, _)| at.distance(ev.pos) <= cx.tol(1.0)).map(|_| (ev.pos, Some(cx.revision))); + } + _ => {} + } + } + /// Notes where a press or a drag last held the pointer, and says whether a release lands /// somewhere else. fn note_held_at(&mut self, ev: &PointerEvent) -> bool { @@ -1080,10 +1189,16 @@ impl Tool for SelectionTool { } } + /// A press lent to another tool is not a Select Behind press of this tool. + fn press_elsewhere(&mut self) { + self.pressed_behind = None; + } + /// A press takes the selection's widgets, a ruler guide, a selected object's centre point or /// the art; the drags then move, scale, rotate, marquee or drag what it took. fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.note_loaded_at_press(ev.kind); + self.note_pressed_behind(cx, ev); let released_away = self.note_held_at(ev); let hovering = ev.kind == PointerKind::Move && matches!(self.state, State::Idle); self.bracket_hover = hovering.then_some(ev.pos); @@ -1146,6 +1261,7 @@ impl Tool for SelectionTool { { self.state = State::Moving { start: p, press: p, hold: p, grip: Grip::Point, began: false, deselect: None, key: None, exclude: None }; + self.pressed_behind = Some((p, None)); return vec![Action::Exec("select.set".into(), json!({ "ids": [behind.0] }))]; } let (hit, scope) = match selected_source_hit(cx, p) { @@ -1518,26 +1634,103 @@ impl Tool for SelectionTool { } } -/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and a -/// selected object under the pointer, away from the anchors, handles and segments Direct -/// Selection edits ([`crate::direct::over_selected_part`])? Elsewhere Cmd lends the press to -/// Direct Selection or Group Selection. +/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and an +/// object under the pointer selected or holding selected art (a group with a selected member), +/// with another object under the pointer too, away from the anchors, handles, mesh points and +/// spine Direct Selection edits ([`crate::direct::over_selected_part`])? Elsewhere Cmd lends the +/// press to Direct Selection or Group Selection. pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { + if !cx.select_behind { + return false; + } let tol = cx.pick_tol(); - // The selection's painted bounds come first: away from them, no document walk is needed. They - // take in a wide stroke's outer half, which the bounding box leaves out without Use Preview - // Bounds. - cx.select_behind - && painted_bounds(cx).is_some_and(|b| b.inflate(tol, tol).contains(p)) - && objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation).iter().any(|id| cx.selection.contains(*id)) - && !crate::direct::over_selected_part(cx, p) + // The answer is kept for the document and the selection as they are: the cursor, the canvas + // marks and a press at the same point ask again without walking the document again. + let key = BehindKey::of(cx, p); + if let Some(memo) = cx.preview_memo + && let Ok(mut st) = memo.0.try_borrow_mut() + && let Some((k, v)) = PreviewMemo::current(&mut st, cx).behind + && k == key + { + return v; + } + // The painted bounds of the objects holding the selection come first: away from them, no + // document walk is needed. They take in a wide stroke's outer half, which the bounding box + // leaves out without Use Preview Bounds, and a group's members that are not selected. With no + // other object under the pointer there is nothing to select behind: the press is lent. + // A shown bounding box's handles and rotate zones are not passed to Select Behind: the press + // there is lent. + let live = vectorcraft_doc::hit::live_inputs(); + let behind = painted_bounds(cx).is_some_and(|b| b.inflate(tol, tol).contains(p)) + && !shown_box(cx).is_some_and(|b| box_hit(cx, &b, p).is_some()) + && { + let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); + stack.len() > 1 && holds_selection(cx, &stack).is_some() + } + && !crate::direct::over_selected_part(cx, p); + if let Some(memo) = cx.preview_memo + && let Ok(mut st) = memo.0.try_borrow_mut() + { + st.measurements += 1; + // Only the entry for the live inputs it was found with keeps the answer. + let m = PreviewMemo::current(&mut st, cx); + if m.live == live { + m.behind = Some((key, behind)); + } + } + behind } -/// Select Behind: of the objects under `p` (topmost first), the one below the lowest selected -/// one, back to the topmost after the bottom one; the topmost when none is selected. +/// The index in `stack` (objects under the pointer, topmost first) of the lowest object that is +/// selected or holds selected art, such as a group with a member picked by Direct Selection or +/// Group Selection. +fn holds_selection(cx: &ToolContext, stack: &[NodeId]) -> Option { + let holders = selection_holders(cx); + stack.iter().rposition(|id| holders.contains(id)) +} + +/// The selected objects and every object that holds one (their groups and layers), kept in the +/// session's [`PreviewMemo`] while the document and the selection stay as they are. +fn selection_holders(cx: &ToolContext) -> std::sync::Arc> { + remembered( + cx, + |m| &mut m.holders, + || { + let set = cx.selection.objects.iter().flat_map(|&id| holder_chain(cx, id)).collect(); + std::sync::Arc::new(set) + }, + ) +} + +/// The selected object `id` and the objects holding it, outermost first, from the object a click +/// with the Selection tool selects for it ([`Hit::top_object`]): below its layers, the isolated +/// object and an envelope whose contents are edited. +fn holder_chain(cx: &ToolContext, id: NodeId) -> Vec { + let Some(a) = cx.doc.ancestry(id) else { return vec![id] }; + let isolated = cx.isolation.and_then(|s| a.iter().position(|n| *n == s)); + let contents = + a.iter().rposition(|n| cx.doc.node(*n).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Envelope { editing: true, .. }))); + // Below the isolated object or the envelope, the child holding `id` is the top object, a + // sublayer included; elsewhere layers and sublayers are skipped. + let chain: Vec = match isolated.max(contents) { + Some(i) => a.iter().skip(i + 1).copied().collect(), + None => a.iter().copied().skip_while(|n| cx.doc.node(*n).is_some_and(|n| n.is_layer())).collect(), + }; + if chain.is_empty() { vec![id] } else { chain } +} + +/// The object a click with the Selection tool selects for the selected object `id` +/// ([`holder_chain`]). +fn top_holder(cx: &ToolContext, id: NodeId) -> NodeId { + holder_chain(cx, id).first().copied().unwrap_or(id) +} + +/// Select Behind: of the objects under `p` (topmost first), the one below the lowest one that is +/// selected or holds selected art, back to the topmost after the bottom one; the topmost when +/// none is. fn object_behind(cx: &ToolContext, p: Point) -> Option { let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); - let next = stack.iter().rposition(|id| cx.selection.contains(*id)).map_or(0, |i| i + 1); + let next = holds_selection(cx, &stack).map_or(0, |i| i + 1); stack.get(next).or(stack.first()).copied() } @@ -1853,6 +2046,14 @@ impl SelectionTool { fn double_click(&mut self, cx: &ToolContext, p: Point, m: Mods) -> Vec { self.state = State::Idle; + // Quick Cmd-clicks that select behind keep what the last one selected, before the widgets + // of that object answer, also when Cmd is let go before the release. Cmd+Shift on a guide + // still releases it. A double-click elsewhere, or after an edit or a selection change, is a + // double-click of its own. A press whose release has not come yet (both in one frame) + // still counts. + if self.pressed_behind.take().is_some_and(|(at, rev)| at.distance(p) <= cx.tol(1.0) && rev.is_none_or(|r| r == cx.revision)) { + return release_guide_at(cx, p, m).into_iter().collect(); + } // A threaded port: the thread breaks there. Any other port takes the double-click // too, so it neither edits the type nor isolates. if let Some((id, port)) = crate::text::port_at(cx, p) { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index cd375d0952..e44d7013d1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1653,7 +1653,17 @@ pub(super) fn guide_labels(doc: &vectorcraft_doc::Document) -> std::collections: /// the pointer is not hit-tested again (#2452), and the last answer stays. fn marks_tool(app: &mut VectorcraftApp, ctx: &egui::Context, hover_still: bool, view: vectorcraft_engine::ViewInfo) -> &'static str { let held = held_mods(app, ctx); - if hover_still { app.session.hover_tool_at(app.hover_doc, &held, view) } else { app.session.hover_tool_id(&held) } + if !hover_still { + return app.session.hover_tool_id(&held); + } + let named = app.session.shown_tool_id(&held); + let tool = app.session.hover_tool_at(app.hover_doc, &held, view); + // The status bar and the help bar are drawn before the canvas: when the tool they name changes + // with this frame's pointer, they are drawn again. + if app.session.shown_tool_id(&held) != named { + ctx.request_repaint(); + } + tool } /// The selection's visuals and the tools' overlays, to be drawn. `tool` is the tool whose marks diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 508ccb03a0..21dd33b715 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -7159,6 +7159,111 @@ fn blend_widgets_hide_while_cmd_lends_direct_selection() { assert_eq!(widgets(&mut app, egui::Modifiers::NONE), plain, "back when the key is let go"); } +/// One canvas frame with `modifiers` held and, when given, the pointer moved to `pointer` (in +/// screen points) → the shapes drawn, with the ones in shape lists listed one by one. +fn drawn_with(app: &mut VectorcraftApp, ctx: &egui::Context, modifiers: egui::Modifiers, pointer: Option) -> Vec { + app.canvas.selection_marks = Default::default(); + let mut events = vec![egui::Event::ModifiersChanged(modifiers)]; + events.extend(pointer.map(egui::Event::PointerMoved)); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let mut drawn = vec![]; + for c in out.shapes { + match c.shape { + Shape::Vec(v) => drawn.extend(v), + s => drawn.push(s), + } + } + drawn +} + +/// The widgets only the Selection tool presses (a Shaper Group's mode widget, a mirror repeat's +/// axis, a grid or radial repeat's handles) hide while Cmd lends Direct Selection. +#[test] +fn selection_tool_widgets_hide_while_cmd_lends_direct_selection() { + let ctx = egui::Context::default(); + let count = |app: &mut VectorcraftApp, modifiers: egui::Modifiers, is_widget: &dyn Fn(&Shape) -> bool| { + drawn_with(app, &ctx, modifiers, None).iter().filter(|s| is_widget(s)).count() + }; + // Each widget that does not draw, hide or come back as it should. + let mut wrong = vec![]; + let mut check = |app: &mut VectorcraftApp, what: &str, is_widget: &dyn Fn(&Shape) -> bool| { + app.select_tool("selection"); + let plain = count(app, egui::Modifiers::NONE, is_widget); + let held = count(app, egui::Modifiers::COMMAND, is_widget); + let back = count(app, egui::Modifiers::NONE, is_widget); + if plain == 0 || held != 0 || back != plain { + wrong.push(format!("{what}: {plain} drawn, {held} with Cmd held, {back} after")); + } + }; + let new_app = || { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app + }; + let circle_of = |r: f32| move |s: &Shape| matches!(s, Shape::Circle(c) if c.radius == r); + + let mut app = new_app(); + for x in [0, 50] { + app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap(); + } + app.run("shaper.scribble", json!({"points": [[25, 20], [75, 35], [30, 50], [125, 65]]})).unwrap(); + check(&mut app, "the Shaper Group's mode widget", &circle_of(vectorcraft_tools::shaperwidget::RADIUS_PX)); + + let mut app = new_app(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 80})).unwrap(); + app.run("object.repeat.mirror", json!({})).unwrap(); + let selection = Tokens::get(&ctx).selection; + check( + &mut app, + "the mirror axis", + &move |s: &Shape| matches!(s, Shape::LineSegment { stroke, .. } if stroke.color == selection && stroke.width == 2.0), + ); + + let mut app = new_app(); + app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 40, "height": 40})).unwrap(); + app.run("object.repeat.grid", json!({"hSpacing": 10, "vSpacing": 10})).unwrap(); + check(&mut app, "the grid repeat's handles", &circle_of(vectorcraft_tools::repeat_grid::HANDLE_RADIUS)); + + let mut app = new_app(); + app.run("shape.rectangle", json!({"x": 180, "y": 40, "width": 40, "height": 40})).unwrap(); + app.run("object.repeat.radial", json!({"instances": 6, "radius": 60})).unwrap(); + check(&mut app, "the radial repeat's handles", &circle_of(vectorcraft_tools::repeat_radial::HANDLE_RADIUS)); + assert!(wrong.is_empty(), "{}", wrong.join("\n")); +} + +/// The canvas decides which tool's widgets to draw for the pointer where it is in the same frame: +/// over the selected blend a Cmd press selects behind, so the Selection tool's blend widgets stay; +/// moved away in the next frame, where Cmd lends Direct Selection, they hide in that frame. +#[test] +fn the_widgets_follow_the_pointer_in_the_frame_it_moves() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + // Behind the blend, an object to select behind. + app.session.execute("shape.rectangle", &json!({"x": 20, "y": 120, "width": 360, "height": 160})).unwrap(); + let a = id(app.session.execute("shape.rectangle", &json!({"x": 60, "y": 160, "width": 80, "height": 80})).unwrap()); + let b = id(app.session.execute("shape.rectangle", &json!({"x": 260, "y": 160, "width": 80, "height": 80})).unwrap()); + app.session.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let blend = id(app.session.execute("object.blend.make", &json!({})).unwrap()); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [blend]})).unwrap(); + let ctx = egui::Context::default(); + let r = vectorcraft_tools::blendwidget::RADIUS_PX; + let widgets = |app: &mut VectorcraftApp, modifiers: egui::Modifiers, at: Option| { + let pointer = at.map(|p| Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(p)); + drawn_with(app, &ctx, modifiers, pointer).iter().filter(|s| matches!(s, Shape::Circle(c) if c.radius == r)).count() + }; + let plain = widgets(&mut app, egui::Modifiers::NONE, None); + assert!(plain >= 2, "the Appearance and Easing widgets: {plain}"); + // Inside the first key object, away from its anchors and the spine. + let over = widgets(&mut app, egui::Modifiers::COMMAND, Some(Point::new(80.0, 175.0))); + assert_eq!(over, plain, "over the selected blend, the press selects behind"); + let away = widgets(&mut app, egui::Modifiers::COMMAND, Some(Point::new(200.0, 380.0))); + assert!(away + 2 <= plain, "away from it, hidden in the same frame: {away} of {plain}"); +} + /// A selected Objects on Path group shows its Rotate All widget with the Selection and Objects on /// Path tools. #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 58c13dbe9b..3727b6c798 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -96,7 +96,7 @@ the two can still win that race. | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | | `ui.tool.select` / `ui.tool.list` | `{tool}` | | -| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is); with Direct Selection or Group Selection it drags with the Selection tool, and with the Selection tool it drags with Direct Selection or Group Selection, whichever was chosen last, except on a selected object away from its anchors, handles and segments while `ctrlClickSelectsBehind` is on, where the press selects the object behind; the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | +| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is); with Direct Selection or Group Selection it drags with the Selection tool (with Direct Selection and `mods.alt` held too, with Group Selection), and with the Selection tool it drags with Direct Selection or Group Selection, whichever was chosen last, except on a selected object (or a group holding a selected member) with another object under the pointer, away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones while `ctrlClickSelectsBehind` is on, where the press selects the object behind; the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | | `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | synthetic keyboard input | | `ui.move` | `{x, y}` | screen-point pointer move | | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..4f3c98abb7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7080,7 +7080,14 @@ there too and a `brush.freehand` call does not change the path's brush or the se A `pointer_gesture` with `mods: {cmd: true}` held at the press, with any tool but the selection tools (Command on macOS, Ctrl elsewhere), drags with the selection tool chosen last (`select_tool`), or Direct Selection with the Pen, Curvature and anchor tools until one is chosen; the release gives the tool back as it was, so the Pen goes on drawing -the path it had begun while that stays selected. Its reply's `tool` is the tool given back. +the path it had begun while that stays selected. With Direct Selection or Group Selection, `mods.cmd` drags with the +Selection tool (with Direct Selection and `mods.alt` held too, with Group Selection). With the Selection tool, it drags +with Direct Selection or Group Selection, whichever was chosen last +(Direct Selection until one is), except where the press lands on a selected object, or on a group holding a selected +member, with another object under the pointer, away from its anchors, direction handles, mesh points, blend spine and +the bounding box's handles and rotate zones, while `ctrlClickSelectsBehind` is on: there the Selection tool keeps the press and selects the +object behind. A double-click or triple-click made with Cmd still held after Cmd-clicks goes to the tool the clicks went +to, and one that follows a Cmd-click selecting behind keeps what that click selected, without isolating or editing. Its reply's `tool` is the tool given back. `tool.selectLastSelection` (Select Last Selection Tool, `{}`) chooses the selection tool chosen last, as Ctrl+` does on Windows and Linux ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..817e79d3ac 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1523,7 +1523,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Composition's leading-space reduction stays along the line when a character rotates. An opening bracket trimmed by Line-end Punctuation Half Width Mojikumi keeps that placement under Character Rotation; its turning point follows the composition adjustment, and removing the rotation keeps the trim. Scores and estimates are unchanged. A character rotated near or at a quarter turn follows a Touch Type drag across its line as well as along it: baseline shift moves a character up from its line at any rotation, and the character turns about its shifted pen position. Right-to-left characters can also move along their line when a preceding logical character is on that line. Positive `text.touchType` `dx` follows reading order, toward the left in horizontal right-to-left text; the first logical character still moves only up and down. These direction rules are VectorCraft's choices; the public Touch Type page describes moving a character without specifying this case. Scores and estimates are unchanged. - - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. A single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses that tool only until the key is let go, and the tool active before comes back (after a drag in progress ends); a quicker press chooses the tool for good. This is VectorCraft's own rule and its own threshold, and General › Hold a Tool Shortcut to Use the Tool Temporarily (`holdToolKeys`, on by default) turns it off. + - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). With the Selection tool, Cmd lends Direct Selection or Group Selection, whichever was chosen last, until the key is released; with Group Selection it lends the Selection tool. A Cmd press on a selected object, or on a group holding a selected member, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, keeps Select Behind while Command Click to Select Objects Behind is on (#5970, #6583). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. A single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses that tool only until the key is let go, and the tool active before comes back (after a drag in progress ends); a quicker press chooses the tool for good. This is VectorCraft's own rule and its own threshold, and General › Hold a Tool Shortcut to Use the Tool Temporarily (`holdToolKeys`, on by default) turns it off. Space held while the Zoom tool drags a marquee moves the marquee and keeps its size ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). When Space is let go, the drag sizes the marquee again from where it moved to. A Space+Shift drag rotates the view whatever the tool, as a Rotate View tool drag does, and Shift does not round the angle to 15°. While the Type tool edits text, Space types a space: held, it does not show the hand, pan or rotate the view, and Cmd+Space still zooms ([the help page](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the Spacebar as the Hand tool when not in text-edit mode). Test: `canvas::tests::space_types_a_space_while_editing_text_and_does_not_pan`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f9f140fc76..8fdb42793c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -366,7 +366,7 @@ tools, never checked side by side) isn't captured row by row. | Space: Hand; Cmd+Space / Cmd+Alt+Space: zoom in/out; middle button pans | done | Space pressed after a tool takes a drag keeps the view still and shows that tool's cursor. Shape and anchor tools may use Space to move the geometry being drawn. Cmd+Space pressed mid-drag likewise keeps the active tool cursor. Space held before a press starts a view gesture, and its view cursor returns after release. `space_during_a_pencil_drag_keeps_the_pencil_cursor`, `cmd_space_mid_tool_drag_keeps_the_active_tool_cursor` | | Document window scroll bars along the right and bottom edges (Normal and Full Screen Mode with Menu Bar; none in Full Screen and Presentation Mode): a thumb as long as the view against the art and the artboards; dragging it scrolls, a click on the track pages, the wheel over a bar scrolls along it; in a rotated view they follow the screen's axes | partial | #2322. The span is the art and the artboards with half a window around them, not Illustrator's 227 in canvas: VectorCraft has no bounded drawing area (#2284). A track click pages rather than jumping to the click; the page size and the rotated-view behaviour are our own choice (the public documentation gives neither) | | A tool drag held near an edge of the canvas scrolls the view (#8551): zoomed in, a selection moved, a shape drawn or a marquee dragged towards the panels goes on past what shows | partial | Within 24 points of the canvas edge, once the pointer has moved 3 points from the press, the view scrolls away from that edge, faster nearer it (up to 900 points a second at the edge, and no faster in a corner, where it scrolls both ways), and keeps scrolling while the pointer stays still; the tool gets the pointer's new place in the document, so moved art stays under the pointer. Back away from the edge it stops. A click near the edge, the Hand, Zoom and Rotate View drags and Space panning do not scroll. The pointer past the canvas edge does not scroll: over a panel the Selection tools hand the art to the panels (#2826). The zone and speeds are VectorCraft's own (the public documentation gives none). Tests: `canvas::tests_edge_scroll` | -| Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); Cmd lends Group Selection the Selection tool, and the Selection tool Direct Selection or Group Selection, whichever was chosen last, except that a Cmd press on a selected object, away from its anchors, handles and segments, still selects the object behind it while Command Click to Select Objects Behind is on; Cmd pressed once a drag is under way lends nothing; while Cmd is held, the status bar's Current Tool and the help bar name the tool it lends ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Work with selections"); engine pointer and canvas regressions | +| Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); Cmd lends Group Selection the Selection tool, and the Selection tool Direct Selection or Group Selection, whichever was chosen last, except that a Cmd press on a selected object, or on a group holding a selected member, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, still selects the object behind it while Command Click to Select Objects Behind is on, so repeated Cmd-clicks select behind as "Select behind an object" (Ctrl+click twice, Command+click twice on macOS) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists; Cmd pressed once a drag is under way lends nothing; while Cmd is held, the status bar's Current Tool and the help bar name the tool a press at the pointer takes; engine pointer and canvas regressions | | Eyedropper copies effective character dimensions between transformed text objects | done | Point/area and grouped text, highlighted ranges, reverse/remembered sampling, opt-outs and atomic invalid-transform rejection; `scaled_type_pick_*` (#6404) | | Eyedropper styles highlighted characters only and preserves ranges across Type switches | done | Font/paint, Shift color-only, Unicode, Undo/Redo and stale-range regression tests; enabled non-neutral source or target object transparency is refused atomically; disable Transparency to sample supported attributes | | Gradient mesh: a solid color dropped from the Color or Swatches panel or a Fill proxy on a selected mesh recolors the mesh point under the pointer, else the patch's four points; with the mesh selected, an Eyedropper click applies the fill color the same way | done | [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); `object.mesh.setPointColor`, one undo step, none when the color is unchanged. The 5-pixel reach for a point is VectorCraft's own. Tests `a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it`, `a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color`, `a_click_on_an_object_over_a_selected_mesh_copies_that_object` | From 80f96d11f9206d893ad141fd513ac47525ec76c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:46:10 -0800 Subject: [PATCH 38/78] Path Precision Tools: Add Inscribed Circle draws the largest circle inside a path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Path Precision Tools › Add Inscribed Circle (`addon.pathtools.inscribedCircle`) draws the largest live circle inside each selected closed path or compound path, centered on its pole of inaccessibility. Part of #6966. - The outline is resolved under its fill rule into outer contours and holes, so overlapping subpaths count as the area they fill and holes bound the circle down to 1e-6 pt wide, the path operations' resolution. Square cells are searched best first, and the radius is measured from the center to the curves: within 0.02 pt of the largest, or a thousandth of the narrower side for a shape less than 10 pt across. - The circle is drawn up to 0.03% smaller, by as much as its four curves reach past a true circle, so it stays inside where it touches. - Open paths, other objects, shapes that fill no area, and outlines past 262,144 flattened pieces or the search's work limit are errors that leave the document unchanged. The first cells are sized to the work limit. - The circles get the current paint, go on top of the current layer or the isolated group, and are one undo step. - Docs: docs/mcp.md, docs/target-app-parity.md, docs/ui-parity.md, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/pathtools.rs | 6 +- .../src/cmd/addons/pathtools/bounding.rs | 2 +- .../src/cmd/addons/pathtools/inscribed.rs | 88 +++++++ .../cmd/addons/pathtools/inscribed/tests.rs | 203 +++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/pathops/src/addons/pathtools.rs | 7 +- .../pathops/src/addons/pathtools/inscribed.rs | 245 ++++++++++++++++++ .../src/addons/pathtools/inscribed/tests.rs | 140 ++++++++++ crates/ui-egui/src/addons/pathtools.rs | 3 +- docs/mcp.md | 18 ++ docs/target-app-parity.md | 4 + docs/ui-parity.md | 1 + 13 files changed, 713 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/cmd/addons/pathtools/inscribed.rs create mode 100644 crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs create mode 100644 crates/pathops/src/addons/pathtools/inscribed.rs create mode 100644 crates/pathops/src/addons/pathtools/inscribed/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 90a6100167..89eaa755d7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -158,6 +158,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. +- 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 586dc9947e..2c14c3deba 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -4,8 +4,8 @@ //! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's //! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes //! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents -//! ([`tangents`]), Tangent Circle ([`tangent_circle`]) and Add Bounding Rectangle and Add -//! Bounding Circle ([`bounding`]). +//! ([`tangents`]), Tangent Circle ([`tangent_circle`]), Add Bounding Rectangle and Add +//! Bounding Circle ([`bounding`]) and Add Inscribed Circle ([`inscribed`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. @@ -14,6 +14,7 @@ mod bridge; mod corners; #[cfg(test)] mod effect_tests; +mod inscribed; mod shape; mod shared_edge; mod tangent_circle; @@ -190,6 +191,7 @@ pub fn specs() -> Vec { v.extend(tangent_circle::specs()); v.extend(tangents::specs()); v.extend(bounding::specs()); + v.extend(inscribed::specs()); v } diff --git a/crates/engine/src/cmd/addons/pathtools/bounding.rs b/crates/engine/src/cmd/addons/pathtools/bounding.rs index 954a4f829a..b82b67832e 100644 --- a/crates/engine/src/cmd/addons/pathtools/bounding.rs +++ b/crates/engine/src/cmd/addons/pathtools/bounding.rs @@ -49,7 +49,7 @@ pub(super) fn specs() -> Vec { /// Enabled with a selection that is not an object of a symbol instance's art, which /// [`selected_roots_to_transform`] refuses. -fn whole_objects(s: &Session) -> std::result::Result<(), String> { +pub(super) fn whole_objects(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; no_symbol_part(s) } diff --git a/crates/engine/src/cmd/addons/pathtools/inscribed.rs b/crates/engine/src/cmd/addons/pathtools/inscribed.rs new file mode 100644 index 0000000000..2e016f23a7 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/inscribed.rs @@ -0,0 +1,88 @@ +//! Add Inscribed Circle: the largest live circle inside each selected closed path or compound +//! path. The circle is the pathops crate's +//! ([`inscribed_circle`](vectorcraft_pathops::addons::pathtools::inscribed_circle)). + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, FillRule, PathData}; +use vectorcraft_pathops::addons::pathtools::{self as pt, InscribedError}; + +use super::super::super::edit::selected_roots_to_transform; +use super::super::super::{CommandSpec, bad, cmd}; +use super::bounding::whole_objects; +use crate::{Result, Session}; + +#[cfg(test)] +mod tests; + +/// The command. +pub(crate) const COMMAND: &str = "addon.pathtools.inscribedCircle"; +/// The undo step's name. +const LABEL: &str = "Add Inscribed Circle"; +/// How far a live circle's four curves reach past a true circle, as a share of its radius: at +/// most 0.0273%, about 20° from each axis. +const CIRCLE_BULGE: f64 = 3e-4; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.pathtools.inscribedCircle", + "Add Inscribed Circle", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{} draw the largest live circle inside each selected closed path or compound path (a path of a compound path selected on its own counts as a path): the circle lies in the area the path fills under its fill rule, so holes and the overlaps of crossing subpaths count as the fill shows them, and its radius is within 0.02 pt of the largest (for a shape at least 10 pt across; a smaller one is measured to a thousandth of its narrower side; a curve whose control polygon is longer than 83,886 pt is flattened more coarsely, and the circle can be smaller by as much). The drawn circle's four curves reach up to 0.03% of its radius past a true circle, so it is drawn that much smaller and stays inside where it touches. Strokes and effects are left out. The circles get the current paint and go on top of the current layer or of the isolated group, as other new art; they are selected; one undo step. It is an error, with the document unchanged, when a selected object is not a closed path or compound path (\"object N is not a closed path or compound path\"; an open path has no inside), when it fills no area (\"object N fills no area\"), and when its outline has more than 262,144 straight pieces once flattened or its search goes past its limit (\"object N is too complex to measure\") → {id: the first circle, ids}", + whole_objects, + inscribed_circle + )] +} + +/// The outline of path or compound path `id` and its fill rule; `None` for anything else, an open +/// path, or a compound path with an open member. +fn outline(d: &Document, id: NodeId) -> Option<(PathData, FillRule)> { + let n = d.node(id)?; + let (paths, rule): (Vec<&PathData>, FillRule) = match &n.kind { + NodeKind::Path { path, rule, .. } => (vec![path], *rule), + NodeKind::Compound { children, rule } => (children.iter().filter_map(|c| c.path_data()).collect(), *rule), + _ => return None, + }; + let subpaths: Vec<_> = paths.iter().flat_map(|p| p.subpaths.iter()).filter(|sp| !sp.anchors.is_empty()).collect(); + if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed) { + return None; + } + Some((PathData::new(subpaths.into_iter().cloned().collect()), rule)) +} + +fn inscribed_circle(s: &mut Session, _p: &Value) -> Result { + let roots = selected_roots_to_transform(s)?; + let d = &s.doc()?.doc; + let mut circles = vec![]; + for id in roots { + let value = id.0; + let Some((path, rule)) = outline(d, id) else { + return Err(bad(COMMAND, format!("object {value} is not a closed path or compound path"))); + }; + let c = pt::inscribed_circle(&path, rule).map_err(|e| match e { + InscribedError::NoArea => bad(COMMAND, format!("object {value} fills no area")), + InscribedError::TooComplex => bad(COMMAND, format!("object {value} is too complex to measure")), + })?; + circles.push(c); + } + let parent = s.doc()?.target_parent()?; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let ids = s.edit(LABEL, |d, sel| { + let mut ids = vec![]; + for c in &circles { + // Smaller by the curves' bulge, so the drawn circle stays inside where it touches. + let (r, at) = (c.radius / (1.0 + CIRCLE_BULGE), c.center); + let live = LiveShape::Ellipse { w: 2.0 * r, h: 2.0 * r, pie: (0.0, 360.0), xf: Affine::translate((at.x - r, at.y - r)) }; + let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false }; + let mut n = Node::new(d.alloc_id(), kind); + look.apply(d, &mut n); + ids.push(n.id); + d.insert(parent, usize::MAX, n)?; + } + sel.set(ids.iter().copied()); + Ok(ids) + })?; + let first = ids.first().map_or(0, |id| id.0); + Ok(json!({ "id": first, "ids": ids.iter().map(|i| i.0).collect::>() })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs b/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs new file mode 100644 index 0000000000..f19c8fd111 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs @@ -0,0 +1,203 @@ +//! Add Inscribed Circle: the largest circle in a square, a concave shape and a ring compound path +//! under its fill rule, one circle per object as one undo step, the drawn circle inside where its +//! curves bulge, and the errors that leave the document as it was. + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; +use vectorcraft_geom::Point; + +use super::COMMAND; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn ids_of(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn object_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|_| n += 1); + n +} + +/// The center and radius of the live circle `id`. +fn circle(s: &Session, id: NodeId) -> (Point, f64) { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { live: Some(live), .. } => match live.as_ref() { + LiveShape::Ellipse { w, h, xf, .. } => { + assert!((w - h).abs() < 1e-9, "a circle, not an ellipse"); + (*xf * Point::new(w / 2.0, h / 2.0), w / 2.0) + } + other => panic!("not a live ellipse: {other:?}"), + }, + other => panic!("not a live shape: {other:?}"), + } +} + +/// The smallest drawn radius for a largest circle of radius `largest`: smaller by the curves' +/// bulge, and by the search's 0.02 pt. +fn least(largest: f64) -> f64 { + largest / (1.0 + super::CIRCLE_BULGE) - 0.02 +} + +/// The command on the selection fails with a message holding `want`, and the document is as it was. +fn refused(s: &mut Session, want: &str) { + let (undo, objects) = (undo_len(s), object_count(s)); + let e = s.execute(COMMAND, &json!({})).unwrap_err().to_string(); + assert!(e.contains(want), "{e}"); + assert_eq!((undo_len(s), object_count(s)), (undo, objects)); +} + +/// The circle in a square sits at its center and touches its sides, gets the current paint, goes +/// on top of the layer and is selected; one undo removes it. +#[test] +fn a_square_gets_the_circle_that_touches_its_sides() { + let mut s = session(); + let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()); + let (undo, objects) = (undo_len(&s), object_count(&s)); + let out = s.execute(COMMAND, &json!({})).unwrap(); + let id = id_of(&out); + let (center, r) = circle(&s, id); + assert!((center - Point::new(150.0, 150.0)).hypot() < 0.02 && r <= 50.0 + 1e-6 && r > least(50.0), "{center:?} {r}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![id]); + let d = &s.doc().unwrap().doc; + let parent = d.parent_of(sq).unwrap(); + assert_eq!(d.parent_of(id), Some(parent)); + assert_eq!(d.node(parent).unwrap().children().unwrap().last().map(|n| n.id), Some(id), "on top of the layer"); + // The current paint, as the rectangle drawn before got it. + let (n, r) = (d.node(id).unwrap(), d.node(sq).unwrap()); + assert_eq!((n.appearance.fill_paint(), n.appearance.stroke_paint()), (r.appearance.fill_paint(), r.appearance.stroke_paint())); + assert_eq!(undo_len(&s), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(object_count(&s), objects); +} + +/// The circle in an L sits in its corner, inside the shape, where the box's center is outside. +#[test] +fn a_concave_shape_gets_the_circle_in_its_corner() { + let mut s = session(); + let anchors = [(0, 0), (100, 0), (100, 30), (30, 30), (30, 100), (0, 100)].map(|(x, y)| json!({"x": x, "y": y})); + s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap(); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + let (center, r) = circle(&s, id); + let largest = 30.0 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2); + assert!(r <= largest + 1e-6 && r > least(largest), "{r}"); + assert!(center.x < 30.0 && center.y < 30.0, "{center:?}"); +} + +/// A compound path of two concentric circles: under even-odd the inner one is a hole, and the +/// circle lies in the ring beside it. Under nonzero it is a hole while the two circles turn +/// opposite ways, and with both turning the same way the circle fills the outer one. +#[test] +fn a_ring_compound_path_gets_a_circle_by_its_fill_rule() { + let mut s = session(); + let outer = id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap()); + let inner = id_of(&s.execute("shape.ellipse", &json!({"x": 160, "y": 160, "width": 80, "height": 80})).unwrap()); + select(&mut s, &[outer, inner]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let ring = Point::new(200.0, 200.0); + let cases = [("evenOdd", false, 70.0, 30.0), ("nonZero", false, 70.0, 30.0), ("nonZero", true, 0.0, 100.0), ("evenOdd", true, 70.0, 30.0)]; + for (rule, same_way, around, largest) in cases { + select(&mut s, &[compound]); + let both = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::>(); + s.execute("path.reverse", &json!({"ids": both, "reversed": true})).unwrap(); + if !same_way { + s.execute("path.reverse", &json!({"ids": [both[1]], "reversed": false})).unwrap(); + } + s.execute("path.setFillRule", &json!({"rule": rule, "ids": [compound.0]})).unwrap(); + select(&mut s, &[compound]); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + let (center, r) = circle(&s, id); + assert!(r > least(largest) && r < largest + 0.0003 * 140.0, "{rule} {same_way}: {r}"); + assert!(((center - ring).hypot() - around).abs() < 0.1, "{rule} {same_way}: {center:?}"); + } +} + +/// Each selected path gets its own circle, all as one undo step; a path of a compound path +/// selected on its own gets a circle of its own outline. +#[test] +fn each_selected_path_gets_a_circle_in_one_step() { + let mut s = session(); + let a = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap()); + let b = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 0, "width": 40, "height": 80})).unwrap()); + select(&mut s, &[a, b]); + let undo = undo_len(&s); + let ids = ids_of(&s.execute(COMMAND, &json!({})).unwrap()); + assert_eq!(ids.len(), 2); + assert_eq!(undo_len(&s), undo + 1); + let centers: Vec = ids.iter().map(|id| circle(&s, *id).0).collect(); + assert!(centers.iter().any(|c| c.x < 40.0) && centers.iter().any(|c| c.x > 100.0), "{centers:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[a, b]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let member = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap()[0].id; + select(&mut s, &[member]); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + let r = circle(&s, id).1; + assert!(r <= 20.0 + 1e-6 && r > least(20.0), "the member's own square: {r}"); +} + +/// The drawn circle stays inside a large square turned so that it touches the square's sides +/// where its curves bulge most past a true circle, about 20° from each axis. +#[test] +fn the_drawn_circle_stays_inside_where_its_curves_bulge() { + let mut s = session(); + let (center, half) = (Point::new(1200.0, 1200.0), 1000.0); + for degrees in [15.0_f64, 19.4, 25.0] { + let (sin, cos) = degrees.to_radians().sin_cos(); + let corner = |u: f64, v: f64| json!({"x": center.x + u * cos - v * sin, "y": center.y + u * sin + v * cos}); + let anchors = [(-half, -half), (half, -half), (half, half), (-half, half)].map(|(u, v)| corner(u, v)); + s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap(); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { + panic!("not a path"); + }; + for seg in path.to_bezpath().segments() { + for i in 0..=200 { + let p = vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 200.0) - center; + let (u, v) = (p.x * cos + p.y * sin, -p.x * sin + p.y * cos); + assert!(u.abs().max(v.abs()) <= half, "{degrees}°: ({u}, {v}) is outside the square"); + } + } + } +} + +/// An open path, an object that is not a path or compound path, a path that fills no area and an +/// empty selection are errors, and nothing is drawn. +#[test] +fn open_paths_other_objects_and_no_selection_are_refused() { + let mut s = session(); + assert!(s.execute(COMMAND, &json!({})).is_err(), "nothing selected"); + let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}]})).unwrap()); + select(&mut s, &[open]); + refused(&mut s, "is not a closed path or compound path"); + let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()); + select(&mut s, &[sq]); + let group = id_of(&s.execute("object.group", &json!({})).unwrap()); + select(&mut s, &[group]); + refused(&mut s, "is not a closed path or compound path"); + // One refused object leaves the other selected objects without a circle too. + select(&mut s, &[group, open]); + refused(&mut s, "is not a closed path or compound path"); + let flat = [(0, 300), (100, 300), (50, 300)].map(|(x, y)| json!({"x": x, "y": y})); + let flat = id_of(&s.execute("path.create", &json!({"anchors": flat, "closed": true})).unwrap()); + select(&mut s, &[flat]); + refused(&mut s, "fills no area"); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..fc152f8178 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -60,6 +60,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.pathtools.erase", "addon.pathtools.expandDashes", "addon.pathtools.extend", + "addon.pathtools.inscribedCircle", "addon.pathtools.inspect", "addon.pathtools.mergeEdge", "addon.pathtools.removeKeepShape", diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index d5fe994bed..58927fbb79 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -6,13 +6,15 @@ //! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes //! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]) or many circles //! joined to their neighbors ([`bridge_many`]), the common tangents of two convex outlines -//! ([`common_tangents`]), the Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch -//! two or three shapes ([`tangent_circles`]). +//! ([`common_tangents`]), the Parametric Shape Tool's shapes ([`shapes`]), the circles that touch +//! two or three shapes ([`tangent_circles`]) and the largest circle inside a shape +//! ([`inscribed_circle`]). mod bridge; mod crossings; mod dashes; mod extend; +mod inscribed; pub mod shapes; mod shared_edge; mod slide; @@ -33,6 +35,7 @@ pub use bridge::{ pub use crossings::{MAX_CROSSED_BY_SEGMENTS, MAX_CROSSING_SEGMENTS, Place, Work, crossings, crossings_on, crossings_on_within, insert_at}; pub use dashes::{DashSpec, Piece, divide_dashes}; pub use extend::{ExtendMode, extend_length_to, extend_open}; +pub use inscribed::{INSCRIBED_PRECISION, Inscribed, InscribedError, MAX_INSCRIBED_EDGES, inscribed_circle}; pub use shared_edge::{ COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at, }; diff --git a/crates/pathops/src/addons/pathtools/inscribed.rs b/crates/pathops/src/addons/pathtools/inscribed.rs new file mode 100644 index 0000000000..285132acba --- /dev/null +++ b/crates/pathops/src/addons/pathtools/inscribed.rs @@ -0,0 +1,245 @@ +//! Add Inscribed Circle: the largest circle inside a filled outline, the center of which is the +//! outline's [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). +//! +//! The outline is first resolved under its fill rule into simple contours (outer contours and +//! holes, as [`crate::try_normalize`] resolves them, narrow ones kept), so overlapping and self-crossing subpaths count as the area they fill +//! and only real edges bound the circle. The contours are flattened, and square cells covering +//! their box are searched best first: a cell's center lies some distance inside the outline, and no +//! point of the cell lies more than half the cell's diagonal farther in, so a cell that cannot beat +//! the best center found by more than the precision is not split. The radius is then measured from +//! the center to the curves themselves. + +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +use kurbo::{ParamCurveNearest, Point, Rect, Shape}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{FillRule, PathData, PathEl}; + +use crate::boolean::{Tidy, fill_bezpath, normalize_bez}; + +#[cfg(test)] +mod tests; + +#[cfg(test)] +thread_local! { + /// The distances from a point to an edge that the last [`search`] on this thread measured. + static MEASURED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How close to the largest circle's radius the search gets, in points, for outlines whose box is +/// at least 10 pt across; a smaller box gets a thousandth of its narrower side. +pub const INSCRIBED_PRECISION: f64 = 0.01; +/// Most straight edges the flattened outline may have. +pub const MAX_INSCRIBED_EDGES: usize = 1 << 18; +/// Most distances from a point to an edge that one search measures. +const MAX_WORK: usize = 1 << 27; +/// Most cells the box is first cut into. +const MAX_FIRST_CELLS: f64 = 4096.0; + +/// The largest circle inside an outline: its center and radius. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Inscribed { + pub center: Point, + pub radius: f64, +} + +/// Why [`inscribed_circle`] found no circle. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InscribedError { + /// The outline fills no area. + NoArea, + /// The outline could not be resolved, has more than [`MAX_INSCRIBED_EDGES`] edges, or the + /// search would measure more than its limit. + TooComplex, +} + +/// The largest circle inside the area that `path` fills under `rule`, within twice +/// [`INSCRIBED_PRECISION`] of the largest radius: the search's precision and the flattening, at +/// half of it. A curve whose control polygon is longer than 83,886 pt is flattened more coarsely +/// ([`vectorcraft_geom::flatten`]), and the circle can be smaller by as much. Holes and gaps +/// narrower than 1e-6 pt close up, as in the other path operations. Open subpaths count as closed, +/// as when they are filled. +pub fn inscribed_circle(path: &PathData, rule: FillRule) -> Result { + let filled = fill_bezpath(path); + let b = filled.bounding_box(); + if !(b.width() > 0.0 && b.height() > 0.0 && b.is_finite()) { + return Err(InscribedError::NoArea); + } + let precision = INSCRIBED_PRECISION.min(b.width().min(b.height()) / 1000.0); + // Every contour of the fill's boundary counts, however narrow, down to the sweep's tolerance + // (1e-6 pt; [`crate::boolean::eps_for`]): a hairline hole is still outside the fill. Curves the + // sweep split are rebuilt from the input's own. + let contours = normalize_bez(&filled, rule).map_err(|_| InscribedError::TooComplex)?; + let tidy = Tidy::keeping(precision, [&filled]); + let mut curves = kurbo::BezPath::new(); + for c in contours.contours() { + curves.extend(tidy.repair(&c.path)); + } + let b = curves.bounding_box(); + if !(b.width() > 0.0 && b.height() > 0.0 && b.is_finite()) { + return Err(InscribedError::NoArea); + } + let edges = edges(&curves, precision / 2.0)?; + let center = search(&edges, b, precision, MAX_WORK)?; + // The circle touches the nearest curve, whatever the flattening moved. + let radius = curves.segments().map(|s| s.nearest(center, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt(); + if !(radius.is_finite() && radius > 0.0) || !fill_contains(&curves, FillRule::NonZero, center) { + return Err(InscribedError::NoArea); + } + Ok(Inscribed { center, radius }) +} + +/// The straight edges of `curves` flattened to within `tolerance`, each subpath closed. +fn edges(curves: &kurbo::BezPath, tolerance: f64) -> Result, InscribedError> { + let mut out = vec![]; + let (mut start, mut last) = (None, None); + let close = |out: &mut Vec<(Point, Point)>, start: Option, last: Option| { + if let (Some(a), Some(b)) = (last, start) + && a != b + { + out.push((a, b)); + } + }; + let mut over = false; + vectorcraft_geom::flatten(curves.iter(), tolerance, |el| { + if over { + return; + } + match el { + PathEl::MoveTo(p) => { + close(&mut out, start, last); + (start, last) = (Some(p), Some(p)); + } + PathEl::LineTo(p) => { + if let Some(a) = last { + out.push((a, p)); + } + last = Some(p); + } + PathEl::ClosePath => { + close(&mut out, start, last); + last = start; + } + _ => {} + } + over = out.len() > MAX_INSCRIBED_EDGES; + }); + close(&mut out, start, last); + if over || out.len() > MAX_INSCRIBED_EDGES { + return Err(InscribedError::TooComplex); + } + Ok(out) +} + +/// How far `p` lies inside the closed `edges` (nonzero winding): the distance to the nearest edge, +/// negative outside. +fn inside(edges: &[(Point, Point)], p: Point) -> f64 { + let mut winding = 0; + let mut nearest = f64::INFINITY; + for &(a, b) in edges { + if (a.y <= p.y) != (b.y <= p.y) { + let side = (b - a).cross(p - a); + if b.y > a.y && side > 0.0 { + winding += 1; + } else if b.y <= a.y && side < 0.0 { + winding -= 1; + } + } + nearest = nearest.min(distance_sq_to_segment(p, a, b)); + } + let d = nearest.sqrt(); + if winding != 0 { d } else { -d } +} + +fn distance_sq_to_segment(p: Point, a: Point, b: Point) -> f64 { + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + (p - (a + ab * t)).hypot2() +} + +/// A square cell of the search: its center, half its side, how far its center lies inside the +/// outline, and the most any of its points can. +#[derive(Clone, Copy)] +struct Cell { + center: Point, + half: f64, + inside: f64, + best: f64, +} + +impl Cell { + fn new(edges: &[(Point, Point)], center: Point, half: f64) -> Self { + let inside = inside(edges, center); + Self { center, half, inside, best: inside + half * std::f64::consts::SQRT_2 } + } +} + +impl PartialEq for Cell { + fn eq(&self, other: &Self) -> bool { + self.cmp(other) == Ordering::Equal + } +} + +impl Eq for Cell {} + +impl PartialOrd for Cell { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Cell { + fn cmp(&self, other: &Self) -> Ordering { + self.best.total_cmp(&other.best) + } +} + +/// The point of the closed `edges`, inside box `b`, farthest from every edge, within `precision`, +/// measuring at most about `limit` distances from a point to an edge. +fn search(edges: &[(Point, Point)], b: Rect, precision: f64, limit: usize) -> Result { + // Square cells as wide as the box's narrower side, or wider when that would make more than + // `first` along the box or in all: at most MAX_FIRST_CELLS, and at most a quarter of the work + // limit, so the first cells take at most about three quarters of it. + let first = MAX_FIRST_CELLS.min((limit / edges.len().max(1) / 4) as f64).max(1.0); + let size = b.width().min(b.height()).max((b.area() / first).sqrt()).max(b.width().max(b.height()) / first); + let (cols, rows) = ((b.width() / size).ceil() as usize, (b.height() / size).ceil() as usize); + let mut work = 0usize; + let measure = |work: &mut usize, center: Point, half: f64| { + *work = work.saturating_add(edges.len()); + #[cfg(test)] + MEASURED.with(|m| m.set(*work)); + Cell::new(edges, center, half) + }; + let mut best = measure(&mut work, b.center(), 0.0); + let mut cells = BinaryHeap::new(); + for row in 0..rows { + for col in 0..cols { + if work > limit { + return Err(InscribedError::TooComplex); + } + let at = Point::new(b.x0 + (col as f64 + 0.5) * size, b.y0 + (row as f64 + 0.5) * size); + cells.push(measure(&mut work, at, size / 2.0)); + } + } + while let Some(cell) = cells.pop() { + if cell.inside > best.inside { + best = cell; + } + if cell.best - best.inside <= precision { + break; + } + if work > limit { + return Err(InscribedError::TooComplex); + } + let h = cell.half / 2.0; + for (dx, dy) in [(-h, -h), (h, -h), (-h, h), (h, h)] { + cells.push(measure(&mut work, cell.center + (dx, dy), h)); + } + } + if best.inside <= 0.0 { + return Err(InscribedError::NoArea); + } + Ok(best.center) +} diff --git a/crates/pathops/src/addons/pathtools/inscribed/tests.rs b/crates/pathops/src/addons/pathtools/inscribed/tests.rs new file mode 100644 index 0000000000..50f2d103d3 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/inscribed/tests.rs @@ -0,0 +1,140 @@ +use kurbo::{Point, Rect}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{Anchor, FillRule, PathData, SubPath, shapes}; + +use super::*; + +fn polygon(pts: &[(f64, f64)]) -> PathData { + PathData::new(vec![SubPath::new(pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)]) +} + +fn circle(x: f64, y: f64, r: f64) -> SubPath { + shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r)).subpaths.remove(0) +} + +/// Points around the circle `c`, a little inside its edge. +fn rim(c: Inscribed) -> impl Iterator { + (0..360).map(move |i| { + let a = (i as f64).to_radians(); + c.center + kurbo::Vec2::new(a.cos(), a.sin()) * (c.radius - 1e-6) + }) +} + +/// The circle lies in the filled area and is within twice the precision of `largest`, which may +/// be `slack` too small: a circle of four curves bulges up to 0.03% past a true circle. +fn holds_within(path: &PathData, rule: FillRule, c: Inscribed, largest: f64, slack: f64) { + let bp = path.to_bezpath(); + assert!(rim(c).all(|p| fill_contains(&bp, rule, p)), "{c:?} reaches outside the fill"); + assert!(c.radius <= largest + slack + 1e-6 && c.radius >= largest - 2.0 * INSCRIBED_PRECISION, "{c:?}, largest {largest}"); +} + +fn holds(path: &PathData, rule: FillRule, c: Inscribed, largest: f64) { + holds_within(path, rule, c, largest, 0.0); +} + +#[test] +fn a_square_holds_the_circle_at_its_center() { + let sq = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let c = inscribed_circle(&sq, FillRule::NonZero).unwrap(); + holds(&sq, FillRule::NonZero, c, 50.0); + assert!((c.center - Point::new(50.0, 50.0)).hypot() < 2.0 * INSCRIBED_PRECISION, "{c:?}"); +} + +#[test] +fn a_concave_shape_holds_the_circle_in_its_corner() { + // An L whose arms are 30 wide: the box's center (50, 50) is outside it. The largest circle + // touches the two outer edges and the inner corner (30, 30): c = √2 (30 − c). + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); + let c = inscribed_circle(&l, FillRule::NonZero).unwrap(); + let largest = 30.0 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2); + holds(&l, FillRule::NonZero, c, largest); +} + +#[test] +fn a_ring_holds_the_circle_beside_its_hole_under_even_odd() { + let ring = PathData::new(vec![circle(0.0, 0.0, 100.0), circle(0.0, 0.0, 40.0)]); + let c = inscribed_circle(&ring, FillRule::EvenOdd).unwrap(); + holds_within(&ring, FillRule::EvenOdd, c, 30.0, 0.0003 * 140.0); + assert!((c.center.to_vec2().hypot() - 70.0).abs() < 0.1, "{c:?}"); + // Both subpaths turn the same way, so under nonzero the inner one fills in and is no hole. + let c = inscribed_circle(&ring, FillRule::NonZero).unwrap(); + holds_within(&ring, FillRule::NonZero, c, 100.0, 0.0003 * 100.0); +} + +#[test] +fn overlapping_subpaths_count_as_the_area_they_fill() { + // Two squares overlapping by half: under nonzero they fill one 150 × 100 rectangle, and the + // edges inside it do not bound the circle. + let a = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let b = polygon(&[(50.0, 0.0), (150.0, 0.0), (150.0, 100.0), (50.0, 100.0)]); + let both = PathData::new(a.subpaths.into_iter().chain(b.subpaths).collect()); + let c = inscribed_circle(&both, FillRule::NonZero).unwrap(); + holds(&both, FillRule::NonZero, c, 50.0); +} + +#[test] +fn a_small_shape_is_measured_to_its_own_scale() { + // The L of the concave test, a thousandth of its size. + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)].map(|(x, y)| (x / 1000.0, y / 1000.0))); + let c = inscribed_circle(&l, FillRule::NonZero).unwrap(); + let largest = 0.03 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2); + assert!(c.radius <= largest + 1e-9 && c.radius > largest * 0.99, "{c:?}, largest {largest}"); +} + +#[test] +fn a_shape_narrower_than_the_default_precision_gets_a_circle() { + // 0.005 pt square: resolved at 0.01 pt it would be dropped as a sliver. + let sq = polygon(&[(0.0, 0.0), (0.005, 0.0), (0.005, 0.005), (0.0, 0.005)]); + let c = inscribed_circle(&sq, FillRule::NonZero).unwrap(); + assert!(c.radius <= 0.0025 + 1e-12 && c.radius > 0.0025 * 0.99, "{c:?}"); +} + +#[test] +fn a_hairline_hole_bounds_the_circle() { + // A 100 pt square with a hole 0.001 pt wide down its middle: the circle stays on one side. + let sq = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let slit = polygon(&[(49.9995, 10.0), (50.0005, 10.0), (50.0005, 90.0), (49.9995, 90.0)]); + let both = PathData::new(sq.subpaths.into_iter().chain(slit.subpaths).collect()); + let c = inscribed_circle(&both, FillRule::EvenOdd).unwrap(); + assert!((c.center.x - 50.0).abs() >= c.radius - 2.0 * INSCRIBED_PRECISION, "{c:?}"); + assert!(c.radius < 30.0, "{c:?}"); +} + +#[test] +fn a_long_thin_shape_is_refused_without_measuring_past_the_work_limit() { + // A strip 5,000 × 1 whose top edge has 5,000 pieces: cut into cells as wide as it is high, + // the first cells alone would measure 5,000 times every edge. + let n = 5000; + let top: Vec<(f64, f64)> = (0..=n).map(|i| (i as f64, 0.0)).collect(); + let pts: Vec<(f64, f64)> = top.into_iter().chain([(n as f64, 1.0), (0.0, 1.0)]).collect(); + let e = edges(&polygon(&pts).to_bezpath(), 0.005).unwrap(); + let limit = 100 * e.len(); + assert_eq!(search(&e, Rect::new(0.0, 0.0, n as f64, 1.0), 0.01, limit), Err(InscribedError::TooComplex)); + // Past the limit by at most the four cells of one split. + let measured = MEASURED.with(std::cell::Cell::get); + assert!(measured <= limit + 4 * e.len(), "{measured} measured, limit {limit}"); +} + +#[test] +fn an_outline_with_too_many_edges_is_too_complex() { + let zigzag: Vec<(f64, f64)> = (0..=MAX_INSCRIBED_EDGES).map(|i| (i as f64, (i % 2) as f64)).chain([(0.0, -10.0)]).collect(); + let bp = polygon(&zigzag).to_bezpath(); + assert_eq!(edges(&bp, 0.005), Err(InscribedError::TooComplex)); + assert_eq!(edges(&polygon(&zigzag[..1000]).to_bezpath(), 0.005).map(|e| e.len()), Ok(1000)); +} + +#[test] +fn a_search_past_its_work_limit_is_too_complex() { + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); + let e = edges(&l.to_bezpath(), 0.005).unwrap(); + let b = Rect::new(0.0, 0.0, 100.0, 100.0); + assert!(search(&e, b, 0.01, MAX_WORK).is_ok()); + assert_eq!(search(&e, b, 0.01, 20 * e.len()), Err(InscribedError::TooComplex)); +} + +#[test] +fn a_shape_with_no_area_has_no_circle() { + let flat = polygon(&[(0.0, 0.0), (100.0, 0.0), (50.0, 0.0)]); + assert_eq!(inscribed_circle(&flat, FillRule::NonZero), Err(InscribedError::NoArea)); + assert_eq!(inscribed_circle(&PathData::default(), FillRule::NonZero), Err(InscribedError::NoArea)); +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 3e7b864c05..dd33370568 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,6 +1,6 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), //! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into -//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle… and Add Bounding Circle…; the Anchor Inspector panel (the selected +//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and @@ -87,6 +87,7 @@ pub fn menu() -> Vec { Item::Cmd("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), Item::Cmd("Add Bounding Rectangle…", BOUNDING_RECTANGLE, json!({ "offset": 0, "each": false })), Item::Cmd("Add Bounding Circle…", BOUNDING_CIRCLE, json!({ "offset": 0, "each": false })), + Item::Cmd("Add Inscribed Circle", "addon.pathtools.inscribedCircle", json!({})), ] } diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..242821d4bb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14816,6 +14816,24 @@ Commands: ```json {"name":"run_command","arguments":{"command":"addon.pathtools.boundingCircle","params":{"offset":2}}} ``` +- `addon.pathtools.inscribedCircle {}` draws the largest live circle inside each selected closed path or compound + path (Object › Plug-ins › Path Precision Tools › Add Inscribed Circle, #6966). Its center is the shape's + [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). A path of a compound path + selected on its own counts as a path. The circle lies in the area the shape fills under its fill rule: holes and the + overlaps of crossing subpaths count as the fill shows them, and strokes and effects are left out. The command + flattens the outline to within 0.005 pt and searches square cells best first, measuring the radius from the center + to the curves, so its radius is within 0.02 pt of the largest. A shape whose + box is less than 10 pt across on its narrower side is measured to a thousandth of that side instead. A curve whose + control polygon is longer than 83,886 pt is flattened more coarsely, and the circle can be smaller by as much. The + drawn circle's four curves reach up to 0.03% of its radius past a true circle, so the command draws it that much + smaller, and it stays inside where it touches the shape. Narrow holes count; holes and gaps narrower than 1e-6 pt close up, as + in the other path operations. The circles get the current paint and go on top of the current layer, or of the isolated group, as other new art does. + The new circles are selected, and one undo removes them all. It is an error, with the document unchanged, when a selected + object is not a closed path or compound path ("object N is not a closed path or compound path"; an open path has no + inside), when it fills no area ("object N fills no area"), and when its outline has more than 262,144 straight + pieces once flattened, or the search measures more than 134,217,728 distances from a point to an edge ("object N is + too complex to measure"). + → `{id: the first circle, ids}` A parametric shape is an ordinary path. It keeps its numbers, with a fingerprint of the outline they drew, in one entry of its object data (`vc-pathtools-shape`, as `document.node` lists `attrs.data`), which SVG export leaves out; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..2bd4e10a02 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2989,6 +2989,10 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Pre A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle (`addon.pathtools.boundingRectangle`) draws a live rectangle on the selection's geometric bounding box, and Add Bounding Circle (`addon.pathtools.boundingCircle`) draws the [smallest enclosing circle](https://en.wikipedia.org/wiki/Smallest-circle_problem) of the selected outlines, with curves flattened to within 0.01 pt and the radius 0.01 pt larger, so the circle holds the curves. A curve is split into 1,024 pieces at most. One command makes at most 1,048,576 splits at any depth, and with `each` every shape gets an equal share. A shape that has used up its share splits each further curve into at most 8 pieces, with at most 7,340,032 more splits shared the same way (8,388,608 in all), and then counts each further curve whole. A piece that still bends more counts by the hull of its control points cut down to its bounding box, which can make the circle larger than the smallest one. Before the 0.01 pt is added, the circle around a circle of four curves is less than 0.3% larger when each curve is split into 8 pieces, and about 14% larger when each counts whole. Both use the current paint, go on top of the current layer or the isolated group, and are one undo step; shapes with no size are skipped (#6966). The commands take `each` (one shape per object) and `offset`, and the menu items Add Bounding Rectangle… and Add Bounding Circle… open a dialog with Offset, One per Object and Preview. Tests: `shapes::tests` in `vectorcraft-geom` (`enclosing`, `convex_hull`), `cmd::addons::pathtools::bounding::tests` in `vectorcraft-engine` and `addons::pathtools::tests` in `vectorcraft-ui-egui` (`add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object`). Commands: `docs/mcp.md` › Path Precision Tools add-on. +## Path Precision Tools add-on: Add Inscribed Circle (2026-11-22) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Inscribed Circle (`addon.pathtools.inscribedCircle`) draws the largest live circle inside each selected closed path or compound path, centered on the shape's [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). The rest is VectorCraft's own: the shape is first resolved under its fill rule into outer contours and holes, flattened to within 0.005 pt and searched in square cells best first, and the radius is measured from the center to the curves, within 0.02 pt of the largest (a shape less than 10 pt across is measured to a thousandth of its narrower side), and the circle is drawn up to 0.03% smaller, by as much as its four curves reach past a true circle, so it stays inside. The circles use the current paint, go on top of the current layer or the isolated group, and are one undo step (#6966). Open paths, other objects, shapes that fill no area, and outlines past 262,144 flattened pieces or the search's work limit are errors. Tests: `addons::pathtools::inscribed::tests` in `vectorcraft-pathops` (a square, a concave shape, a ring under both fill rules, overlapping subpaths, a small shape, a shape narrower than 0.01 pt, a hairline hole, the edge and work limits, a long thin shape, no area) and `cmd::addons::pathtools::inscribed::tests` in `vectorcraft-engine`. Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Path Precision Tools add-on: Expand Dashes into Paths (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns the dashed stroke of each selected path and compound path into separate open paths, one per dash, for cutters and plotters that need the centre lines rather than Outline Stroke's filled outlines. The dashes are laid out by the renderer's own dash code, so they match what the canvas draws: the dash pattern, its offset and Align Dashes to Corners and Path Ends, a dash running on through the start of a closed path, a dash all the way round staying closed, and under a round or projecting cap each dot (a dash of no length) as a path on its point. Each dash keeps the path's appearance with the top stroke's dashes and arrowheads off; the path's fills stay on it, below its dashes; a compound path's dashes are plain paths. One undo step; the dashes are selected; at most 100000 (more, or a pattern too fine to draw, is refused). Tests: `expand_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (the stroke kept with dashes off, the offset, one undo step, the fill kept below, dashes centred on corners when aligned, dots under round and butt caps, compound paths, refusals and the piece cap), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..1926538a88 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -559,6 +559,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… draw a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, from a dialog with Offset, One per Object (a shape around each object instead of one around the whole selection) and Preview; one undo step | done | `addon.pathtools.boundingRectangle` and `addon.pathtools.boundingCircle` (in `crates/engine/src/cmd/addons/pathtools/bounding.rs`, the circle in `crates/geom/src/shapes.rs`, `enclosing_circle`; the dialog is the command dialog, `crates/ui-egui/src/dialogs/command.rs`) and their tests, with the menu items' test `add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | From 210fc900d54009ee744dc11901b5a2eb9fa3dca7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:47:10 -0800 Subject: [PATCH 39/78] Tests: Cmd on a lone object and under a layer effect Adds tests for two Select Behind rules: a Cmd press on a selected object with nothing behind it is lent to Direct Selection, and a layer effect that moves the art moves where a Cmd press selects behind, in Preview after Outline view too, while a drop shadow is not hit. The hover's lend decision key is a named struct. The pointer_gesture paragraph in docs/mcp.md is wrapped to the file's width, and the Temporary tools line in docs/target-app-parity.md cites the default keyboard shortcuts page. --- crates/engine/src/tests/draw2.rs | 53 ++++++++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 49 +++++++++++++++++++---------- docs/mcp.md | 13 ++++---- docs/target-app-parity.md | 2 +- 4 files changed, 93 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 3ffd8e4576..c497fed246 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4843,6 +4843,59 @@ fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() { assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); } +#[test] +fn a_cmd_press_on_a_lone_selected_object_is_lent() { + // With nothing behind the selected object, there is nothing to select behind: Direct Selection + // takes the press. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let lone = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [lone.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); +} + +#[test] +fn a_layer_effect_that_moves_art_moves_where_a_cmd_press_selects_behind() { + // A layer effect draws the selected object 250 pt to the right of its path, over the object + // behind it: a Cmd press where it is drawn selects behind. A drop shadow there is not hit, so + // the press is lent. Outline view hits the path where it is, and Preview afterwards still finds + // the moved art. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let outline = ViewInfo { outline: true, ..view() }; + let drawn = Point::new(450.0, 200.0); + // On both rectangles' top edges, which Outline view hits, away from the box's handles. + let path = Point::new(170.0, 150.0); + for effect in ["distort.transform", "stylize.dropShadow"] { + let mut s = session(); + let back = rect(&mut s, 50.0, 150.0, 700.0, 300.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + let layer = s.doc().unwrap().doc.layers[0].id; + let params = if effect == "distort.transform" { json!({"moveH": 250}) } else { json!({"x": 250, "y": 0, "blur": 0}) }; + s.execute("effect.apply", &json!({"effect": effect, "params": params, "ids": [layer.0], "item": null})).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + // The back rectangle is drawn moved too, so it is under both points. + if effect == "distort.transform" { + assert_eq!(s.hover_tool_at(Some(path), &cmd, outline), "selection", "Outline view: on the path"); + assert_eq!(s.hover_tool_at(Some(drawn), &cmd, v), "selection", "Preview: where the effect draws it"); + s.pointer(&PointerEvent::new(PointerKind::Down, drawn.x, drawn.y).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, drawn.x, drawn.y).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); + } else { + assert_eq!(s.hover_tool_at(Some(drawn), &cmd, v), "directSelection", "on the shadow"); + } + } +} + #[test] fn repeated_cmd_clicks_select_behind_a_group_whose_member_is_selected() { // The first Cmd-click on an unselected group lends Direct Selection, which selects the path diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index d9c2e6e4dc..736b99617a 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -10,13 +10,24 @@ use vectorcraft_tools::{Action, Cursor, ImeSurrounding, Mods, Overlay, PointerEv use crate::{EngineError, Prefs, Result, Session}; -/// What a hover's lend decision holds for ([`Session::hover_tool_at`]): the active document's uid -/// and revision, the active tool, the keys, the selection tools chosen last and the preferences a -/// press's hit test reads (Command Click to Select Objects Behind, Object Selection by Path Only, -/// Type Object Selection by Path Only, Selection Tolerance, anchor Size; Use Preview Bounds, -/// Measure Type by Glyph Bounds, Show Handles When Multiple Anchors Are Selected). -pub(crate) type HoverKey = - (Option<(u64, u64)>, &'static str, Mods, (Option<&'static str>, Option<&'static str>), ((bool, bool, bool, f64, u32), (bool, bool, bool))); +/// What a hover's lend decision holds for ([`Session::hover_tool_at`]). +#[derive(Clone, Copy, PartialEq)] +pub(crate) struct HoverKey { + /// The active document's uid and revision, which moves with the selection. + doc: Option<(u64, u64)>, + tool: &'static str, + mods: Mods, + /// The selection tool and the part selection tool chosen last. + last_tools: (Option<&'static str>, Option<&'static str>), + ctrl_click_selects_behind: bool, + object_selection_by_path_only: bool, + type_selection_by_path_only: bool, + selection_tolerance: f64, + anchor_size: u32, + use_preview_bounds: bool, + type_glyph_bounds: bool, + show_handles_multiple_anchors: bool, +} /// The tool whose radius is General › Corner Radius. const ROUNDED_RECTANGLE: &str = "roundedRectangle"; @@ -333,16 +344,20 @@ impl Session { /// and the preferences a press's hit test reads. fn hover_key(&self, mods: &Mods) -> HoverKey { let p = &self.prefs; - let picks = - (p.ctrl_click_selects_behind, p.object_selection_by_path_only, p.type_selection_by_path_only, p.selection_tolerance, p.anchor_size); - let bounds = (p.use_preview_bounds, p.type_glyph_bounds, p.show_handles_multiple_anchors); - ( - self.active().map(|d| (d.uid, d.revision)), - self.tool.id(), - *mods, - (self.last_selection_tool, self.last_part_selection_tool), - (picks, bounds), - ) + HoverKey { + doc: self.active().map(|d| (d.uid, d.revision)), + tool: self.tool.id(), + mods: *mods, + last_tools: (self.last_selection_tool, self.last_part_selection_tool), + ctrl_click_selects_behind: p.ctrl_click_selects_behind, + object_selection_by_path_only: p.object_selection_by_path_only, + type_selection_by_path_only: p.type_selection_by_path_only, + selection_tolerance: p.selection_tolerance, + anchor_size: p.anchor_size, + use_preview_bounds: p.use_preview_bounds, + type_glyph_bounds: p.type_glyph_bounds, + show_handles_multiple_anchors: p.show_handles_multiple_anchors, + } } /// The tool whose marks and widgets the canvas draws this frame with `mods` held and the diff --git a/docs/mcp.md b/docs/mcp.md index 4f3c98abb7..afa53faaa8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7082,12 +7082,13 @@ macOS, Ctrl elsewhere), drags with the selection tool chosen last (`select_tool` Curvature and anchor tools until one is chosen; the release gives the tool back as it was, so the Pen goes on drawing the path it had begun while that stays selected. With Direct Selection or Group Selection, `mods.cmd` drags with the Selection tool (with Direct Selection and `mods.alt` held too, with Group Selection). With the Selection tool, it drags -with Direct Selection or Group Selection, whichever was chosen last -(Direct Selection until one is), except where the press lands on a selected object, or on a group holding a selected -member, with another object under the pointer, away from its anchors, direction handles, mesh points, blend spine and -the bounding box's handles and rotate zones, while `ctrlClickSelectsBehind` is on: there the Selection tool keeps the press and selects the -object behind. A double-click or triple-click made with Cmd still held after Cmd-clicks goes to the tool the clicks went -to, and one that follows a Cmd-click selecting behind keeps what that click selected, without isolating or editing. Its reply's `tool` is the tool given back. +with Direct Selection or Group Selection, whichever was chosen last (Direct Selection until one is), except where the +press lands on a selected object, or on a group holding a selected member, with another object under the pointer, away +from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, while +`ctrlClickSelectsBehind` is on: there the Selection tool keeps the press and selects the object behind. A double-click +or triple-click made with Cmd still held after Cmd-clicks goes to the tool the clicks went to, and one that follows a +Cmd-click selecting behind keeps what that click selected, without isolating or editing. Its reply's `tool` is the tool +given back. `tool.selectLastSelection` (Select Last Selection Tool, `{}`) chooses the selection tool chosen last, as Ctrl+` does on Windows and Linux ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 817e79d3ac..f70d0f6c0f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1523,7 +1523,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Composition's leading-space reduction stays along the line when a character rotates. An opening bracket trimmed by Line-end Punctuation Half Width Mojikumi keeps that placement under Character Rotation; its turning point follows the composition adjustment, and removing the rotation keeps the trim. Scores and estimates are unchanged. A character rotated near or at a quarter turn follows a Touch Type drag across its line as well as along it: baseline shift moves a character up from its line at any rotation, and the character turns about its shifted pen position. Right-to-left characters can also move along their line when a preceding logical character is on that line. Positive `text.touchType` `dx` follows reading order, toward the left in horizontal right-to-left text; the first logical character still moves only up and down. These direction rules are VectorCraft's choices; the public Touch Type page describes moving a character without specifying this case. Scores and estimates are unchanged. - - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). With the Selection tool, Cmd lends Direct Selection or Group Selection, whichever was chosen last, until the key is released; with Group Selection it lends the Selection tool. A Cmd press on a selected object, or on a group holding a selected member, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, keeps Select Behind while Command Click to Select Objects Behind is on (#5970, #6583). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. A single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses that tool only until the key is let go, and the tool active before comes back (after a drag in progress ends); a quicker press chooses the tool for good. This is VectorCraft's own rule and its own threshold, and General › Hold a Tool Shortcut to Use the Tool Temporarily (`holdToolKeys`, on by default) turns it off. + - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). With the Selection tool, Cmd lends Direct Selection or Group Selection, whichever was chosen last, until the key is released; with Group Selection it lends the Selection tool. A Cmd press on a selected object, or on a group holding a selected member, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, keeps Select Behind while Command Click to Select Objects Behind is on, as "Select behind an object" (Ctrl+click twice) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists (#5970, #6583). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. A single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses that tool only until the key is let go, and the tool active before comes back (after a drag in progress ends); a quicker press chooses the tool for good. This is VectorCraft's own rule and its own threshold, and General › Hold a Tool Shortcut to Use the Tool Temporarily (`holdToolKeys`, on by default) turns it off. Space held while the Zoom tool drags a marquee moves the marquee and keeps its size ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). When Space is let go, the drag sizes the marquee again from where it moved to. A Space+Shift drag rotates the view whatever the tool, as a Rotate View tool drag does, and Shift does not round the angle to 15°. While the Type tool edits text, Space types a space: held, it does not show the hand, pan or rotate the view, and Cmd+Space still zooms ([the help page](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the Spacebar as the Hand tool when not in text-edit mode). Test: `canvas::tests::space_types_a_space_while_editing_text_and_does_not_pan`. From 70a56fb5be73bf73c2d72be4dd04e4e7b9a90532 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:40:39 -0800 Subject: [PATCH 40/78] Path Precision Tools: Add Inscribed Circle bounds its work and memory - The searches for all the selected objects share one limit of 134,217,728 distances from a point to an edge, as Add Bounding Circle shares its splits, and each cell is measured only when the limit has room for it. One search keeps at most 1,048,576 cells waiting. The pathops crate adds inscribed_circle_within for a shared budget. - The search stops once its best center is within the precision of half the box's narrower side, so a long rectangle ends at its first cells, and cells that cannot beat the best center are no longer queued. - A fill much smaller than the precision still gets a circle: the search keeps splitting until it finds a center inside the outline. - The precision also follows the box of the area the fill rule leaves. - Flattening stops at the first curve past the edge limit. An outline that flattening closes up, or whose center lands outside the curves, is flattened up to four times, 16 times finer each time; one it still cannot resolve is too complex to measure, not empty. Areas are summed from each contour's own first point. - An outline with more than 262,144 anchors in its filled subpaths is refused before it is resolved. - A selected layer is refused like any other object that is not a path, and inside an isolated compound path the circles join it, as Tangent Circle's do. - The menu item uses a named constant, and a UI test checks that it runs the command with no dialog and selects a new live circle in each selected shape, as one undo step. - The params text and docs say that the 0.02 pt bound holds before the circle is drawn 0.03% smaller, that a shape under 10 pt across is measured to a five-hundredth of its narrower side, when long curves are flattened more coarsely, and that edges can move by 1e-6 pt as in the other path operations. --- .../src/cmd/addons/pathtools/inscribed.rs | 15 +- .../cmd/addons/pathtools/inscribed/tests.rs | 18 ++ crates/pathops/src/addons/pathtools.rs | 5 +- .../pathops/src/addons/pathtools/inscribed.rs | 210 ++++++++++++++---- .../src/addons/pathtools/inscribed/tests.rs | 180 ++++++++++++++- crates/ui-egui/src/addons/pathtools.rs | 4 +- crates/ui-egui/src/addons/pathtools/tests.rs | 38 ++++ docs/mcp.md | 30 ++- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 10 files changed, 436 insertions(+), 68 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/inscribed.rs b/crates/engine/src/cmd/addons/pathtools/inscribed.rs index 2e016f23a7..e240fdf43d 100644 --- a/crates/engine/src/cmd/addons/pathtools/inscribed.rs +++ b/crates/engine/src/cmd/addons/pathtools/inscribed.rs @@ -29,7 +29,7 @@ pub(super) fn specs() -> Vec { "Add Inscribed Circle", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{} draw the largest live circle inside each selected closed path or compound path (a path of a compound path selected on its own counts as a path): the circle lies in the area the path fills under its fill rule, so holes and the overlaps of crossing subpaths count as the fill shows them, and its radius is within 0.02 pt of the largest (for a shape at least 10 pt across; a smaller one is measured to a thousandth of its narrower side; a curve whose control polygon is longer than 83,886 pt is flattened more coarsely, and the circle can be smaller by as much). The drawn circle's four curves reach up to 0.03% of its radius past a true circle, so it is drawn that much smaller and stays inside where it touches. Strokes and effects are left out. The circles get the current paint and go on top of the current layer or of the isolated group, as other new art; they are selected; one undo step. It is an error, with the document unchanged, when a selected object is not a closed path or compound path (\"object N is not a closed path or compound path\"; an open path has no inside), when it fills no area (\"object N fills no area\"), and when its outline has more than 262,144 straight pieces once flattened or its search goes past its limit (\"object N is too complex to measure\") → {id: the first circle, ids}", + "{} draw the largest live circle inside each selected closed path or compound path (a path of a compound path selected on its own counts as a path): the circle lies in the area the path fills under its fill rule, so holes and the overlaps of crossing subpaths count as the fill shows them, and before it is drawn its radius is within 0.02 pt of the largest (when the filled area's box is at least 10 pt across on its narrower side; for a smaller one, within a five-hundredth of that side; a curve whose control polygon is longer than 4096² times the flattening tolerance, half the search's precision (83,886 pt at 0.005 pt), is flattened more coarsely, and the circle can be smaller by as much; a curved hole narrower than the flattening tolerance can also make it smaller; a shape that flattening would close up or move off its curves is flattened finer, down to 1/65,536 of the tolerance). The drawn circle's four curves reach up to 0.03% of its radius past a true circle, so it is drawn 0.03% smaller and stays inside where it touches. Holes and gaps narrower than 1e-6 pt close up, and edges can move by as much, as in the other path operations. Strokes and effects are left out. The circles get the current paint and go on top of the current layer or of the isolated group, as other new art; inside an isolated compound path they join it and take its appearance; they are selected; one undo step. It is an error, with the document unchanged, when a selected object is not a closed path or compound path (\"object N is not a closed path or compound path\"; an open path has no inside), when it fills no area (\"object N fills no area\"), and when its outline has more than 262,144 anchors (in subpaths of two or more) or more than 262,144 straight pieces once flattened, or the searches of the selected objects together measure more than 134,217,728 distances from a point to an edge, or one search keeps more than 1,048,576 cells waiting, or the shape is so thin for its length that it flattens to no area even at the finest tolerance (\"object N is too complex to measure\") → {id: the first circle, ids}", whole_objects, inscribed_circle )] @@ -52,21 +52,30 @@ fn outline(d: &Document, id: NodeId) -> Option<(PathData, FillRule)> { } fn inscribed_circle(s: &mut Session, _p: &Value) -> Result { + // The roots leave out selected layers, which are not paths either. + let st = s.doc()?; + if let Some(layer) = st.selection.objects.iter().find(|id| st.doc.node(**id).is_some_and(Node::is_layer)) { + return Err(bad(COMMAND, format!("object {} is not a closed path or compound path", layer.0))); + } let roots = selected_roots_to_transform(s)?; let d = &s.doc()?.doc; let mut circles = vec![]; + // The searches share one work limit, so the command stays bounded however many objects are + // selected. + let mut work = pt::MAX_INSCRIBED_WORK; for id in roots { let value = id.0; let Some((path, rule)) = outline(d, id) else { return Err(bad(COMMAND, format!("object {value} is not a closed path or compound path"))); }; - let c = pt::inscribed_circle(&path, rule).map_err(|e| match e { + let c = pt::inscribed_circle_within(&path, rule, &mut work).map_err(|e| match e { InscribedError::NoArea => bad(COMMAND, format!("object {value} fills no area")), InscribedError::TooComplex => bad(COMMAND, format!("object {value} is too complex to measure")), })?; circles.push(c); } - let parent = s.doc()?.target_parent()?; + // Path art: inside an isolated compound path, the circles join it, as Tangent Circle's do. + let parent = s.doc()?.target_parent_for_path()?; let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); let ids = s.edit(LABEL, |d, sel| { let mut ids = vec![]; diff --git a/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs b/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs index f19c8fd111..86f0342ff7 100644 --- a/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs @@ -152,6 +152,11 @@ fn each_selected_path_gets_a_circle_in_one_step() { let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); let r = circle(&s, id).1; assert!(r <= 20.0 + 1e-6 && r > least(20.0), "the member's own square: {r}"); + // Inside the isolated compound path, the circle joins it. + s.execute("object.isolate", &json!({"id": compound.0})).unwrap(); + select(&mut s, &[member]); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(compound)); } /// The drawn circle stays inside a large square turned so that it touches the square's sides @@ -200,4 +205,17 @@ fn open_paths_other_objects_and_no_selection_are_refused() { let flat = id_of(&s.execute("path.create", &json!({"anchors": flat, "closed": true})).unwrap()); select(&mut s, &[flat]); refused(&mut s, "fills no area"); + // A selected layer is refused too, alone or with a path. + let mut layer = None; + s.doc().unwrap().doc.walk(|n| { + if n.is_layer() { + layer.get_or_insert(n.id); + } + }); + let layer = layer.unwrap(); + let path = id_of(&s.execute("shape.rectangle", &json!({"x": 200, "y": 100, "width": 50, "height": 50})).unwrap()); + for ids in [vec![layer], vec![layer, path]] { + select(&mut s, &ids); + refused(&mut s, "is not a closed path or compound path"); + } } diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index 58927fbb79..032576e605 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -35,7 +35,10 @@ pub use bridge::{ pub use crossings::{MAX_CROSSED_BY_SEGMENTS, MAX_CROSSING_SEGMENTS, Place, Work, crossings, crossings_on, crossings_on_within, insert_at}; pub use dashes::{DashSpec, Piece, divide_dashes}; pub use extend::{ExtendMode, extend_length_to, extend_open}; -pub use inscribed::{INSCRIBED_PRECISION, Inscribed, InscribedError, MAX_INSCRIBED_EDGES, inscribed_circle}; +pub use inscribed::{ + INSCRIBED_PRECISION, Inscribed, InscribedError, MAX_INSCRIBED_CELLS, MAX_INSCRIBED_EDGES, MAX_INSCRIBED_WORK, inscribed_circle, + inscribed_circle_within, +}; pub use shared_edge::{ COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at, }; diff --git a/crates/pathops/src/addons/pathtools/inscribed.rs b/crates/pathops/src/addons/pathtools/inscribed.rs index 285132acba..7b021d512e 100644 --- a/crates/pathops/src/addons/pathtools/inscribed.rs +++ b/crates/pathops/src/addons/pathtools/inscribed.rs @@ -32,10 +32,15 @@ thread_local! { pub const INSCRIBED_PRECISION: f64 = 0.01; /// Most straight edges the flattened outline may have. pub const MAX_INSCRIBED_EDGES: usize = 1 << 18; -/// Most distances from a point to an edge that one search measures. -const MAX_WORK: usize = 1 << 27; +/// Most distances from a point to an edge that one search measures, or that the searches of one +/// [`inscribed_circle_within`] budget measure together. +pub const MAX_INSCRIBED_WORK: usize = 1 << 27; /// Most cells the box is first cut into. const MAX_FIRST_CELLS: f64 = 4096.0; +/// Most cells the search keeps waiting to be split. +pub const MAX_INSCRIBED_CELLS: usize = 1 << 20; +/// How many times an outline the flattening does not resolve is flattened 16 times finer. +const FINER_FLATTENINGS: usize = 4; /// The largest circle inside an outline: its center and radius. #[derive(Clone, Copy, Debug, PartialEq)] @@ -49,28 +54,53 @@ pub struct Inscribed { pub enum InscribedError { /// The outline fills no area. NoArea, - /// The outline could not be resolved, has more than [`MAX_INSCRIBED_EDGES`] edges, or the - /// search would measure more than its limit. + /// The outline could not be resolved, has more than [`MAX_INSCRIBED_EDGES`] anchors in its + /// subpaths of two or more or more than as many edges once flattened, or the + /// search would measure more than its limit or keep more than [`MAX_INSCRIBED_CELLS`] cells + /// waiting, or the outline is so thin for its length that it flattens to no area. TooComplex, } -/// The largest circle inside the area that `path` fills under `rule`, within twice -/// [`INSCRIBED_PRECISION`] of the largest radius: the search's precision and the flattening, at -/// half of it. A curve whose control polygon is longer than 83,886 pt is flattened more coarsely -/// ([`vectorcraft_geom::flatten`]), and the circle can be smaller by as much. Holes and gaps -/// narrower than 1e-6 pt close up, as in the other path operations. Open subpaths count as closed, -/// as when they are filled. +/// The largest circle inside the area that `path` fills under `rule`, within twice the precision +/// of the largest radius: the search's precision and the flattening, at half of it. The precision +/// is [`INSCRIBED_PRECISION`], or a thousandth of the narrower side of the filled area's box when +/// that is less than 10 pt. A curve whose control polygon is longer than 4096² times the +/// flattening tolerance (83,886 pt at 0.005 pt) is flattened more coarsely +/// ([`vectorcraft_geom::flatten`]), and the circle can be smaller by as much; so can a curved hole +/// narrower than the flattening tolerance. The bounds hold for the fill as the path operations +/// resolve it: holes and gaps narrower than 1e-6 pt close up, and edges can move by as much. Open +/// subpaths are closed as the other path operations close them, handles included. The searches +/// for one outline measure at most [`MAX_INSCRIBED_WORK`] distances in all, the final distances +/// to the curves included. pub fn inscribed_circle(path: &PathData, rule: FillRule) -> Result { + inscribed_circle_within(path, rule, &mut MAX_INSCRIBED_WORK.clone()) +} + +/// [`inscribed_circle`], measuring at most `work` distances from a point to an edge (and never +/// more than [`MAX_INSCRIBED_WORK`]) and taking the ones it measured off `work`, so several +/// searches can share one budget. +pub fn inscribed_circle_within(path: &PathData, rule: FillRule, work: &mut usize) -> Result { + // A path with more anchors than the edge limit, in the subpaths that are filled, is refused + // before it is resolved. + let mut filled_anchors = path.subpaths.iter().map(|sp| sp.anchors.len()).filter(|&n| n >= 2); + if filled_anchors.try_fold(0usize, |total, n| total.checked_add(n).filter(|&t| t <= MAX_INSCRIBED_EDGES)).is_none() { + return Err(InscribedError::TooComplex); + } let filled = fill_bezpath(path); let b = filled.bounding_box(); if !(b.width() > 0.0 && b.height() > 0.0 && b.is_finite()) { return Err(InscribedError::NoArea); } - let precision = INSCRIBED_PRECISION.min(b.width().min(b.height()) / 1000.0); + let precision = precision_for(b); // Every contour of the fill's boundary counts, however narrow, down to the sweep's tolerance // (1e-6 pt; [`crate::boolean::eps_for`]): a hairline hole is still outside the fill. Curves the // sweep split are rebuilt from the input's own. let contours = normalize_bez(&filled, rule).map_err(|_| InscribedError::TooComplex)?; + // The resolved boundary can have far more pieces than the input; past the edge limit it is + // refused before it is copied. + if contours.contours().map(|c| c.path.segments().count()).sum::() > MAX_INSCRIBED_EDGES { + return Err(InscribedError::TooComplex); + } let tidy = Tidy::keeping(precision, [&filled]); let mut curves = kurbo::BezPath::new(); for c in contours.contours() { @@ -80,14 +110,61 @@ pub fn inscribed_circle(path: &PathData, rule: FillRule) -> Result 0.0 && b.height() > 0.0 && b.is_finite()) { return Err(InscribedError::NoArea); } - let edges = edges(&curves, precision / 2.0)?; - let center = search(&edges, b, precision, MAX_WORK)?; - // The circle touches the nearest curve, whatever the flattening moved. - let radius = curves.segments().map(|s| s.nearest(center, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt(); - if !(radius.is_finite() && radius > 0.0) || !fill_contains(&curves, FillRule::NonZero, center) { - return Err(InscribedError::NoArea); + // The fill rule can leave a much narrower area than the outline's box. + let precision = precision.min(precision_for(b)); + // The attempts for this outline share one allowance, taken off `work` as it is spent. + let start = (*work).min(MAX_INSCRIBED_WORK); + let mut allowance = start; + let found = measure(&curves, b, precision, &mut allowance); + *work = work.saturating_sub(start - allowance); + found +} + +/// The largest circle in the resolved `curves`, whose box is `b`, searched to `precision`, +/// measuring at most `allowance` distances and taking them off it. +fn measure(curves: &kurbo::BezPath, b: Rect, precision: f64, allowance: &mut usize) -> Result { + // Flattening can close up or move an area thinner than its tolerance, so that the flattened + // outline holds nothing or its best center lies outside the curves: the outline is then + // flattened 16 times finer, up to 4 times (down to 1/65,536 of the tolerance). The resolved + // contours have an area, so an outline that is still not measured is past what the + // flattening can resolve (very long curves are flattened more coarsely). + let mut tolerance = precision / 2.0; + // The last edges searched: a finer tolerance can flatten to the same ones (very long curves), + // which would give the same center again. + let mut searched = None; + for attempt in 0..=FINER_FLATTENINGS { + let edges = edges(curves, tolerance)?; + let held = area(&edges); + let last = attempt == FINER_FLATTENINGS; + let fresh = searched.as_ref() != Some(&edges); + if fresh && (held > tolerance * tolerance || (last && held.partial_cmp(&0.0) == Some(Ordering::Greater))) { + match search(&edges, b, precision, allowance) { + Ok(center) => { + // The circle touches the nearest curve, whatever the flattening moved; those + // distances come out of the allowance too. + let pieces = curves.segments().count(); + if *allowance < pieces { + return Err(InscribedError::TooComplex); + } + *allowance -= pieces; + let radius = curves.segments().map(|s| s.nearest(center, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt(); + if radius.is_finite() && radius > 0.0 && fill_contains(curves, FillRule::NonZero, center) { + return Ok(Inscribed { center, radius }); + } + } + Err(InscribedError::NoArea) => {} + Err(e) => return Err(e), + } + searched = Some(edges); + } + tolerance /= 16.0; } - Ok(Inscribed { center, radius }) + Err(InscribedError::TooComplex) +} + +/// The search's precision for an area whose box is `b`. +fn precision_for(b: Rect) -> f64 { + INSCRIBED_PRECISION.min(b.width().min(b.height()) / 1000.0) } /// The straight edges of `curves` flattened to within `tolerance`, each subpath closed. @@ -101,9 +178,10 @@ fn edges(curves: &kurbo::BezPath, tolerance: f64) -> Result, out.push((a, b)); } }; - let mut over = false; - vectorcraft_geom::flatten(curves.iter(), tolerance, |el| { - if over { + // Once past the limit, no further curve is flattened. + let over = std::cell::Cell::new(false); + vectorcraft_geom::flatten(curves.iter().take_while(|_| !over.get()), tolerance, |el| { + if over.get() { return; } match el { @@ -123,15 +201,33 @@ fn edges(curves: &kurbo::BezPath, tolerance: f64) -> Result, } _ => {} } - over = out.len() > MAX_INSCRIBED_EDGES; + over.set(out.len() > MAX_INSCRIBED_EDGES); }); close(&mut out, start, last); - if over || out.len() > MAX_INSCRIBED_EDGES { + if over.get() || out.len() > MAX_INSCRIBED_EDGES { return Err(InscribedError::TooComplex); } Ok(out) } +/// The area the closed `edges` hold: their outer contours and holes turn opposite ways. Each +/// contour's points are taken from its first one, so a small area far from the origin is not +/// rounded away. +fn area(edges: &[(Point, Point)]) -> f64 { + let (mut total, mut contour) = (0.0, 0.0); + let (mut o, mut last) = (Point::ZERO, None); + for &(a, b) in edges { + // An edge that does not start where the last one ended starts the next contour. + if last != Some(a) { + total += contour; + (contour, o) = (0.0, a); + } + contour += (a - o).cross(b - o); + last = Some(b); + } + ((total + contour) / 2.0).abs() +} + /// How far `p` lies inside the closed `edges` (nonzero winding): the distance to the nearest edge, /// negative outside. fn inside(edges: &[(Point, Point)], p: Point) -> f64 { @@ -197,45 +293,77 @@ impl Ord for Cell { } /// The point of the closed `edges`, inside box `b`, farthest from every edge, within `precision`, -/// measuring at most about `limit` distances from a point to an edge. -fn search(edges: &[(Point, Point)], b: Rect, precision: f64, limit: usize) -> Result { +/// measuring at most `budget` distances from a point to an edge, and never more than +/// [`MAX_INSCRIBED_WORK`], and taking the ones it measured off `budget`. +fn search(edges: &[(Point, Point)], b: Rect, precision: f64, budget: &mut usize) -> Result { + let mut work = 0usize; + let found = search_measuring(edges, b, (precision, (*budget).min(MAX_INSCRIBED_WORK), MAX_INSCRIBED_CELLS), &mut work); + *budget = budget.saturating_sub(work); + found +} + +/// [`search`] with `(precision, limit, max_cells)`, measuring at most `limit` distances (counted +/// in `work`) and keeping at most `max_cells` cells waiting. +fn search_measuring(edges: &[(Point, Point)], b: Rect, limits: (f64, usize, usize), work: &mut usize) -> Result { + let (precision, limit, max_cells) = limits; // Square cells as wide as the box's narrower side, or wider when that would make more than // `first` along the box or in all: at most MAX_FIRST_CELLS, and at most a quarter of the work // limit, so the first cells take at most about three quarters of it. let first = MAX_FIRST_CELLS.min((limit / edges.len().max(1) / 4) as f64).max(1.0); let size = b.width().min(b.height()).max((b.area() / first).sqrt()).max(b.width().max(b.height()) / first); let (cols, rows) = ((b.width() / size).ceil() as usize, (b.height() / size).ceil() as usize); - let mut work = 0usize; + // Each cell is measured only when the limit still has room for it. let measure = |work: &mut usize, center: Point, half: f64| { - *work = work.saturating_add(edges.len()); + let Some(after) = work.checked_add(edges.len()).filter(|&after| after <= limit) else { + return Err(InscribedError::TooComplex); + }; + *work = after; #[cfg(test)] MEASURED.with(|m| m.set(*work)); - Cell::new(edges, center, half) + Ok(Cell::new(edges, center, half)) }; - let mut best = measure(&mut work, b.center(), 0.0); + // No circle in the box is wider than its narrower side. + let ceiling = b.width().min(b.height()) / 2.0; + // Until a center inside the outline is found, every cell that may hold one is split; after + // that, only cells that may beat the best center by more than the precision. + let open = |cell: &Cell, best: &Cell| cell.best > 0.0 && (best.inside <= 0.0 || cell.best - best.inside > precision); + let done = |best: &Cell| best.inside > 0.0 && best.inside >= ceiling - precision; + let mut best = measure(work, b.center(), 0.0)?; let mut cells = BinaryHeap::new(); - for row in 0..rows { - for col in 0..cols { - if work > limit { + let add = |cells: &mut BinaryHeap, best: &mut Cell, cell: Cell| { + if cell.inside > best.inside { + *best = cell; + } + // A best center at the ceiling ends the search, full queue or not. + if !done(best) && open(&cell, best) { + if cells.len() >= max_cells { return Err(InscribedError::TooComplex); } + cells.push(cell); + } + Ok(()) + }; + for row in 0..rows { + for col in 0..cols { + if done(&best) { + return Ok(best.center); + } let at = Point::new(b.x0 + (col as f64 + 0.5) * size, b.y0 + (row as f64 + 0.5) * size); - cells.push(measure(&mut work, at, size / 2.0)); + let cell = measure(work, at, size / 2.0)?; + add(&mut cells, &mut best, cell)?; } } while let Some(cell) = cells.pop() { - if cell.inside > best.inside { - best = cell; - } - if cell.best - best.inside <= precision { + if done(&best) || !open(&cell, &best) { break; } - if work > limit { - return Err(InscribedError::TooComplex); - } let h = cell.half / 2.0; for (dx, dy) in [(-h, -h), (h, -h), (-h, h), (h, h)] { - cells.push(measure(&mut work, cell.center + (dx, dy), h)); + if done(&best) { + return Ok(best.center); + } + let child = measure(work, cell.center + (dx, dy), h)?; + add(&mut cells, &mut best, child)?; } } if best.inside <= 0.0 { diff --git a/crates/pathops/src/addons/pathtools/inscribed/tests.rs b/crates/pathops/src/addons/pathtools/inscribed/tests.rs index 50f2d103d3..1731d798a0 100644 --- a/crates/pathops/src/addons/pathtools/inscribed/tests.rs +++ b/crates/pathops/src/addons/pathtools/inscribed/tests.rs @@ -89,6 +89,20 @@ fn a_shape_narrower_than_the_default_precision_gets_a_circle() { assert!(c.radius <= 0.0025 + 1e-12 && c.radius > 0.0025 * 0.99, "{c:?}"); } +#[test] +fn a_tiny_shape_far_from_the_origin_gets_a_circle() { + let sq = polygon(&[(10_000.0, 10_000.0), (10_000.000_1, 10_000.0), (10_000.000_1, 10_000.000_1), (10_000.0, 10_000.000_1)]); + let c = inscribed_circle(&sq, FillRule::NonZero).unwrap(); + assert!(c.radius > 0.00005 * 0.99 && c.radius <= 0.00005 + 1e-9, "{c:?}"); + // With a second tiny square far from the first, each square's area is measured from its own + // corner. + let near = polygon(&[(0.0, 0.0), (0.0001, 0.0), (0.0001, 0.0001), (0.0, 0.0001)]); + let far = polygon(&[(1e6, 1e6), (1e6 + 0.0001, 1e6), (1e6 + 0.0001, 1e6 + 0.0001), (1e6, 1e6 + 0.0001)]); + let both = PathData::new(near.subpaths.into_iter().chain(far.subpaths).collect()); + let a = area(&edges(&both.to_bezpath(), 0.005).unwrap()); + assert!((a - 2e-8).abs() < 1e-10, "{a}"); +} + #[test] fn a_hairline_hole_bounds_the_circle() { // A 100 pt square with a hole 0.001 pt wide down its middle: the circle stays on one side. @@ -102,17 +116,129 @@ fn a_hairline_hole_bounds_the_circle() { #[test] fn a_long_thin_shape_is_refused_without_measuring_past_the_work_limit() { - // A strip 5,000 × 1 whose top edge has 5,000 pieces: cut into cells as wide as it is high, - // the first cells alone would measure 5,000 times every edge. + // A strip 5,000 long, 1 high at one end and 2 at the other, whose top edge has 5,000 pieces: + // cut into cells as wide as it is high, the first cells alone would measure 2,500 times every + // edge. let n = 5000; let top: Vec<(f64, f64)> = (0..=n).map(|i| (i as f64, 0.0)).collect(); - let pts: Vec<(f64, f64)> = top.into_iter().chain([(n as f64, 1.0), (0.0, 1.0)]).collect(); + let pts: Vec<(f64, f64)> = top.into_iter().chain([(n as f64, 1.0), (0.0, 2.0)]).collect(); let e = edges(&polygon(&pts).to_bezpath(), 0.005).unwrap(); let limit = 100 * e.len(); - assert_eq!(search(&e, Rect::new(0.0, 0.0, n as f64, 1.0), 0.01, limit), Err(InscribedError::TooComplex)); - // Past the limit by at most the four cells of one split. + assert_eq!(search(&e, Rect::new(0.0, 0.0, n as f64, 2.0), 0.01, &mut limit.clone()), Err(InscribedError::TooComplex)); let measured = MEASURED.with(std::cell::Cell::get); - assert!(measured <= limit + 4 * e.len(), "{measured} measured, limit {limit}"); + assert!(measured <= limit, "{measured} measured, limit {limit}"); +} + +#[test] +fn a_long_rectangle_stops_once_no_wider_circle_fits() { + // Every point of the center line is 50 from the long sides: the box's center is already the + // largest circle's, and the search stops at the first cells. + let r = polygon(&[(0.0, 0.0), (100_000.0, 0.0), (100_000.0, 100.0), (0.0, 100.0)]); + let c = inscribed_circle(&r, FillRule::NonZero).unwrap(); + holds(&r, FillRule::NonZero, c, 50.0); + let measured = MEASURED.with(std::cell::Cell::get); + assert!(measured <= (MAX_FIRST_CELLS as usize + 1) * 4, "{measured} measured"); +} + +#[test] +fn a_fill_far_smaller_than_the_precision_still_gets_a_circle() { + // Two 0.001 pt squares at opposite corners of a 100 pt box, which sets the precision to + // 0.01 pt. + let a = polygon(&[(0.0, 0.0), (0.001, 0.0), (0.001, 0.001), (0.0, 0.001)]); + let b = polygon(&[(99.999, 99.999), (100.0, 99.999), (100.0, 100.0), (99.999, 100.0)]); + let both = PathData::new(a.subpaths.into_iter().chain(b.subpaths).collect()); + let c = inscribed_circle(&both, FillRule::NonZero).unwrap(); + assert!(c.radius > 0.0 && c.radius <= 0.0005 + 1e-9, "{c:?}"); + assert!(fill_contains(&both.to_bezpath(), FillRule::NonZero, c.center), "{c:?}"); +} + +#[test] +fn a_lens_thinner_than_the_flattening_tolerance_gets_a_circle() { + // A straight side and a curve bowed 0.001 pt from it, 141 pt long: flattened to 0.005 pt the + // curve would lie on the straight side. + let lens = |side: f64| { + let n = kurbo::Vec2::new(1.0, -1.0) / 2f64.sqrt() * (0.001 / 0.75); + let (a, b) = (Point::ZERO, Point::new(side, side)); + PathData::new(vec![SubPath::new( + vec![ + Anchor::with_handles(a, Point::new(side / 3.0, side / 3.0) + n, a), + Anchor::with_handles(b, b, Point::new(side * 2.0 / 3.0, side * 2.0 / 3.0) + n), + ], + true, + )]) + }; + let l = lens(100.0); + let c = inscribed_circle(&l, FillRule::NonZero).unwrap(); + assert!(c.radius > 0.0 && c.radius <= 0.0005 + 1e-9, "{c:?}"); + assert!(fill_contains(&l.to_bezpath(), FillRule::NonZero, c.center), "{c:?}"); + // A curve that long is flattened too coarsely to show the bow at all: too complex, not empty. + assert_eq!(inscribed_circle(&lens(1e6), FillRule::NonZero), Err(InscribedError::TooComplex)); +} + +#[test] +fn a_bowed_strip_thinner_than_the_flattening_tolerance_is_not_reported_empty() { + // Two curves 0.001 pt apart, both bowed 0.003 pt the same way: flattened to 0.005 pt they + // become a straight strip that lies outside the bowed one. + let strip = |side: f64| { + let unit = kurbo::Vec2::new(1.0, -1.0) / 2f64.sqrt(); + let (bow, gap) = (unit * (0.003 / 0.75), unit * 0.001); + let (a, b) = (Point::ZERO, Point::new(side, side)); + let third = (b - a) / 3.0; + let (a1, b1) = (a + gap, b + gap); + PathData::new(vec![SubPath::new( + vec![ + Anchor::with_handles(a, a, a + third + bow), + Anchor::with_handles(b, b - third + bow, b), + Anchor::with_handles(b1, b1, b1 - third + bow), + Anchor::with_handles(a1, a1 + third + bow, a1), + ], + true, + )]) + }; + let inside = |s: &PathData, c: Inscribed| { + assert!(c.radius > 0.0 && c.radius <= 0.0005 + 1e-9, "{c:?}"); + // Measured against the curves flattened to 1e-8 pt by kurbo itself, which does not + // coarsen long curves: kurbo's winding can miss a curve a point lies this close to. + let mut polyline = kurbo::BezPath::new(); + kurbo::flatten(s.to_bezpath(), 1e-8, |el| polyline.push(el)); + let fine = edges(&polyline, 1e-8).unwrap(); + assert!(rim(c).all(|p| super::inside(&fine, p) > 1e-8), "{c:?} reaches outside"); + }; + // 28 and 141 pt long: a circle inside it, or too complex to measure; never "no area". + for side in [20.0, 100.0] { + let s = strip(side); + match inscribed_circle(&s, FillRule::NonZero) { + Ok(c) => inside(&s, c), + e => assert_eq!(e, Err(InscribedError::TooComplex), "{side}"), + } + } +} + +#[test] +fn a_thin_turned_rectangle_gets_the_circle_at_its_center() { + // 100 pt long and 0.009998 pt wide, turned 45°: no wider than twice the flattening tolerance. + let (u, v) = (kurbo::Vec2::new(1.0, 1.0) / 2f64.sqrt(), kurbo::Vec2::new(1.0, -1.0) / 2f64.sqrt()); + let (along, across) = (u * 100.0, v * 0.009998); + let corners = [Point::ZERO, Point::ZERO + along, Point::ZERO + along + across, Point::ZERO + across]; + let r = polygon(&corners.map(|p| (p.x, p.y))); + let c = inscribed_circle(&r, FillRule::NonZero).unwrap(); + holds(&r, FillRule::NonZero, c, 0.004999); + assert!(c.radius > 0.004999 * 0.99, "{c:?}"); + // 1,000 pt long and 0.0001 pt wide: also measured at the center. + let (along, across) = (u * 1000.0, v * 0.0001); + let corners = [Point::ZERO, Point::ZERO + along, Point::ZERO + along + across, Point::ZERO + across]; + let r = polygon(&corners.map(|p| (p.x, p.y))); + let c = inscribed_circle(&r, FillRule::NonZero).unwrap(); + assert!(c.radius > 0.00005 * 0.99 && c.radius <= 0.00005 + 1e-9, "{c:?}"); +} + +#[test] +fn a_search_past_its_cell_limit_is_too_complex() { + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); + let e = edges(&l.to_bezpath(), 0.005).unwrap(); + let b = Rect::new(0.0, 0.0, 100.0, 100.0); + assert!(search_measuring(&e, b, (0.01, MAX_INSCRIBED_WORK, MAX_INSCRIBED_CELLS), &mut 0).is_ok()); + assert_eq!(search_measuring(&e, b, (0.01, MAX_INSCRIBED_WORK, 10), &mut 0), Err(InscribedError::TooComplex)); } #[test] @@ -120,6 +246,11 @@ fn an_outline_with_too_many_edges_is_too_complex() { let zigzag: Vec<(f64, f64)> = (0..=MAX_INSCRIBED_EDGES).map(|i| (i as f64, (i % 2) as f64)).chain([(0.0, -10.0)]).collect(); let bp = polygon(&zigzag).to_bezpath(); assert_eq!(edges(&bp, 0.005), Err(InscribedError::TooComplex)); + // Too many anchors are refused before the outline is resolved, even on a line that would + // otherwise fill no area. + let line: Vec<(f64, f64)> = (0..=MAX_INSCRIBED_EDGES).map(|i| (i as f64, 0.0)).collect(); + assert_eq!(inscribed_circle(&polygon(&line), FillRule::NonZero), Err(InscribedError::TooComplex)); + assert_eq!(inscribed_circle(&polygon(&line[..1000]), FillRule::NonZero), Err(InscribedError::NoArea)); assert_eq!(edges(&polygon(&zigzag[..1000]).to_bezpath(), 0.005).map(|e| e.len()), Ok(1000)); } @@ -128,8 +259,41 @@ fn a_search_past_its_work_limit_is_too_complex() { let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); let e = edges(&l.to_bezpath(), 0.005).unwrap(); let b = Rect::new(0.0, 0.0, 100.0, 100.0); - assert!(search(&e, b, 0.01, MAX_WORK).is_ok()); - assert_eq!(search(&e, b, 0.01, 20 * e.len()), Err(InscribedError::TooComplex)); + assert!(search(&e, b, 0.01, &mut MAX_INSCRIBED_WORK.clone()).is_ok()); + assert_eq!(search(&e, b, 0.01, &mut (20 * e.len())), Err(InscribedError::TooComplex)); +} + +#[test] +fn searches_that_share_a_budget_stop_when_it_runs_out() { + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); + let mut work = MAX_INSCRIBED_WORK; + assert!(inscribed_circle_within(&l, FillRule::NonZero, &mut work).is_ok()); + let one = MAX_INSCRIBED_WORK - work; + assert!(one > 0); + // Enough for one search and half of another: the first fits, the second runs out. + let mut work = one + one / 2; + assert!(inscribed_circle_within(&l, FillRule::NonZero, &mut work).is_ok()); + assert!(work < one, "{work} left of {one}"); + assert_eq!(inscribed_circle_within(&l, FillRule::NonZero, &mut work), Err(InscribedError::TooComplex)); + // One distance short of a whole search: refused without measuring past the budget. + let mut work = one - 1; + assert_eq!(inscribed_circle_within(&l, FillRule::NonZero, &mut work), Err(InscribedError::TooComplex)); + let measured = MEASURED.with(std::cell::Cell::get); + assert!(measured < one, "{measured} measured, budget {}", one - 1); +} + +#[test] +fn an_area_the_fill_rule_leaves_small_is_measured_to_its_own_scale() { + // Two identical 100 pt squares cancel under even-odd, leaving the small L of the test above: + // the outline's box is 100 pt across, the filled area's 0.1 pt. + let sq = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let l = polygon( + &[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)].map(|(x, y)| (x / 1000.0 + 50.0, y / 1000.0 + 50.0)), + ); + let all = PathData::new(sq.subpaths.iter().cloned().chain(sq.subpaths.iter().cloned()).chain(l.subpaths).collect()); + let c = inscribed_circle(&all, FillRule::EvenOdd).unwrap(); + let largest = 0.03 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2); + assert!(c.radius <= largest + 1e-9 && c.radius > largest * 0.99, "{c:?}, largest {largest}"); } #[test] diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index dd33370568..c71527ab1a 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -41,6 +41,8 @@ pub const TANGENT_KINDS: &[(&str, &str)] = &[("All", "all"), ("External", "exter /// dialog (Offset, One per Object) with a Preview. pub const BOUNDING_RECTANGLE: &str = "addon.pathtools.boundingRectangle"; pub const BOUNDING_CIRCLE: &str = "addon.pathtools.boundingCircle"; +/// Add Inscribed Circle's command, whose menu item runs it with no dialog. +pub const INSCRIBED_CIRCLE: &str = "addon.pathtools.inscribedCircle"; /// The close modes, as `addon.pathtools.close` names them, and their labels. const CLOSE_MODES: [(&str, &str); 3] = [("handles", "Keep Handles"), ("straight", "Straight"), ("smooth", "Smooth")]; const LABEL_W: f32 = 64.0; @@ -87,7 +89,7 @@ pub fn menu() -> Vec { Item::Cmd("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), Item::Cmd("Add Bounding Rectangle…", BOUNDING_RECTANGLE, json!({ "offset": 0, "each": false })), Item::Cmd("Add Bounding Circle…", BOUNDING_CIRCLE, json!({ "offset": 0, "each": false })), - Item::Cmd("Add Inscribed Circle", "addon.pathtools.inscribedCircle", json!({})), + Item::Cmd("Add Inscribed Circle", INSCRIBED_CIRCLE, json!({})), ] } diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 2c49c661fe..fb9a9c2ac1 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -530,3 +530,41 @@ fn add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_objec } } } + +#[test] +fn add_inscribed_circle_draws_its_circles_without_a_dialog() { + let mut app = app(); + let find = |app: &VectorcraftApp| { + let entries = menus::menu_entries(app); + entries + .into_iter() + .find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Add Inscribed Circle") + .expect("Add Inscribed Circle") + }; + let item = find(&app); + assert_eq!((item.command.as_deref(), &item.params), (Some(super::INSCRIBED_CIRCLE), &json!({}))); + assert!(!item.enabled, "with nothing selected"); + let a = app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("shape.rectangle", json!({"x": 100, "y": 20, "width": 20, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let (steps, nodes) = (app.session.doc().unwrap().history.undo.len(), app.session.doc().unwrap().doc.node_count()); + let item = find(&app); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(&mut app, &cmd, p); + assert!(app.ui.dialog.is_none(), "no dialog opens"); + let st = app.session.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.doc.node_count()), (steps + 1, nodes + 2), "a circle in each rectangle, one undo step"); + let made = &st.selection.objects; + assert_eq!(made.len(), 2, "the two circles are selected: {made:?}"); + for (id, inside) in made.iter().zip([[10.0, 20.0, 40.0, 60.0], [100.0, 20.0, 120.0, 60.0]]) { + assert!(id.0 != a && id.0 != b, "{id:?} is a new object"); + let live = match &st.doc.node(*id).unwrap().kind { + vectorcraft_doc::NodeKind::Path { live, .. } => live.as_deref(), + _ => None, + }; + assert!(matches!(live, Some(vectorcraft_doc::LiveShape::Ellipse { w, h, .. }) if w == h), "{id:?} is a live circle"); + let r = st.doc.bounds_of(&[*id], false).unwrap(); + assert!(r.x0 >= inside[0] && r.y0 >= inside[1] && r.x1 <= inside[2] && r.y1 <= inside[3], "{r:?} inside {inside:?}"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 242821d4bb..17e6ad3d06 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14821,18 +14821,24 @@ Commands: [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). A path of a compound path selected on its own counts as a path. The circle lies in the area the shape fills under its fill rule: holes and the overlaps of crossing subpaths count as the fill shows them, and strokes and effects are left out. The command - flattens the outline to within 0.005 pt and searches square cells best first, measuring the radius from the center - to the curves, so its radius is within 0.02 pt of the largest. A shape whose - box is less than 10 pt across on its narrower side is measured to a thousandth of that side instead. A curve whose - control polygon is longer than 83,886 pt is flattened more coarsely, and the circle can be smaller by as much. The - drawn circle's four curves reach up to 0.03% of its radius past a true circle, so the command draws it that much - smaller, and it stays inside where it touches the shape. Narrow holes count; holes and gaps narrower than 1e-6 pt close up, as - in the other path operations. The circles get the current paint and go on top of the current layer, or of the isolated group, as other new art does. - The new circles are selected, and one undo removes them all. It is an error, with the document unchanged, when a selected - object is not a closed path or compound path ("object N is not a closed path or compound path"; an open path has no - inside), when it fills no area ("object N fills no area"), and when its outline has more than 262,144 straight - pieces once flattened, or the search measures more than 134,217,728 distances from a point to an edge ("object N is - too complex to measure"). + flattens the outline to within 0.005 pt and searches square cells best first to within 0.01 pt, then measures the + radius from the center to the curves, so before the circle is drawn its radius is within 0.02 pt of the largest. + When the box of the filled area is less than 10 pt across on its narrower side, the search and the flattening use + a thousandth and a two-thousandth of that side, and the radius is within a five-hundredth of it. A curve whose + control polygon is longer than 4096² times the flattening tolerance (83,886 pt at 0.005 pt) is flattened more + coarsely, and the circle can be smaller by as much. A curved hole narrower than the flattening tolerance can also + make it smaller. A shape that flattening would close up or move off its curves is flattened finer, down to 1/65,536 + of the tolerance. The drawn circle's four curves reach up to 0.03% of its radius past a true circle, so the command + draws it 0.03% smaller, and it stays inside where it touches the shape. Holes and gaps narrower than 1e-6 pt close + up, and edges can move by as much, as in the other path operations. The circles get the current paint and go on + top of the current layer, or of the isolated group, as other new art does; inside an isolated compound path they + join it and take its appearance. The new circles are selected, and one undo removes them all. It is an error, + with the document unchanged, when a selected object is not a closed path or compound path ("object N is not a + closed path or compound path"; an open path has no inside), when it fills no area ("object N fills no area"), and + when its outline has more than 262,144 anchors (in subpaths of two or more) or more than 262,144 straight pieces + once flattened, or the searches of all the selected objects together measure more than 134,217,728 distances from + a point to an edge, or one search keeps more than 1,048,576 cells waiting, or the shape is so thin for its length + that it flattens to no area even at the finest tolerance ("object N is too complex to measure"). → `{id: the first circle, ids}` A parametric shape is an ordinary path. It keeps its numbers, with a fingerprint of the outline they drew, in one diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2bd4e10a02..cd3c4c6f23 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2991,7 +2991,7 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Pre ## Path Precision Tools add-on: Add Inscribed Circle (2026-11-22) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Inscribed Circle (`addon.pathtools.inscribedCircle`) draws the largest live circle inside each selected closed path or compound path, centered on the shape's [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). The rest is VectorCraft's own: the shape is first resolved under its fill rule into outer contours and holes, flattened to within 0.005 pt and searched in square cells best first, and the radius is measured from the center to the curves, within 0.02 pt of the largest (a shape less than 10 pt across is measured to a thousandth of its narrower side), and the circle is drawn up to 0.03% smaller, by as much as its four curves reach past a true circle, so it stays inside. The circles use the current paint, go on top of the current layer or the isolated group, and are one undo step (#6966). Open paths, other objects, shapes that fill no area, and outlines past 262,144 flattened pieces or the search's work limit are errors. Tests: `addons::pathtools::inscribed::tests` in `vectorcraft-pathops` (a square, a concave shape, a ring under both fill rules, overlapping subpaths, a small shape, a shape narrower than 0.01 pt, a hairline hole, the edge and work limits, a long thin shape, no area) and `cmd::addons::pathtools::inscribed::tests` in `vectorcraft-engine`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Inscribed Circle (`addon.pathtools.inscribedCircle`) draws the largest live circle inside each selected closed path or compound path, centered on the shape's [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). The rest is VectorCraft's own: the shape is first resolved under its fill rule into outer contours and holes, flattened to within 0.005 pt and searched in square cells best first, and the radius is measured from the center to the curves, within 0.02 pt of the largest (when the filled area's box is less than 10 pt across, within a five-hundredth of its narrower side), and the circle is then drawn 0.03% smaller, by as much as its four curves reach past a true circle, so it stays inside. The searches of one command share one work limit. The circles use the current paint, go on top of the current layer or the isolated group (inside an isolated compound path they join it and take its appearance), and are one undo step (#6966). Open paths, other objects, shapes that fill no area, and outlines past 262,144 anchors or flattened pieces or the search's limits are errors. Tests: `addons::pathtools::inscribed::tests` in `vectorcraft-pathops` (a square, a concave shape, a ring under both fill rules, overlapping subpaths, a small shape, a shape narrower than 0.01 pt, a hairline hole, a small area left by the fill rule, the edge and work limits, a shared work limit, a long thin shape, a long rectangle, a fill far smaller than the precision, a lens and a bowed strip thinner than the flattening tolerance, the cell limit, no area), `cmd::addons::pathtools::inscribed::tests` in `vectorcraft-engine` and `addons::pathtools::tests` in `vectorcraft-ui-egui` (`add_inscribed_circle_draws_its_circles_without_a_dialog`). Commands: `docs/mcp.md` › Path Precision Tools add-on. ## Path Precision Tools add-on: Expand Dashes into Paths (2026-11-01) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1926538a88..7ba71e39bb 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -559,7 +559,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… draw a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, from a dialog with Offset, One per Object (a shape around each object instead of one around the whole selection) and Preview; one undo step | done | `addon.pathtools.boundingRectangle` and `addon.pathtools.boundingCircle` (in `crates/engine/src/cmd/addons/pathtools/bounding.rs`, the circle in `crates/geom/src/shapes.rs`, `enclosing_circle`; the dialog is the command dialog, `crates/ui-egui/src/dialogs/command.rs`) and their tests, with the menu items' test `add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests; a VectorCraft addition, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests, with the menu item's test `add_inscribed_circle_draws_its_circles_without_a_dialog` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | From 47276ca0f2de2f30213118dee2ecac2e3a06538d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:38:31 -0800 Subject: [PATCH 41/78] Quick Pen: the stale-hover tests allow the path's length handles The two tests that check a stale hover's Smart Guides stay hidden with Smart Guides off counted every overlay other than the path's points as a guide. The length handles at the ends of the path being drawn now show there too, so the tests failed although the guides were hidden. The shared check accepts a handle and the line to it from the path's end, and still fails when the tool shows a stale hover's guides. --- crates/engine/src/tests/quickpen.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index e8915997dd..443a0db7cd 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -550,6 +550,18 @@ fn continuous_arc_after_a_line(s: &mut Session, v: ViewInfo) { key(s, ToolKey::AltTap); } +/// Whether the tool shows only the path's points and its length handles (a handle and the line to +/// it from the path's end): no hover preview, label or Smart Guide. +fn only_points(s: &mut Session, v: ViewInfo) -> bool { + let o = s.overlays(v); + let handles: Vec = o.iter().filter_map(|o| if let Overlay::Handle { p, .. } = o { Some(*p) } else { None }).collect(); + o.iter().all(|o| match o { + Overlay::CurvePoint { .. } | Overlay::Handle { .. } => true, + Overlay::Line { b, .. } => handles.contains(b), + _ => false, + }) +} + /// The last point of the path the tool drew (any other path is a two-point line). fn drawn_end(s: &Session) -> Point { let drawn = paths(s).into_iter().find(|(_, p)| p.subpaths[0].anchors.len() >= 3).unwrap(); @@ -710,9 +722,8 @@ fn a_hover_shows_nothing_after_smart_guides_change() { s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), on).unwrap(); let off_anchor = label(&mut s, on).unwrap() - at; assert!(off_anchor.x > 0.0 && (off_anchor.x - off_anchor.y).abs() < 1e-9, "the label sits diagonally off the anchor: {off_anchor:?}"); - let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); assert!(!only_points(&mut s, on)); - assert!(only_points(&mut s, off), "only the path's points show"); + assert!(only_points(&mut s, off), "only the path's points and length handles show"); // A click before the pointer moves does not bring the stale hover back. press_in(&mut s, &[(400.0, 300.0)], off); assert_eq!(label(&mut s, off), None, "no label for the stale hover after the click"); @@ -746,7 +757,6 @@ fn a_click_that_adds_nothing_keeps_a_stale_hover_hidden() { s.execute("select.set", &json!({"ids": []})).unwrap(); continuous_arc_after_a_line(&mut s, on); s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 100.0), on).unwrap(); - let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); assert!(!only_points(&mut s, on), "the anchor's guide shows"); assert!(only_points(&mut s, off)); let steps = undo_steps(&s); From 80b90c5ebb913efbfbf9e5ab0d681d12195e40c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:07:27 -0800 Subject: [PATCH 42/78] Quick Pen: a length drag out and back to the same length records no undo step A length drag that changed the length and then came back to where it started previewed the path again at its first length, so letting go recorded an undo step for an unchanged path. A drag that ends at the length the piece started with is now taken back as Escape takes it back, on the path being drawn and on a selected path. --- crates/engine/src/tests/quickpen.rs | 23 ++++++++++++++--------- crates/tools/src/quickpen.rs | 12 ++++++++---- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 443a0db7cd..dc660e919b 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -1084,8 +1084,8 @@ fn a_length_drag_stays_on_the_canvas() { assert_eq!(only_path(&s).anchors.len(), 3, "the drawing went on"); } -/// A length drag across a line, which leaves its length as it was, changes nothing and records no -/// undo step, on the path being drawn and on a selected path. +/// A length drag across a line, or out along it and back, leaves its length as it was: it changes +/// nothing and records no undo step, on the path being drawn and on a selected path. #[test] fn a_length_drag_that_keeps_the_length_records_no_undo_step() { let mut s = session(); @@ -1094,15 +1094,20 @@ fn a_length_drag_that_keeps_the_length_records_no_undo_step() { click(&mut s, 200.0, 100.0); let undo = undo_steps(&s); let before = only_path(&s); - // The end handle is at (220, 100); the drag goes straight down from it. - press(&mut s, &[(220.0, 100.0), (220.0, 160.0)]); - assert_eq!(only_path(&s), before); - assert_eq!(undo_steps(&s), undo); + // The end handle is at (220, 100); the first drag goes straight down from it, the second out + // along the line and back. + for drag in [[(220.0, 100.0), (220.0, 160.0), (220.0, 160.0)], [(220.0, 100.0), (260.0, 100.0), (220.0, 100.0)]] { + press(&mut s, &drag); + assert_eq!(only_path(&s), before, "{drag:?}"); + assert_eq!(undo_steps(&s), undo, "{drag:?}"); + } key(&mut s, ToolKey::Escape); let undo = undo_steps(&s); - press(&mut s, &[(220.0, 100.0), (220.0, 160.0)]); - assert_eq!(only_path(&s), before); - assert_eq!(undo_steps(&s), undo); + for drag in [[(220.0, 100.0), (220.0, 160.0), (220.0, 160.0)], [(220.0, 100.0), (260.0, 100.0), (220.0, 100.0)]] { + press(&mut s, &drag); + assert_eq!(only_path(&s), before, "{drag:?}"); + assert_eq!(undo_steps(&s), undo, "{drag:?}"); + } } /// The paths of a selected compound path show length handles, also after a drag selected the diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index b00524643a..23d19bc87e 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -941,11 +941,15 @@ impl QuickPenTool { if !drag.begun { return vec![]; } - // The command leaves a piece that already has the length unchanged; a drag that drew the - // last piece again has already changed the drawing. + // A drag that ends at the length the piece started with is taken back, as Escape takes it + // back: it records no undo step. let changed = (drag.length - drag.handle.piece.length).abs() > 1e-9 * drag.length.max(1.0); - if changed - && drag.last.is_none() + if !changed { + self.restore_last_piece(&drag); + return vec![Action::Cancel, drawn()]; + } + // A drag that drew the last piece again has already changed the drawing. + if drag.last.is_none() && let Some(dr) = self.drawing.as_mut() && dr.id == Some(drag.handle.id) && dr.si == drag.handle.si From 57be8ca36fe95aa148dfa08e2d58996177749f68 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:52:11 -0800 Subject: [PATCH 43/78] Plug-ins: a command's manifest can place it in another menu MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit At plug-in API level 2 a command may give `menu`: `{"path": [...], "after"?: label}`. The menus list it in that menu, right after the built-in item `after` names (either label of an item that switches between two), or at the end of the menu, with the plug-in's name in parentheses after its label. Keyboard Shortcuts, the command palette and `command_list` list it under that menu, and `plugin.list` gives its `menu` with `after` escaped. A manifest may name 14 menus of Edit, Object, Type, Select, Effect and View. File, Window, Help, the application menu and the submenus that list files, fonts, panels or plug-ins are refused when the module is installed, as is any other `menu`, an `after` that is not 1-64 printable characters and a repeated `menu`. A command whose label with the plug-in's name reads like a built-in item or submenu of that menu, or like a command a plug-in with a lower id places there, stays in its plug-in's submenu, and `plugin.list` and `plugin.inspect` mark it `placed: false`. The desktop app and `vectorcraft-cli` give the same result. Commands of several plug-ins at one spot are listed in plug-in id order and then manifest order. A plug-in whose commands are all placed elsewhere is a single item in Object › Plug-ins. At API level 1 the key is ignored, repeated or not. --- crates/engine/src/cmd/plugin.rs | 294 ++++++++++++++++++++++++++- crates/engine/src/tests/plugins.rs | 76 +++++++ crates/engine/tests/plugin_fuzz.rs | 32 ++- crates/plugins/src/lib.rs | 2 +- crates/plugins/src/manifest.rs | 190 ++++++++++++++++- crates/plugins/src/permissions.rs | 4 + crates/ui-egui/src/dialogs/plugin.rs | 111 +++++++++- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 34 +++- crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/menus.rs | 2 +- crates/ui-egui/src/menus/labels.rs | 7 +- crates/ui-egui/src/menus/tree.rs | 8 + crates/ui-egui/src/tests/plugins.rs | 211 +++++++++++++++++++ docs/mcp.md | 4 +- docs/plugins.md | 53 ++++- docs/target-app-parity.md | 3 +- 40 files changed, 1016 insertions(+), 40 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..cef2b14775 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -44,6 +44,7 @@ //! images or symbol instances of those kinds, to read only: its output must return each of them //! unchanged ([`objects::decode_output_with`]). +use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; use serde_json::{Map, Value, json}; @@ -113,8 +114,19 @@ pub fn describe(p: &Plugin) -> Value { .iter() .map(|c| { let run = m.for_command(c); - json!({"id": c.id, "command": command_id(&m.id, &c.id), "label": c.shown_label(), "params": run.params_doc(), - "paramsSchema": serde_json::to_value(&run).ok().and_then(|v| v.get("params").cloned())}) + let mut entry = json!({"id": c.id, "command": command_id(&m.id, &c.id), "label": c.shown_label(), "params": run.params_doc(), + "paramsSchema": serde_json::to_value(&run).ok().and_then(|v| v.get("params").cloned())}); + if let Some(place) = &c.place { + let mut menu = json!({"path": place.path}); + if let Some(after) = &place.after { + menu["after"] = json!(permissions::display_text(after, permissions::MAX_SHOWN_NAME)); + } + if placed_menu(p, c).is_none() { + menu["placed"] = json!(false); + } + entry["menu"] = menu; + } + entry }) .collect(); v["commands"] = json!(commands); @@ -466,15 +478,278 @@ pub fn find_spec(id: &str) -> Option<&'static CommandSpec> { command_specs().into_iter().find(|c| c.id == id) } +/// The letters and digits of `label`, lowercased. Two labels with the same key read alike in a menu +/// (`Paste (in Place)` and `Paste in Place`). +fn label_key(label: &str) -> String { + label.chars().filter(|ch| ch.is_alphanumeric()).flat_map(char::to_lowercase).collect() +} + +/// The labels of engine commands whose menu item switches to the label of [`other_state`] (the +/// desktop app's dynamic labels). +pub const SWITCHING_LABELS: &[&str] = &[ + "Preview", + "Outline", + "Show Rulers", + "Change to Global Rulers", + "Show Transparency Grid", + "Lock Guides", + "Hide Slices", + "Show Print Tiling", + "Lock Grid", + "Edit Envelope", + "Edit Contents", + "Start Global Edit", +]; + +/// The label of `label`'s other state, for a menu item that switches between two labels: `Show +/// Edges` for `Hide Edges`, `Unlock Guides` for `Lock Guides`, `Stop Global Edit` for `Start Global +/// Edit`, and the reverse. +pub fn other_state(label: &str) -> Option { + const PAIRS: &[(&str, &str)] = &[ + ("Preview", "Outline"), + ("Change to Global Rulers", "Change to Artboard Rulers"), + ("Edit Envelope", "Edit Contents"), + ("Start Global Edit", "Stop Global Edit"), + ]; + let paired = |&(a, b): &(&'static str, &'static str)| { + if label == a { + Some(b) + } else if label == b { + Some(a) + } else { + None + } + }; + if let Some(other) = PAIRS.iter().find_map(paired) { + return Some(other.to_string()); + } + [("Hide ", "Show "), ("Show ", "Hide "), ("Lock ", "Unlock "), ("Unlock ", "Lock ")] + .iter() + .find_map(|(from, to)| label.strip_prefix(from).map(|rest| format!("{to}{rest}"))) +} + +/// The menu that plug-in `p`'s command `c` is listed in when its manifest's `menu` places it in +/// another menu: that menu's path, or `None` when `c` stays in its plug-in's submenu. It stays +/// there when its menu label ([`Command::menu_label`]) has the same letters and digits, ignoring +/// case, as an engine command listed in that menu (either label of one of [`SWITCHING_LABELS`]), +/// an item of [`DESKTOP_MENU_ITEMS`] there, or a command that a plug-in with a lower id, or an +/// earlier command of `p`, places in that menu. The result is the same with and without the +/// desktop app. Results for installed plug-ins are kept until the registry changes. +pub fn placed_menu(p: &Plugin, c: &Command) -> Option<&'static [&'static str]> { + type Placed = HashMap>; + static PLACED: Mutex> = Mutex::new(None); + c.place.as_ref()?; + let m = p.manifest(); + // Read before the registry, so a result found while the registry changes is kept under the + // revision before the change. + let revision = registry::revision(); + // `plugin.inspect` describes a module that is not installed, or not yet in place of the + // installed one: never kept. + if !registry::get(&m.id).is_some_and(|q| std::ptr::eq(&*q, p)) { + return find_place(p, c); + } + let id = command_id(&m.id, &c.id); + if let Ok(placed) = PLACED.lock() + && let Some((at, known)) = placed.as_ref() + && *at == revision + && let Some(found) = known.get(&id) + { + return *found; + } + let found = find_place(p, c); + if let Ok(mut placed) = PLACED.lock() { + let (at, known) = placed.get_or_insert_with(|| (revision, HashMap::new())); + if *at != revision { + *at = revision; + known.clear(); + } + known.insert(id, found); + } + found +} + +/// [`placed_menu`], found again. +fn find_place(p: &Plugin, c: &Command) -> Option<&'static [&'static str]> { + let place = c.place.as_ref()?; + let m = p.manifest(); + let key = label_key(&c.menu_label(&m.name)); + let reads_like = + |label: &str| label_key(label) == key || SWITCHING_LABELS.contains(&label) && other_state(label).is_some_and(|o| label_key(&o) == key); + if super::command_specs().iter().any(|s| s.menu == place.path && reads_like(s.label)) + || DESKTOP_MENU_ITEMS.iter().any(|(path, label)| *path == place.path && label_key(label) == key) + { + return None; + } + let taken = |name: &str, d: &Command| d.place.as_ref().is_some_and(|e| e.path == place.path) && label_key(&d.menu_label(name)) == key; + // The registry lists plug-ins in id order. `p` itself may not be installed yet (`plugin.inspect`), + // or be replacing the installed module of its id, so its own commands come from `m`. + for q in registry::list() { + let qm = q.manifest(); + if qm.id >= m.id { + break; + } + if qm.commands.iter().any(|d| taken(&qm.name, d)) { + return None; + } + } + for d in &m.commands { + if d.id == c.id { + return Some(place.path); + } + if taken(&m.name, d) { + return None; + } + } + Some(place.path) +} + +/// The labels of the desktop app's own items (not engine commands) in the menus of +/// [`vectorcraft_plugins::manifest::MENU_PLACES`], with both labels of an item that switches +/// between two. [`placed_menu`] reads them, so its result is the same with and without the desktop +/// app. +pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[ + (&["Edit"], "Spelling"), + (&["Edit"], "Edit Custom Dictionary…"), + (&["Edit"], "Edit Colors"), + (&["Edit"], "Edit Original"), + (&["Edit"], "Transparency Flattener Presets…"), + (&["Edit"], "Print Presets…"), + (&["Edit"], "PDF Presets…"), + (&["Edit"], "Tracing Presets…"), + (&["Edit"], "Perspective Grid Presets…"), + (&["Edit"], "Refresh Monitor Profile"), + (&["Edit"], "Keyboard Shortcuts…"), + (&["Edit"], "Preferences…"), + (&["Edit", "Edit Colors"], "Recolor with Preset"), + (&["Object"], "Transform"), + (&["Object"], "Arrange"), + (&["Object"], "Align"), + (&["Object"], "Distribute"), + (&["Object"], "Lock"), + (&["Object"], "Hide"), + (&["Object"], "Slice"), + (&["Object"], "Path"), + (&["Object"], "Shape"), + (&["Object"], "Pattern"), + (&["Object"], "Repeat"), + (&["Object"], "Intertwine"), + (&["Object"], "Objects on Path"), + (&["Object"], "Blend"), + (&["Object"], "Envelope Distort"), + (&["Object"], "Perspective"), + (&["Object"], "Live Paint"), + (&["Object"], "Image Trace"), + (&["Object"], "Text Wrap"), + (&["Object"], "Clipping Mask"), + (&["Object"], "Compound Path"), + (&["Object"], "Artboards"), + (&["Object"], "Graph"), + (&["Object"], "Collect for Export"), + (&["Object"], "Plug-ins"), + (&["Type"], "Font"), + (&["Type"], "Recent Fonts"), + (&["Type"], "Size"), + (&["Type"], "Bold"), + (&["Type"], "Italic"), + (&["Type"], "Glyphs"), + (&["Type"], "Insert Special Character"), + (&["Type"], "Insert Whitespace Character"), + (&["Type"], "Insert Break Character"), + (&["Type"], "Type on a Path"), + (&["Type"], "Dynamic Text Presets"), + (&["Type"], "Threaded Text"), + (&["Type"], "Find Font…"), + (&["Type"], "Change Case"), + (&["Type"], "Bullets and Numbering"), + (&["Type"], "Show Hidden Characters"), + (&["Type"], "Hide Hidden Characters"), + (&["Type"], "Type Orientation"), + (&["Select"], "Same"), + (&["Select"], "Object"), + (&["Select"], "Saved Selection"), + (&["Effect"], "Apply Last Effect"), + (&["Effect"], "Last Effect…"), + (&["Effect"], "3D and Materials"), + (&["Effect"], "Color Adjustments"), + (&["Effect"], "Color Effects"), + (&["Effect"], "Convert to Shape"), + (&["Effect"], "Crop Marks"), + (&["Effect"], "Distort & Transform"), + (&["Effect"], "Path"), + (&["Effect"], "Path Effects"), + (&["Effect"], "Pathfinder"), + (&["Effect"], "Rasterize…"), + (&["Effect"], "Stylize"), + (&["Effect"], "SVG Filters"), + (&["Effect"], "Warp"), + (&["Effect"], "Effect Gallery…"), + (&["Effect"], "Artistic"), + (&["Effect"], "Blur"), + (&["Effect"], "Brush Strokes"), + (&["Effect"], "Distort"), + (&["Effect"], "Pixelate"), + (&["Effect"], "Sharpen"), + (&["Effect"], "Sketch"), + (&["Effect"], "Texture"), + (&["Effect"], "Video"), + (&["Effect"], "Plug-ins"), + (&["View"], "Outline"), + (&["View"], "Preview"), + (&["View"], "Pixel Preview"), + (&["View"], "Trim View"), + (&["View"], "Presentation Mode"), + (&["View"], "Screen Mode"), + (&["View"], "Proof Setup"), + (&["View"], "Zoom In"), + (&["View"], "Zoom Out"), + (&["View"], "Fit Artboard in Window"), + (&["View"], "Fit All in Window"), + (&["View"], "Actual Size"), + (&["View"], "Rotate View"), + (&["View"], "Rotate View to Selection"), + (&["View"], "Reset Rotate View"), + (&["View"], "Hide Edges"), + (&["View"], "Show Edges"), + (&["View"], "Hide Artboards"), + (&["View"], "Show Artboards"), + (&["View"], "Hide Template"), + (&["View"], "Show Template"), + (&["View"], "Rulers"), + (&["View"], "Hide Bounding Box"), + (&["View"], "Show Bounding Box"), + (&["View"], "Hide Text Threads"), + (&["View"], "Show Text Threads"), + (&["View"], "Hide Gradient Annotator"), + (&["View"], "Show Gradient Annotator"), + (&["View"], "Hide Corner Widget"), + (&["View"], "Show Corner Widget"), + (&["View"], "Show Live Paint Gaps"), + (&["View"], "Hide Live Paint Gaps"), + (&["View"], "Guides"), + (&["View"], "Smart Guides"), + (&["View"], "Perspective Grid"), + (&["View"], "Show Grid"), + (&["View"], "Hide Grid"), + (&["View"], "Snap to Grid"), + (&["View"], "Snap to Pixel"), + (&["View"], "Snap to Point"), + (&["View"], "Snap to Glyph"), + (&["View"], "Saved View"), +]; + /// The command spec of plug-in `p`'s command `c`: its id, its label as menus show it (escaped and -/// capped), its menu (Object › Plug-ins › the plug-in's name, or Effect › Plug-ins › it for a live -/// effect: never a menu the manifest names) and its params description. +/// capped, and followed by the plug-in's name when it is listed in another menu), its menu +/// ([`placed_menu`], else Object › Plug-ins › the plug-in's name, or Effect › Plug-ins › it for a +/// live effect) and its params description. fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec { let m = p.manifest(); let id = command_id(&m.id, &c.id); - let label = c.shown_label(); + let placed = placed_menu(p, c); + let label = if placed.is_some() { c.menu_label(&m.name) } else { c.shown_label() }; let top = if m.kind == Kind::Effect { "Effect" } else { "Object" }; let name = permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME); + let submenu = [top, "Plug-ins", name.as_str()]; + let path: &[&str] = placed.unwrap_or(&submenu); let mut fields = String::from("ids?: [object id] (left out or null: the selection), params?: {…} (its parameters; or give them as top-level keys)"); let doc = m.for_command(c).params_doc(); @@ -487,11 +762,14 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec { m.id, c.id ); let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); - let same = |s: &&&'static CommandSpec| s.id == id && s.label == label && s.menu == [top, "Plug-ins", name.as_str()] && s.params == params; + let same = |s: &&&'static CommandSpec| s.id == id && s.label == label && s.menu == path && s.params == params; if let Some(s) = made.iter().find(same) { return s; } - let menu: &'static [&'static str] = Box::leak(vec![top, "Plug-ins", registry::intern(&name)].into_boxed_slice()); + let menu: &'static [&'static str] = match placed { + Some(path) => path, + None => Box::leak(vec![top, "Plug-ins", registry::intern(&name)].into_boxed_slice()), + }; let spec: &'static CommandSpec = Box::leak(Box::new(CommandSpec { id: registry::intern(&id), label: registry::intern(&label), @@ -1270,7 +1548,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..f2d84f00c9 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4571,6 +4571,82 @@ fn plugin_commands_are_registered_run_and_removed() { assert!(s.execute(grow, &json!({})).is_err(), "removed, it no longer runs"); } +/// At API level 2 a command's `menu` lists it in that menu with its plug-in's name after its +/// label, and `plugin.list` gives its `menu` with `after` escaped. A command whose label reads like +/// a built-in command of that menu, or like a command a plug-in with a lower id places there, +/// stays in its plug-in's submenu, and `plugin.list` marks it `placed: false`. Replaced by a module +/// whose command has no `menu`, a command is back in its submenu. +#[test] +fn placed_plugin_commands_are_listed_in_their_menu() { + let mut s = session(); + let placing = |id: &str, name: &str, commands: &str| { + let manifest = format!(r#"{{"id":"{id}","name":"{name}","api":2,"version":"1","kind":"filter","commands":{commands}}}"#); + tpl::returning(&manifest, r#"{"objects":[]}"#) + }; + let (ant, bee, cat) = ("test.engine.place.ant", "test.engine.place.bee", "test.engine.place.cat"); + let low = |id: &str| crate::cmd::plugin::command_id(id, "low"); + let menu_of = |s: &Session, command: &str| listed(s, command).map(|c| c.menu.iter().map(|m| m.to_string()).collect::>()); + let in_select = json!([{"id": "low", "label": "Low Area", "menu": {"path": ["Select"], "after": "\u{202E}Inverse"}}]).to_string(); + let in_select = in_select.as_str(); + + let info = install_wat(&mut s, &placing(ant, "Tidy", in_select)); + let menu = &info["commands"][0]["menu"]; + assert_eq!(menu["path"], json!(["Select"])); + assert!(menu["after"].as_str().is_some_and(|a| a.ends_with("Inverse") && !a.contains('\u{202E}')), "escaped: {menu}"); + assert!(menu.get("placed").is_none(), "{menu}"); + let c = listed(&s, &low(ant)).expect("listed"); + assert_eq!((c.label, menu_of(&s, &low(ant))), ("Low Area (Tidy)", Some(vec!["Select".to_string()]))); + + // Another plug-in of the same name placing the same label at the same spot stays in its submenu. + let info = install_wat(&mut s, &placing(bee, "Tidy", in_select)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + assert_eq!(listed(&s, &low(bee)).map(|c| c.label), Some("Low Area")); + assert_eq!(menu_of(&s, &low(bee)), Some(vec!["Object".into(), "Plug-ins".into(), "Tidy".into()])); + assert_eq!(menu_of(&s, &low(ant)), Some(vec!["Select".to_string()])); + + // `Paste (in Place)` reads like Edit's Paste in Place; Keep is placed. + let edit = r#"[{"id":"paste","label":"Paste","menu":{"path":["Edit"]}},{"id":"keep","label":"Keep","menu":{"path":["Edit"]}}]"#; + let info = install_wat(&mut s, &placing(cat, "in Place", edit)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + assert!(info["commands"][1]["menu"].get("placed").is_none()); + let paste = crate::cmd::plugin::command_id(cat, "paste"); + assert_eq!(menu_of(&s, &paste), Some(vec!["Object".into(), "Plug-ins".into(), "in Place".into()])); + assert_eq!(menu_of(&s, &crate::cmd::plugin::command_id(cat, "keep")), Some(vec!["Edit".to_string()])); + // `Stop Global (Edit)` reads like the other label of Select's Start Global Edit. + let dog = "test.engine.place.dog"; + let info = install_wat(&mut s, &placing(dog, "Edit", r#"[{"id":"stop","label":"Stop Global","menu":{"path":["Select"]}}]"#)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + run(&mut s, "plugin.remove", json!({"id": dog})); + // Object's Show All has one label, so `Hide (All)` is placed beside it. + let all = "test.engine.place.all"; + let info = install_wat(&mut s, &placing(all, "All", r#"[{"id":"hide","label":"Hide","menu":{"path":["Object"]}}]"#)); + assert!(info["commands"][0]["menu"].get("placed").is_none(), "{}", info["commands"][0]); + assert_eq!(menu_of(&s, &crate::cmd::plugin::command_id(all, "hide")), Some(vec!["Object".to_string()])); + run(&mut s, "plugin.remove", json!({"id": all})); + // `Hide (Edges)` reads like the desktop app's View › Hide Edges, with or without the desktop app. + let edges = "test.engine.place.edges"; + let info = install_wat(&mut s, &placing(edges, "Edges", r#"[{"id":"hide","label":"Hide","menu":{"path":["View"]}}]"#)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + run(&mut s, "plugin.remove", json!({"id": edges})); + // Inspecting a plug-in that is not installed reports what installing it gives: of two commands + // with one label at one spot, the second stays in its submenu. + let twice = r#"[{"id":"a","label":"Low","menu":{"path":["Select"]}},{"id":"b","label":"Low","menu":{"path":["Select"]}}]"#; + let data = vectorcraft_format::base64_encode(&wat::parse_str(placing("test.engine.place.eel", "Eel", twice)).unwrap()); + let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": data})); + assert!(inspected["commands"][0]["menu"].get("placed").is_none(), "{inspected}"); + assert_eq!(inspected["commands"][1]["menu"]["placed"], json!(false), "{inspected}"); + + // Replaced by a module whose command has no `menu`, Ant's command is back in its submenu and + // Bee's takes the spot. + install_wat(&mut s, &placing(ant, "Tidy", r#"[{"id":"low","label":"Low Area"}]"#)); + assert_eq!(menu_of(&s, &low(ant)), Some(vec!["Object".into(), "Plug-ins".into(), "Tidy".into()])); + assert_eq!(menu_of(&s, &low(bee)), Some(vec!["Select".to_string()])); + for id in [ant, bee, cat] { + run(&mut s, "plugin.remove", json!({"id": id})); + } + assert!(listed(&s, &low(bee)).is_none()); +} + /// A command run is journaled like any other, so an action records it with its parameters and /// plays it back. #[test] diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 35f29a2a25..158a4d6798 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -707,9 +707,10 @@ proptest! { } /// Manifests with hostile `commands` (junk of every type, bad and repeated ids, labels with - /// control and bidirectional override characters, a `menu` naming another menu, junk - /// parameters) parse to an error or to commands whose menu labels show no hidden character and - /// that sit under Plug-ins alone; installing one and running each of its commands ends as an + /// control and bidirectional override characters, a `menu` of any shape naming any menu, junk + /// parameters) at API level 1 or 2 parse to an error or to commands whose menu labels show no + /// hidden character and that sit under Plug-ins, or at level 2 in one of the menus a manifest + /// may name, with the plug-in's name; installing one and running each of its commands ends as an /// error or an edit, never a panic, and the document then renders and exports. #[test] fn hostile_manifest_commands_never_crash( @@ -723,7 +724,17 @@ proptest! { 1 => "[a-z\u{0007}\n]{1,8}".prop_map(Value::from), 1 => arb_junk(), ], - prop_oneof![Just(Value::Null), Just(json!("File")), arb_junk()], + prop_oneof![ + Just(Value::Null), + Just(json!("File")), + Just(json!({"path": ["Select"], "after": "Inverse"})), + Just(json!({"path": ["Object", "Path"]})), + Just(json!({"path": ["File"]})), + Just(json!({"path": ["Select"], "after": "\u{202E}Inverse"})), + arb_junk().prop_map(|j| json!({"path": j})), + arb_junk().prop_map(|j| json!({"path": ["Select"], "after": j})), + arb_junk(), + ], prop_oneof![Just(Value::Null), Just(json!({"by": {"type": "number", "min": 0, "max": 10, "default": 2}})), arb_junk()], ) .prop_map(|(id, label, menu, params)| { @@ -742,8 +753,9 @@ proptest! { ), junk in prop::option::weighted(0.1, arb_junk()), given in prop_oneof![Just(json!({})), Just(json!({"by": 3})), arb_junk()], + api in 1u32..=2, ) { - let mut m = json!({"id": "fuzz.commands", "name": "Fuzz \u{202E}Commands", "kind": kind}); + let mut m = json!({"id": "fuzz.commands", "name": "Fuzz \u{202E}Commands", "kind": kind, "api": api}); if matches!(kind, "exporter" | "importer") { m["extensions"] = json!(["fz"]); } @@ -756,6 +768,12 @@ proptest! { let shown = c.shown_label(); prop_assert!(!shown.chars().any(|ch| ch.is_control() || matches!(ch, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", shown); prop_assert!(shown.chars().count() <= vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + let placed = c.menu_label(&man.name); + prop_assert!(!placed.chars().any(|ch| ch.is_control() || matches!(ch, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", placed); + if let Some(place) = &c.place { + prop_assert!(api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&place.path), "{:?}", place); + prop_assert!(placed.ends_with(')') && placed.len() > shown.len(), "a placed item names its plug-in: {}", placed); + } } } let mut s = rich_session(); @@ -774,7 +792,9 @@ proptest! { let ran = r.map_err(|msg| TestCaseError::fail(format!("panicked running {text}: {msg}")))?; prop_assert!(ran.is_empty() || parsed.is_ok(), "a manifest that doesn't parse installed: {}", text); for (id, menu) in &ran { - prop_assert!(menu.len() == 3 && menu[1] == "Plug-ins" && matches!(menu[0], "Object" | "Effect"), "{id}: {menu:?}"); + let submenu = menu.len() == 3 && menu[1] == "Plug-ins" && matches!(menu[0], "Object" | "Effect"); + let place = api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&menu.as_slice()); + prop_assert!(submenu || place, "{id}: {menu:?}"); } renders(&s, "after hostile commands")?; vectorcraft_plugins::registry::remove("fuzz.commands"); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..dada995bb3 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -52,7 +52,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; -pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; +pub use manifest::{Budget, Command, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..b96ae96bde 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -31,6 +31,74 @@ pub const MAX_ALLOWED_COMMANDS: usize = 256; /// Longest command id a manifest's `commandAllowlist` names, in bytes. pub const MAX_ALLOWED_ID: usize = 128; +/// The menus a command's `menu` may name, each as its path of English menu labels. File, Window, +/// Help and the application menu are not among them, and neither are the submenus that list +/// files, fonts, panels or other plug-ins. +pub const MENU_PLACES: &[&[&str]] = &[ + &["Edit"], + &["Edit", "Edit Colors"], + &["Object"], + &["Object", "Transform"], + &["Object", "Arrange"], + &["Object", "Path"], + &["Object", "Compound Path"], + &["Object", "Clipping Mask"], + &["Type"], + &["Select"], + &["Select", "Same"], + &["Select", "Object"], + &["Effect"], + &["View"], +]; + +/// Where a command's `menu` places it: in the menu at `path` (one of [`MENU_PLACES`]), after the +/// built-in item labeled `after` (1 to 64 printable characters), or at the end of that menu when +/// `after` is left out or names no built-in item there. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct MenuPlace { + pub path: &'static [&'static str], + #[serde(skip_serializing_if = "Option::is_none")] + pub after: Option, +} + +impl MenuPlace { + /// Reads a command's `menu` value: `{"path": [label, …], "after"?: label}`. + fn read(v: &Value) -> std::result::Result { + let wrong_path = || { + let k = "menu.path"; + let places: Vec = + MENU_PLACES.iter().map(|p| format!("[{}]", p.iter().map(|l| format!("{l:?}")).collect::>().join(", "))).collect(); + format!("`{k}` must be one of {}", places.join(", ")) + }; + let Some(o) = v.as_object() else { + let key = "menu"; + return Err(format!("`{key}` must be an object")); + }; + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "path" | "after")) { + let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); + return Err(format!("unknown key `{k}`; the keys here are {}", "path, after")); + } + let path: Vec<&str> = match o.get("path").and_then(Value::as_array) { + Some(path) => path.iter().map(Value::as_str).collect::>().ok_or_else(wrong_path)?, + None => return Err(wrong_path()), + }; + let path = *MENU_PLACES.iter().find(|p| **p == path.as_slice()).ok_or_else(wrong_path)?; + let key = "menu.after"; + let after = match o.get("after") { + None => None, + Some(Value::String(s)) => { + let s = s.trim(); + if s.is_empty() || s.chars().count() > 64 || s.chars().any(char::is_control) { + return Err(format!("`{key}` must be 1-64 printable characters")); + } + Some(s.to_string()) + } + Some(_) => return Err(format!("`{key}` must be a string")), + }; + Ok(MenuPlace { path, after }) + } +} + /// What a plug-in is. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -220,9 +288,9 @@ pub struct Param { } /// A menu command a plug-in adds (`commands`): the host lists it under Object › Plug-ins › the -/// plug-in's name (Effect › Plug-ins for a live effect's), runs it as the command -/// `plugin..`, and calls the plug-in's `vc_run` with `_context.command` set to -/// `id` and the parameters it declares. +/// plug-in's name (Effect › Plug-ins for a live effect's), or in the menu its `menu` names, runs it +/// as the command `plugin..`, and calls the plug-in's `vc_run` with +/// `_context.command` set to `id` and the parameters it declares. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Command { /// `[a-z][a-z0-9_]*`, at most [`MAX_COMMAND_ID`] characters, unique within the manifest. @@ -233,6 +301,13 @@ pub struct Command { /// Parameters in declaration (dialog) order, declared as the manifest's own are. #[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")] pub params: Vec<(String, Param)>, + /// The menu it is listed in instead of the plug-in's submenu (`menu`, read at + /// [`crate::permissions::MENU_API`] and later). + #[serde(rename = "menu", skip_deserializing, skip_serializing_if = "Option::is_none")] + pub place: Option, + /// Each `menu` value the manifest gives, until [`Manifest::parse`] reads them. + #[serde(skip)] + pub(crate) declared_menu: Vec, } impl Command { @@ -241,6 +316,18 @@ impl Command { pub fn shown_label(&self) -> String { crate::permissions::display_text(self.label.trim(), crate::permissions::MAX_SHOWN_NAME) } + + /// The label its menu item shows for plug-in `plugin_name`: [`Command::shown_label`], and for a + /// command placed in another menu, followed by the plug-in's name in parentheses. + pub fn menu_label(&self, plugin_name: &str) -> String { + match self.place { + None => self.shown_label(), + Some(_) => { + let name = crate::permissions::display_text(plugin_name.trim(), crate::permissions::MAX_SHOWN_NAME); + format!("{} ({name})", self.shown_label()) + } + } + } } impl From for Param { @@ -360,8 +447,9 @@ impl Manifest { if serde_json::from_str::(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) { return Err(Error::Manifest("`paintOutput` may only be true".into())); } - let man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?; + let mut man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?; man.validate()?; + man.read_places()?; Ok(man) } @@ -397,6 +485,31 @@ impl Manifest { self.commands.iter().find(|c| c.id == id) } + /// Reads each command's `menu` into its [`Command::place`] at + /// [`crate::permissions::MENU_API`] and later, and drops it below that level, where the key is + /// ignored. A `menu` that names a menu outside [`MENU_PLACES`], has the wrong shape or is given + /// twice is refused, and the error names the command. + fn read_places(&mut self) -> Result<()> { + let reads = self.api >= permissions::MENU_API; + for (i, c) in self.commands.iter_mut().enumerate() { + let menus = std::mem::take(&mut c.declared_menu); + if !reads { + continue; + } + let name = command_name(i, &c.id); + let place = match menus.as_slice() { + [] => continue, + [menu] => MenuPlace::read(menu), + _ => { + let key = "menu"; + Err(format!("duplicate field `{key}`")) + } + }; + c.place = Some(place.map_err(|e| Error::Manifest(format!("command {name}: {e}")))?); + } + Ok(()) + } + /// Checks what the module declared: its id, name and text lengths, its extensions, a budget its /// kind may have (only a filter may be heavy), and each parameter and its dialog layout. fn validate(&self) -> Result<()> { @@ -805,7 +918,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu Err(A::Error::custom(self.wrong())) } fn visit_map>(self, mut map: A) -> std::result::Result { - let (mut id, mut label, mut params) = (None::, None::, None::); + let (mut id, mut label, mut params, mut menu) = (None::, None::, None::, Vec::::new()); let named = |id: &Option, e: &dyn std::fmt::Display| { A::Error::custom(format!("command {}: {e}", command_name(self.0, id.as_deref().unwrap_or_default()))) }; @@ -824,6 +937,11 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu params = Some(map.next_value().map_err(|e| named(&id, &e))?); false } + // A repeated `menu` is refused only where the key is read ([`Manifest::parse`]). + "menu" => { + menu.push(map.next_value().map_err(|e| named(&id, &e))?); + false + } "id" | "label" | "params" => true, _ => { map.next_value::()?; @@ -840,7 +958,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu let Some(label) = label else { return Err(named(&Some(id), &"missing field `label`")); }; - Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default() }) + Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default(), place: None, declared_menu: menu }) } } @@ -1216,7 +1334,7 @@ mod tests { } /// A filter or a live effect lists menu commands with their own parameters; a `menu` key is - /// ignored. A malformed entry, a bad or repeated id, a label that isn't printable and too many + /// ignored at API level 1. A malformed entry, a bad or repeated id, a label that isn't printable and too many /// commands are refused, and the error names the command. #[test] fn commands_are_checked_and_errors_name_them() { @@ -1238,7 +1356,7 @@ mod tests { assert!(serde_json::to_value(Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap()).unwrap().get("commands").is_none()); let effect = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","commands":[{"id":"c","label":"C"}]}"#).unwrap(); assert_eq!(effect.commands.len(), 1); - let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new() }.shown_label(); + let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new(), place: None, declared_menu: Vec::new() }.shown_label(); assert_eq!(label("Flip\u{202E}txt.exe"), "Flip\\u{202E}txt.exe"); let many: Vec = (0..=MAX_COMMANDS).map(|i| format!(r#"{{"id":"c{i}","label":"C"}}"#)).collect(); @@ -1294,6 +1412,62 @@ mod tests { assert!(hidden.unwrap_err().to_string().contains("command `x\\u{202E}`"), "an id in an error is escaped"); } + /// At API level 2 a command's `menu` places it in one of [`MENU_PLACES`], after a named item or + /// at the end; a menu outside them (File, Help, Window, Edit › Preferences) or a `menu` of the + /// wrong shape is refused and the error names the command. At level 1 the key is ignored. + #[test] + fn a_command_menu_names_an_allowed_place() { + let with = |api: u32, menu: &str| { + format!( + r#"{{"id":"org.example.low","name":"Low Area","api":{api},"kind":"filter","commands":[{{"id":"low","label":"Low Area Closed Paths","menu":{menu}}}]}}"# + ) + }; + let m = Manifest::parse(with(2, r#"{"path":["Select"],"after":" Inverse "}"#).as_bytes()).unwrap(); + let c = &m.commands[0]; + assert_eq!(c.place, Some(MenuPlace { path: &["Select"], after: Some("Inverse".into()) })); + assert_eq!(c.menu_label(&m.name), "Low Area Closed Paths (Low Area)", "a placed item names its plug-in"); + assert_eq!(serde_json::to_value(&m).unwrap()["commands"][0]["menu"], json!({"path": ["Select"], "after": "Inverse"})); + let end = Manifest::parse(with(2, r#"{"path":["Select","Same"]}"#).as_bytes()).unwrap(); + assert_eq!(end.commands[0].place, Some(MenuPlace { path: &["Select", "Same"], after: None })); + + // API level 1 ignores the key, as hosts before it did: the command stays in the plug-in's submenu. + for menu in [r#"{"path":["Select"]}"#, r#""File""#, r#"{"path":["File"]}"#, r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#] { + let old = Manifest::parse(with(1, menu).as_bytes()).unwrap(); + assert_eq!(old.commands[0].place, None, "{menu}"); + assert_eq!(old.commands[0].menu_label(&old.name), "Low Area Closed Paths"); + } + + let long = format!(r#"{{"path":["Select"],"after":"{}"}}"#, "x".repeat(65)); + for (menu, says) in [ + (r#"{"path":["File"]}"#, "`menu.path` must be one of"), + (r#"{"path":["Help"]}"#, "`menu.path` must be one of"), + (r#"{"path":["Window"]}"#, "`menu.path` must be one of"), + (r#"{"path":["VectorCraft"]}"#, "`menu.path` must be one of"), + (r#"{"path":["Edit","Preferences"]}"#, "`menu.path` must be one of"), + (r#"{"path":["Object","Plug-ins"]}"#, "`menu.path` must be one of"), + (r#"{"path":["select"]}"#, "`menu.path` must be one of"), + (r#"{"path":[]}"#, "`menu.path` must be one of"), + (r#"{"path":"Select"}"#, "`menu.path` must be one of"), + (r#"{"path":["Select",1]}"#, "`menu.path` must be one of"), + (r#"{"after":"Inverse"}"#, "`menu.path` must be one of"), + (r#""Select""#, "`menu` must be an object"), + (r#"["Select"]"#, "`menu` must be an object"), + (r#"{"path":["Select"],"before":"Inverse"}"#, "unknown key `before`"), + (r#"{"path":["Select"],"after":3}"#, "`menu.after` must be a string"), + (r#"{"path":["Select"],"after":null}"#, "`menu.after` must be a string"), + (r#"{"path":["Select"],"after":" "}"#, "`menu.after` must be 1-64 printable characters"), + (r#"{"path":["Select"],"after":"In\u0007verse"}"#, "`menu.after` must be 1-64 printable characters"), + (long.as_str(), "`menu.after` must be 1-64 printable characters"), + (r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#, "duplicate field `menu`"), + ] { + let e = Manifest::parse(with(2, menu).as_bytes()).unwrap_err().to_string(); + assert!(e.contains("command `low`") && e.contains(says), "{menu}: {e}"); + } + let twice = + r#"{"id":"a","name":"x","api":2,"kind":"filter","commands":[{"id":"x","label":"A","menu":{"path":["Edit"]},"menu":{"path":["Edit"]}}]}"#; + assert!(Manifest::parse(twice.as_bytes()).unwrap_err().to_string().contains("duplicate field `menu`")); + } + #[test] fn strings_and_number_lists_resolve_like_the_other_types() { let m = Manifest::parse( diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..a07b7a7a64 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -25,6 +25,10 @@ pub const PROGRESS_API: u32 = 2; /// The API level that adds a filter's `inputs` ([`crate::InputKind`]). pub const INPUTS_API: u32 = 2; +/// The API level that reads a command's `menu` ([`crate::manifest::MenuPlace`]); below it the key +/// is ignored. +pub const MENU_API: u32 = 2; + /// Most permissions a manifest may list. pub const MAX_PERMISSIONS: usize = 16; diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 706188f6da..4e42b33a1a 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -11,7 +11,8 @@ //! background too, with its progress and Cancel, when it runs at once or when OK runs it without a //! kept preview ([`in_background`]). A filter or live effect with commands of //! its own is a submenu named after it, holding its item and then its commands; a command with -//! parameters opens the same dialog for them ([`open_command`]). Exporters are formats of File › Export › +//! parameters opens the same dialog for them ([`open_command`]). A command whose manifest names +//! another menu is listed in that menu instead ([`place_commands`]). Exporters are formats of File › Export › //! Export As; one with parameters opens dialog `pluginExport` once the file is picked, and its //! Export button writes the file. Importers open the files File › Open finds no built-in format //! for, and File › Open With lists them, to open a file with one of them by name; one with @@ -70,6 +71,114 @@ fn with_commands(plugin: &Plugin, own: Item) -> Item { Item::Sub(registry::intern(&permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME)), items) } +/// Moves each plug-in command whose manifest's `menu` names another menu +/// ([`vectorcraft_plugins::MenuPlace`]) from its plug-in's submenu into that menu of `tree`: after +/// the built-in item its `after` names (with or without an ellipsis), or at the end of the menu. +/// Its label ends with the plug-in's name ([`vectorcraft_plugins::Command::menu_label`]). +/// Commands placed at the same spot are listed in plug-in id order and then in manifest order. A +/// plug-in's submenu left with its own item alone becomes that item. A command whose menu `tree` +/// doesn't have, or that [`vectorcraft_engine::cmd::plugin::placed_menu`] leaves in its plug-in's +/// submenu, stays there. +pub fn place_commands(tree: &mut [(&'static str, Vec)]) { + let mut spots: Vec<(&'static [&'static str], Option, Vec)> = Vec::new(); + for p in registry::list() { + let m = p.manifest(); + if !matches!(m.kind, Kind::Filter | Kind::Effect) { + continue; + } + for c in &m.commands { + let Some(place) = &c.place else { continue }; + if vectorcraft_engine::cmd::plugin::placed_menu(&p, c).is_none() { + continue; + } + // An `after` that names no built-in item of the menu means the end of it, as no `after` does. + let after = place + .after + .as_deref() + .map(|a| anchor_key(a).to_string()) + .filter(|a| menu_at(tree, place.path).is_some_and(|menu| menu.iter().any(|it| is_anchor(it, a)))); + let id = registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &c.id)); + let item = Item::Cmd(label(&c.menu_label(&m.name), !c.params.is_empty()), id, Value::Null); + match spots.iter_mut().find(|s| s.0 == place.path && s.1 == after) { + Some(s) => s.2.push(item), + None => spots.push((place.path, after, vec![item])), + } + } + } + spots.retain(|s| menu_at(tree, s.0).is_some()); + if spots.is_empty() { + return; + } + let placed: std::collections::HashSet<&str> = spots + .iter() + .flat_map(|s| s.2.iter()) + .filter_map(|it| match it { + Item::Cmd(_, id, _) => Some(*id), + _ => None, + }) + .collect(); + // Plug-in submenus are under Object › Plug-ins and Effect › Plug-ins. + for (_, items) in tree.iter_mut().filter(|(title, _)| matches!(*title, "Object" | "Effect")) { + leave_out(items, &placed); + } + for (path, after, items) in spots { + let Some(menu) = menu_at(tree, path) else { continue }; + let at = after.and_then(|a| menu.iter().position(|it| is_anchor(it, &a))).map_or(menu.len(), |i| i + 1); + menu.splice(at..at, items); + } +} + +/// A label as `after` matches it: trimmed, without a closing ellipsis. +fn anchor_key(label: &str) -> &str { + label.trim().trim_end_matches('…').trim_end() +} + +/// Is `it` the built-in item or submenu labeled `key` ([`anchor_key`])? An item of +/// [`crate::menus::DYNAMIC_LABELS`] matches by the label of either of its states +/// ([`vectorcraft_engine::cmd::plugin::other_state`]). Items that list a plug-in are never an anchor. +fn is_anchor(it: &Item, key: &str) -> bool { + match it { + Item::Cmd(l, id, p) => { + let toggles = crate::menus::DYNAMIC_LABELS.contains(l); + let other = || vectorcraft_engine::cmd::plugin::other_state(l).is_some_and(|o| o == key); + !crate::menus::lists_plugin(id, p) && (anchor_key(l) == key || toggles && other()) + } + Item::Sub(l, children) => !crate::menus::holds_plugin_commands(children) && anchor_key(l) == key, + _ => false, + } +} + +/// The built-in menu of `tree` at `path`: a top-level menu, then its submenus by label. +fn menu_at<'a>(tree: &'a mut [(&'static str, Vec)], path: &[&str]) -> Option<&'a mut Vec> { + let (first, rest) = path.split_first()?; + let mut menu = &mut tree.iter_mut().find(|(title, _)| title == first)?.1; + for segment in rest { + menu = menu.iter_mut().find_map(|it| match it { + Item::Sub(l, children) if l == segment && !crate::menus::holds_plugin_commands(children) => Some(children), + _ => None, + })?; + } + Some(menu) +} + +/// Takes the commands in `placed` out of the plug-in submenus under `items`; a submenu left with no +/// command becomes its plug-in's own item. +fn leave_out(items: &mut [Item], placed: &std::collections::HashSet<&str>) { + for it in items.iter_mut() { + let Item::Sub(_, children) = it else { continue }; + if !crate::menus::holds_plugin_commands(children) { + leave_out(children, placed); + continue; + } + children.retain(|c| !matches!(c, Item::Cmd(_, id, _) if placed.contains(id))); + if !children.iter().any(|c| matches!(c, Item::Cmd(_, id, _) if vectorcraft_engine::cmd::plugin::is_command_id(id))) + && let Some(own) = children.first().cloned() + { + *it = own; + } + } +} + /// Object › Plug-ins: the installed object filters (each with its commands, if it has any), then /// Install Plug-in… and Reload Plug-ins. pub fn object_menu() -> Vec { diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..94332b3e72 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7691,6 +7691,7 @@ variable-list-end {0}, {1} {0} i {1} @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants «{_1}» demana un pressupost elevat (cada execució fins a {minutes} minuts i {times} vegades les instruccions habituals): una persona l’ha d’aprovar a l’aplicació d’escriptori, o passa `allowHeavy: true` en una sessió iniciada amb --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` ha de tenir 1-64 caràcters imprimibles +@msg `{key}` must be 1-64 printable characters `{key}` ha de tenir 1-64 caràcters imprimibles @msg `version`, `description` or `author` is too long `version`, `description` o `author` és massa llarg @msg `warnings` must be a list of strings `warnings` ha de ser una llista de cadenes @msg `{k}` must be one of {_1} `{k}` ha de ser un de {_1} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..27d1e9175a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7302,6 +7302,7 @@ axis Y Axis osa Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ žádá o velký výpočetní rozpočet (každé spuštění až {minutes} minut a {times}krát víc instrukcí než obvykle): musí ho schválit člověk v desktopové aplikaci, nebo předejte `allowHeavy: true` v relaci spuštěné s --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` musí mít 1-64 tisknutelných znaků +@msg `{key}` must be 1-64 printable characters `{key}` musí mít 1-64 tisknutelných znaků @msg `version`, `description` or `author` is too long `version`, `description` nebo `author` je příliš dlouhé @msg `warnings` must be a list of strings `warnings` musí být seznam řetězců @msg `{k}` must be one of {_1} `{k}` musí být jedno z {_1} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..8f7631cf9a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -532,6 +532,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg an exporter always gets an export's budget: leave `budget` out en eksportør får altid et eksportbudget: udelad `budget` @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants »{_1}« beder om et tungt budget (hver kørsel op til {minutes} minutter og {times} gange de sædvanlige instruktioner): en person skal godkende det i skrivebordsappen, eller send `allowHeavy: true` i en session startet med --allow-plugin-grants @msg `name` must be 1-64 printable characters `name` skal være 1-64 tegn, der kan udskrives +@msg `{key}` must be 1-64 printable characters `{key}` skal være 1-64 tegn, der kan udskrives @msg `version`, `description` or `author` is too long `version`, `description` eller `author` er for lang @msg `warnings` must be a list of strings `warnings` skal være en liste med strenge @msg `{k}` must be one of {_1} `{k}` skal være en af {_1} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..4ebb7c9220 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6885,6 +6885,7 @@ axis Y Axis Y-Achse @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ verlangt ein großes Rechenbudget (jede Ausführung bis zu {minutes} Minuten und {times}-mal so viele Anweisungen wie üblich): Eine Person muss es in der Desktop-App genehmigen, oder übergeben Sie `allowHeavy: true` in einer mit --allow-plugin-grants gestarteten Sitzung # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` muss 1-64 druckbare Zeichen haben +@msg `{key}` must be 1-64 printable characters `{key}` muss 1-64 druckbare Zeichen haben @msg `version`, `description` or `author` is too long `version`, `description` oder `author` ist zu lang @msg `warnings` must be a list of strings `warnings` muss eine Liste von Zeichenketten sein @msg `{k}` must be one of {_1} `{k}` muss einer der folgenden Werte sein: {_1} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..d75cd4c4fb 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7291,6 +7291,7 @@ axis Y Axis Άξονας Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants το «{_1}» ζητά μεγάλο υπολογιστικό προϋπολογισμό (κάθε εκτέλεση έως {minutes} λεπτά και {times} φορές τις συνήθεις εντολές): πρέπει να το εγκρίνει ένα άτομο στην εφαρμογή επιφάνειας εργασίας ή περάστε `allowHeavy: true` σε μια συνεδρία που ξεκίνησε με --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters το `name` πρέπει να έχει 1-64 εκτυπώσιμους χαρακτήρες +@msg `{key}` must be 1-64 printable characters το `{key}` πρέπει να έχει 1-64 εκτυπώσιμους χαρακτήρες @msg `version`, `description` or `author` is too long το `version`, το `description` ή το `author` είναι πολύ μεγάλο @msg `warnings` must be a list of strings το `warnings` πρέπει να είναι λίστα συμβολοσειρών @msg `{k}` must be one of {_1} το `{k}` πρέπει να είναι ένα από τα {_1} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..5a2b8f9857 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7277,6 +7277,7 @@ axis Y Axis Eje Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” pide un presupuesto de cálculo grande (cada ejecución hasta {minutes} minutos y {times} veces las instrucciones habituales): una persona debe aprobarlo en la aplicación de escritorio, o pasa `allowHeavy: true` en una sesión iniciada con --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` debe tener 1-64 caracteres imprimibles +@msg `{key}` must be 1-64 printable characters `{key}` debe tener 1-64 caracteres imprimibles @msg `version`, `description` or `author` is too long `version`, `description` o `author` es demasiado largo @msg `warnings` must be a list of strings `warnings` debe ser una lista de cadenas @msg `{k}` must be one of {_1} `{k}` debe ser uno de estos: {_1} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..57f87528a4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7368,6 +7368,7 @@ axis Y Axis Y-akseli @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants ”{_1}” pyytää suurta laskentabudjettia (jokainen ajo enintään {minutes} minuuttia ja {times} kertaa tavallinen määrä käskyjä): ihmisen on hyväksyttävä se työpöytäsovelluksessa, tai anna `allowHeavy: true` istunnossa, joka on käynnistetty valitsimella --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name`-kentässä on oltava 1-64 tulostettavaa merkkiä +@msg `{key}` must be 1-64 printable characters `{key}`-kentässä on oltava 1-64 tulostettavaa merkkiä @msg `version`, `description` or `author` is too long `version`, `description` tai `author` on liian pitkä @msg `warnings` must be a list of strings `warnings` on oltava merkkijonojen luettelo @msg `{k}` must be one of {_1} `{k}` on oltava jokin seuraavista: {_1} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..56ea0bac94 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7298,6 +7298,7 @@ axis Y Axis Axe Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants « {_1} » demande un budget de calcul important (chaque exécution jusqu’à {minutes} minutes et {times} fois les instructions habituelles) : une personne doit l’approuver dans l’application de bureau, ou passez `allowHeavy: true` dans une session démarrée avec --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` doit compter 1-64 caractères imprimables +@msg `{key}` must be 1-64 printable characters `{key}` doit compter 1-64 caractères imprimables @msg `version`, `description` or `author` is too long `version`, `description` ou `author` est trop long @msg `warnings` must be a list of strings `warnings` doit être une liste de chaînes @msg `{k}` must be one of {_1} `{k}` doit valoir l’une de ces valeurs : {_1} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..54817a47c7 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7114,6 +7114,7 @@ arrowhead Feather पंख @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" या "lineEndHalf" होना चाहिए। @msg `name` is empty `name` खाली है @msg `name` must be 1-64 printable characters `name` में 1-64 प्रिंट करने योग्य वर्ण होने चाहिए +@msg `{key}` must be 1-64 printable characters `{key}` में 1-64 प्रिंट करने योग्य वर्ण होने चाहिए @msg `names` is a list of preset names `names` प्रीसेट नामों की सूची है @msg `names` lists preset names `names` प्रीसेट नामों की सूची देता है @msg `names` must be a list of names `names` को नामों की सूची होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..8b6374bd63 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7287,6 +7287,7 @@ axis Y Axis Y tengely @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants a(z) „{_1}” nagy számítási keretet kér (futásonként legfeljebb {minutes} perc és a szokásos utasításszám {times}-szorosa): egy személynek jóvá kell hagynia az asztali alkalmazásban, vagy add meg az `allowHeavy: true` értéket egy --allow-plugin-grants kapcsolóval indított munkamenetben # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters a `name` 1-64 nyomtatható karakter legyen +@msg `{key}` must be 1-64 printable characters a `{key}` 1-64 nyomtatható karakter legyen @msg `version`, `description` or `author` is too long a `version`, a `description` vagy az `author` túl hosszú @msg `warnings` must be a list of strings a `warnings` karakterláncok listája legyen @msg `{k}` must be one of {_1} `{k}`: ezek egyike kell: {_1} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..4ca1800dc3 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -415,6 +415,7 @@ @msg an exporter always gets an export's budget: leave `budget` out pengekspor selalu mendapat anggaran ekspor: hilangkan `budget` @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” meminta anggaran berat (setiap proses hingga {minutes} menit dan {times} kali instruksi biasa): seseorang harus menyetujuinya di aplikasi desktop, atau berikan `allowHeavy: true` dalam sesi yang dimulai dengan --allow-plugin-grants @msg `name` must be 1-64 printable characters `name` harus berupa 1-64 karakter yang dapat dicetak +@msg `{key}` must be 1-64 printable characters `{key}` harus berupa 1-64 karakter yang dapat dicetak @msg `version`, `description` or `author` is too long `version`, `description` atau `author` terlalu panjang @msg `warnings` must be a list of strings `warnings` harus berupa daftar string @msg `{k}` must be one of {_1} `{k}` harus salah satu dari {_1} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..3a8c3a60d1 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6924,6 +6924,7 @@ axis Y Axis Asse Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” chiede un budget di calcolo elevato (ogni esecuzione fino a {minutes} minuti e {times} volte le istruzioni consuete): una persona deve approvarlo nell’app desktop, oppure passa `allowHeavy: true` in una sessione avviata con --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` deve avere 1-64 caratteri stampabili +@msg `{key}` must be 1-64 printable characters `{key}` deve avere 1-64 caratteri stampabili @msg `version`, `description` or `author` is too long `version`, `description` o `author` è troppo lungo @msg `warnings` must be a list of strings `warnings` deve essere un elenco di stringhe @msg `{k}` must be one of {_1} `{k}` deve essere uno dei seguenti: {_1} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..f261704aae 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6999,6 +6999,7 @@ axis Y Axis Y 軸 @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants 「{_1}」は大きな計算予算を求めています (1 回の実行につき最大 {minutes} 分、通常の {times} 倍の命令)。デスクトップ アプリで人が承認するか、--allow-plugin-grants を付けて開始したセッションで `allowHeavy: true` を指定してください # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` は印刷可能な 1-64 文字にしてください +@msg `{key}` must be 1-64 printable characters `{key}` は印刷可能な 1-64 文字にしてください @msg `version`, `description` or `author` is too long `version`、`description` または `author` が長すぎます @msg `warnings` must be a list of strings `warnings` は文字列のリストにしてください @msg `{k}` must be one of {_1} `{k}` は {_1} のいずれかにしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..ef9708d8a0 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9404,6 +9404,7 @@ axis Y Axis Y ღერძი @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ დიდ გამოთვლით ბიუჯეტს ითხოვს (თითო გაშვება {minutes} წუთამდე და ჩვეულებრივზე {times}-ჯერ მეტი ინსტრუქცია): ის დესკტოპის აპში ადამიანმა უნდა დაამტკიცოს, ან გადაეცით `allowHeavy: true` --allow-plugin-grants-ით გაშვებულ სესიაში # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` უნდა შედგებოდეს 1-64 დასაბეჭდი სიმბოლოსგან +@msg `{key}` must be 1-64 printable characters `{key}` უნდა შედგებოდეს 1-64 დასაბეჭდი სიმბოლოსგან @msg `version`, `description` or `author` is too long `version`, `description` ან `author` ზედმეტად გრძელია @msg `warnings` must be a list of strings `warnings` უნდა იყოს სტრიქონების სია @msg `{k}` must be one of {_1} `{k}` უნდა იყოს ერთ-ერთი: {_1} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..c28c2e1ca0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6896,6 +6896,7 @@ axis Y Axis Y축 @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}”은(는) 큰 계산 예산을 요청합니다(실행당 최대 {minutes}분, 평소의 {times}배 명령어). 데스크톱 앱에서 사람이 승인하거나 --allow-plugin-grants로 시작한 세션에서 `allowHeavy: true`를 전달하세요 # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name`은(는) 인쇄 가능한 문자 1-64자여야 합니다 +@msg `{key}` must be 1-64 printable characters `{key}`은(는) 인쇄 가능한 문자 1-64자여야 합니다 @msg `version`, `description` or `author` is too long `version`, `description` 또는 `author`가 너무 깁니다 @msg `warnings` must be a list of strings `warnings`는 문자열 목록이어야 합니다 @msg `{k}` must be one of {_1} `{k}`은(는) {_1} 중 하나여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..c612a8a9fd 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -379,6 +379,7 @@ liquify-list-end {0}, {1} {0} en {1} @msg an exporter always gets an export's budget: leave `budget` out een exportplug-in krijgt altijd het budget van een export: laat `budget` weg @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}” vraagt om een groot rekenbudget (elke uitvoering tot {minutes} minuten en {times} keer het gebruikelijke aantal instructies): een persoon moet dit goedkeuren in de desktop-app, of geef `allowHeavy: true` door in een sessie die is gestart met --allow-plugin-grants @msg `name` must be 1-64 printable characters `name` moet uit 1-64 afdrukbare tekens bestaan +@msg `{key}` must be 1-64 printable characters `{key}` moet uit 1-64 afdrukbare tekens bestaan @msg `version`, `description` or `author` is too long `version`, `description` of `author` is te lang @msg `warnings` must be a list of strings `warnings` moet een lijst met strings zijn @msg `{k}` must be one of {_1} `{k}` moet een van {_1} zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..b5239d8a39 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7157,6 +7157,7 @@ axis Y Axis Oś Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}” prosi o duży budżet obliczeń (każde uruchomienie do {minutes} minut i {times} razy więcej instrukcji niż zwykle): musi ją zatwierdzić osoba w aplikacji desktopowej albo przekaż `allowHeavy: true` w sesji uruchomionej z --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` musi mieć 1-64 drukowalnych znaków +@msg `{key}` must be 1-64 printable characters `{key}` musi mieć 1-64 drukowalnych znaków @msg `version`, `description` or `author` is too long `version`, `description` lub `author` jest za długie @msg `warnings` must be a list of strings `warnings` musi być listą ciągów znaków @msg `{k}` must be one of {_1} `{k}` musi mieć jedną z wartości: {_1} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..2bb3e74c81 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7201,6 +7201,7 @@ axis Y Axis Eixo Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” pede um orçamento de processamento grande (cada execução até {minutes} minutos e {times} vezes as instruções habituais): uma pessoa precisa aprová-lo no aplicativo de desktop, ou passe `allowHeavy: true` em uma sessão iniciada com --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` deve ter 1-64 caracteres imprimíveis +@msg `{key}` must be 1-64 printable characters `{key}` deve ter 1-64 caracteres imprimíveis @msg `version`, `description` or `author` is too long `version`, `description` ou `author` é longo demais @msg `warnings` must be a list of strings `warnings` deve ser uma lista de strings @msg `{k}` must be one of {_1} `{k}` deve ser um de {_1} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..4f1bff082f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6923,6 +6923,7 @@ axis Y Axis Ось Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants «{_1}» запрашивает большой вычислительный бюджет (каждый запуск до {minutes} минут и в {times} раз больше инструкций, чем обычно): его должен одобрить человек в настольном приложении, либо передайте `allowHeavy: true` в сеансе, запущенном с --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` должен содержать 1-64 печатаемых символа +@msg `{key}` must be 1-64 printable characters `{key}` должен содержать 1-64 печатаемых символа @msg `version`, `description` or `author` is too long `version`, `description` или `author` слишком длинное @msg `warnings` must be a list of strings `warnings` должно быть списком строк @msg `{k}` must be one of {_1} `{k}` должно быть одним из: {_1} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..ed74b506a9 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8933,6 +8933,7 @@ digits Hindi Hindi @msg `mode` must be one of {_1} `mode` måste vara något av {_1} @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` måste vara "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" eller "lineEndHalf" @msg `name` must be 1-64 printable characters `name` måste vara 1-64 utskrivbara tecken +@msg `{key}` must be 1-64 printable characters `{key}` måste vara 1-64 utskrivbara tecken @msg `names` is a list of preset names `names` är en lista med namn på förinställningar @msg `names` lists preset names `names` listar namn på förinställningar @msg `names` must be a list of names `names` måste vara en lista med namn diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..9009698065 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5425,7 +5425,7 @@ fn script_interpreter_core_errors_are_translated() { } } -/// A manifest whose `commands` value has the wrong shape is refused with an error that every +/// A manifest whose `commands` value, or a command's `menu`, has the wrong shape is refused with an error that every /// language of [`COMPLETE_MESSAGES`] translates whole, the command's name and the place in the /// manifest included. #[test] @@ -5442,9 +5442,35 @@ fn wrongly_shaped_plugin_commands_errors_are_translated() { r#"[{"id":"x","id":"y","label":"A"}]"#.to_string(), format!("[{}]", many.join(",")), ]; - let english = ["must", "list", "missing", "field", "duplicate", "object", "line", "column", "each", "with", "invalid", "expected"]; - for value in &commands { - let manifest = format!(r#"{{"id":"a","name":"x","kind":"filter","commands":{value}}}"#); + let english = [ + "must", + "list", + "missing", + "field", + "duplicate", + "object", + "line", + "column", + "each", + "with", + "invalid", + "expected", + "unknown", + "printable", + "characters", + ]; + // A `menu` of the wrong shape (read at API level 2). + let menus = [ + r#"{"path":["File"]}"#, + r#"{"path":["Select"],"before":"Inverse"}"#, + r#"{"path":["Select"],"after":3}"#, + r#"{"path":["Select"],"after":" "}"#, + r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#, + ]; + let manifests = commands.iter().map(|value| format!(r#"{{"id":"a","name":"x","kind":"filter","commands":{value}}}"#)).chain( + menus.iter().map(|menu| format!(r#"{{"id":"a","name":"x","api":2,"kind":"filter","commands":[{{"id":"x","label":"A","menu":{menu}}}]}}"#)), + ); + for manifest in manifests { let e = vectorcraft_plugins::manifest::Manifest::parse(manifest.as_bytes()).unwrap_err().to_string(); let numbers: Vec<&str> = e.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).collect(); for code in COMPLETE_MESSAGES { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..6663b1385e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7374,6 +7374,7 @@ axis Y Axis Y ekseni @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” büyük bir hesaplama bütçesi istiyor (her çalıştırma en fazla {minutes} dakika ve olağan komutların {times} katı): masaüstü uygulamasında bir kişinin onaylaması gerekir veya --allow-plugin-grants ile başlatılan bir oturumda `allowHeavy: true` geçirin # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` 1-64 yazdırılabilir karakter olmalıdır +@msg `{key}` must be 1-64 printable characters `{key}` 1-64 yazdırılabilir karakter olmalıdır @msg `version`, `description` or `author` is too long `version`, `description` veya `author` çok uzun @msg `warnings` must be a list of strings `warnings` bir dize listesi olmalıdır @msg `{k}` must be one of {_1} `{k}` şunlardan biri olmalıdır: {_1} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..2bf33a0d89 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6906,6 +6906,7 @@ axis Y Axis Вісь Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants «{_1}» запитує великий обчислювальний бюджет (кожен запуск до {minutes} хвилин і в {times} разів більше інструкцій, ніж зазвичай): його має схвалити людина в настільному застосунку, або передайте `allowHeavy: true` у сеансі, запущеному з --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` має містити 1-64 друковані символи +@msg `{key}` must be 1-64 printable characters `{key}` має містити 1-64 друковані символи @msg `version`, `description` or `author` is too long `version`, `description` або `author` задовге @msg `warnings` must be a list of strings `warnings` має бути списком рядків @msg `{k}` must be one of {_1} `{k}` має бути одним з: {_1} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..73c4984e17 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6952,6 +6952,7 @@ axis Y Axis Trục Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” yêu cầu ngân sách tính toán lớn (mỗi lần chạy tới {minutes} phút và gấp {times} lần số lệnh thông thường): cần một người phê duyệt trong ứng dụng máy tính, hoặc truyền `allowHeavy: true` trong phiên khởi động bằng --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` phải có 1-64 ký tự in được +@msg `{key}` must be 1-64 printable characters `{key}` phải có 1-64 ký tự in được @msg `version`, `description` or `author` is too long `version`, `description` hoặc `author` quá dài @msg `warnings` must be a list of strings `warnings` phải là một danh sách chuỗi @msg `{k}` must be one of {_1} `{k}` phải là một trong {_1} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..2a0fbcd5a4 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7134,6 +7134,7 @@ axis Y Axis Y 轴 @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}”需要大量计算预算(每次运行最多 {minutes} 分钟,指令数为通常的 {times} 倍):需要有人在桌面应用中批准,或在以 --allow-plugin-grants 启动的会话中传入 `allowHeavy: true` # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` 必须是 1-64 个可打印字符 +@msg `{key}` must be 1-64 printable characters `{key}` 必须是 1-64 个可打印字符 @msg `version`, `description` or `author` is too long `version`、`description` 或 `author` 太长 @msg `warnings` must be a list of strings `warnings` 必须是字符串列表 @msg `{k}` must be one of {_1} `{k}` 必须是 {_1} 之一 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..5a3d90d647 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6955,6 +6955,7 @@ axis Y Axis Y 軸 @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants 「{_1}」需要大量運算預算(每次執行最多 {minutes} 分鐘,指令數為一般的 {times} 倍):需要有人在桌面應用程式中核准,或在以 --allow-plugin-grants 啟動的工作階段中傳入 `allowHeavy: true` # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` 必須是 1-64 個可列印字元 +@msg `{key}` must be 1-64 printable characters `{key}` 必須是 1-64 個可列印字元 @msg `version`, `description` or `author` is too long `version`、`description` 或 `author` 太長 @msg `warnings` must be a list of strings `warnings` 必須是字串清單 @msg `{k}` must be one of {_1} `{k}` 必須是 {_1} 其中之一 diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index ac5ec6825b..8b18e296ae 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -76,9 +76,9 @@ pub use invoke::{click_target, invoke, invoke_from_system_menu}; pub(crate) use keyboard::handle_input as handle_keyboard_input; // Shared numeric fields preserve their caret when a transient menu returns their focus. pub(crate) use keyboard::restoring_field_focus; -pub(crate) use labels::lists_plugin; pub(crate) use labels::shows_a_name; pub use labels::{CONTEXT_LABELS, DYNAMIC_LABELS, display_label, dynamic_label, item_shortcut, menu_strings}; +pub(crate) use labels::{holds_plugin_commands, lists_plugin}; pub use run::{check_params, run_ui_command}; pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 61a4bf5872..4a004cdbb7 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -334,9 +334,14 @@ pub const DYNAMIC_LABELS: &[&str] = &[ "Lock Grid", ]; -/// Is `children` a plug-in's submenu: does it hold a command the plug-in declares? +/// Is `children` a plug-in's submenu: does it hold a command the plug-in declares, and only items +/// that list plug-ins? A built-in submenu that a plug-in's manifest places a command in is not. pub(crate) fn holds_plugin_commands(children: &[Item]) -> bool { children.iter().any(|c| matches!(c, Item::Cmd(_, id, _) if vectorcraft_engine::cmd::plugin::is_command_id(id))) + && children.iter().all(|c| match c { + Item::Cmd(_, id, params) => lists_plugin(id, params), + _ => true, + }) } /// Every English string the menus, the command palette, the panel registry, the toolbar and the diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 3e68b98c92..cceb9c214c 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -11,6 +11,14 @@ pub fn menu_tree() -> Vec<(&'static str, Vec)> { } pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { + let mut tree = built_in_tree(english_names); + crate::dialogs::plugin::place_commands(&mut tree); + tree +} + +/// The menus with each plug-in command in its plug-in's submenu, before +/// [`crate::dialogs::plugin::place_commands`] moves those whose manifest names another menu. +fn built_in_tree(english_names: bool) -> Vec<(&'static str, Vec)> { let panel = |label: &'static str, id: &'static str| cp(label, "window.panel", json!({ "panel": id, "toggle": true })); vec![ ( diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 0a80254db0..7a57447356 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -619,6 +619,217 @@ fn plugin_commands_are_menu_items_and_shortcut_entries() { assert!(crate::keymap::template().bindable(&crate::keymap::command_of(grow)).is_none()); } +/// A filter at API level 2 named `name` whose commands are `commands` (a JSON list). +fn placing_plugin(id: &str, name: &str, commands: &str) -> String { + placing_kind(id, name, "filter", commands) +} + +/// A plug-in of `kind` at API level 2 named `name` whose commands are `commands` (a JSON list). +fn placing_kind(id: &str, name: &str, kind: &str, commands: &str) -> String { + let manifest = format!(r#"{{"id":"{id}","name":"{name}","api":2,"version":"1","kind":"{kind}","commands":{commands}}}"#); + vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()) +} + +/// A command whose manifest's `menu` names another menu is listed there, after the built-in item +/// `after` names or at the end of the menu, with its plug-in's name after its label, and not in its +/// plug-in's submenu; one with no `menu` stays there. Commands of two plug-ins at the same spot are +/// listed in plug-in id order whichever was installed first. Keyboard Shortcuts and the command +/// palette list it under its menu, and removing its plug-in takes it out of every menu. +#[test] +fn a_plugin_command_is_placed_in_the_menu_its_manifest_names() { + let mut app = app(); + let (ant, bee) = ("test.ui.place.ant", "test.ui.place.bee"); + let low = |id: &str| vectorcraft_engine::cmd::plugin::command_id(id, "low"); + // Bee is installed first; Ant's id sorts first. + let bee_commands = r#"[{"id":"low","label":"Low Area","menu":{"path":["Select"],"after":"Inverse"}}, + {"id":"tail","label":"Tail","menu":{"path":["Select"],"after":"No Such Item"}}]"#; + app.run("plugin.install", json!({"dataBase64": placing_plugin(bee, "Bee", bee_commands)})).unwrap(); + let ant_commands = r#"[{"id":"low","label":"Low Area","menu":{"path":["Select"],"after":"Inverse…"},"params":{"area":{"type":"number","min":0,"max":100,"default":4}}}, + {"id":"same","label":"Same Area","menu":{"path":["Select","Same"]}}, + {"id":"lost","label":"Lost Anchor","menu":{"path":["Select"],"after":"No Such Item"}}, + {"id":"end","label":"End","menu":{"path":["Select"]}}, + {"id":"edges","label":"Edges","menu":{"path":["View"],"after":"Show Edges"}}, + {"id":"stay","label":"Stay"}]"#; + app.run("plugin.install", json!({"dataBase64": placing_plugin(ant, "Ant", ant_commands)})).unwrap(); + + let entries = menus::menu_entries(&app); + let select: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["Select"]).collect(); + let at = |command: &str| select.iter().position(|e| e.command.as_deref() == Some(command)); + let inverse = at("select.inverse").expect("Inverse is listed"); + assert_eq!((at(&low(ant)), at(&low(bee))), (Some(inverse + 1), Some(inverse + 2)), "after Inverse, Ant's before Bee's"); + assert_eq!(select[inverse + 1].label, "Low Area (Ant)…", "the item names its plug-in"); + assert_eq!(select[inverse + 2].label, "Low Area (Bee)"); + // An `after` that names no item means the end of the menu, as no `after` does, and the end keeps + // plug-in id order and then manifest order too. + let command = vectorcraft_engine::cmd::plugin::command_id; + let lost = command(ant, "lost"); + let tail = [at(&lost), at(&command(ant, "end")), at(&command(bee, "tail"))]; + let n = select.len(); + assert_eq!(tail, [Some(n - 3), Some(n - 2), Some(n - 1)], "Ant's two, then Bee's, at the end"); + let same = vectorcraft_engine::cmd::plugin::command_id(ant, "same"); + assert!(entry(&entries, &["Select", "Same"], "Same Area (Ant)").is_some_and(|e| e.command.as_deref() == Some(same.as_str()))); + assert!(menus::menu_strings().contains("Same"), "Select › Same is still a built-in submenu"); + // An item that switches between two labels is matched by either of them. + let view: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["View"]).collect(); + let edges = view.iter().position(|e| e.command.as_deref() == Some("view.edges")).expect("Hide Edges is listed"); + assert_eq!(view.get(edges + 1).and_then(|e| e.command.clone()), Some(command(ant, "edges")), "after the edges toggle"); + + // Each placed command is in one menu only; Stay is still in Ant's submenu. + for command in [low(ant), low(bee), same.clone(), lost.clone()] { + assert_eq!(entries.iter().filter(|e| e.command.as_deref() == Some(command.as_str())).count(), 1, "{command}"); + } + assert!(entry(&entries, &["Object", "Plug-ins", "Ant"], "Stay").is_some()); + let bee_item = entry(&entries, &["Object", "Plug-ins"], "Bee").expect("Bee is a plain item again: all its commands are placed"); + assert_eq!(bee_item.command.as_deref(), Some("plugin.dialog")); + + let listed = crate::shortcut_editor::entry(&low(ant)).expect("in Keyboard Shortcuts"); + assert_eq!((listed.label.as_str(), listed.group.as_str()), ("Low Area (Ant)", "Select")); + assert!(crate::palette::items().iter().any(|(name, id, _)| *id == low(bee) && name.ends_with("Low Area (Bee)")), "in the command palette"); + + app.run("plugin.remove", json!({"id": ant})).unwrap(); + let entries = menus::menu_entries(&app); + assert!(entries.iter().all(|e| e.command.as_deref().is_none_or(|c| !c.starts_with("plugin.test.ui.place.ant."))), "Ant's commands are gone"); + assert!(entries.iter().any(|e| e.path == ["Select"] && e.command.as_deref() == Some(low(bee).as_str()))); + app.run("plugin.remove", json!({"id": bee})).unwrap(); + assert!(menus::menu_entries(&app).iter().all(|e| e.command.as_deref() != Some(low(bee).as_str()))); + assert!(crate::shortcut_editor::entries().iter().all(|e| e.key != low(bee))); +} + +/// A live effect whose commands are all placed elsewhere is a single item in Effect › Plug-ins. A +/// filter with the same name placing a command with the same label at the same spot keeps it in its +/// own submenu, so the menu shows that label once. Replaced by a module whose command has no +/// `menu`, the effect's command leaves the menu it was placed in and is listed once, in its +/// submenu. +#[test] +fn placed_commands_of_a_live_effect_and_a_clashing_label() { + let mut app = app(); + let (eff, twin) = ("test.ui.place.eff", "test.ui.place.twin"); + let command = vectorcraft_engine::cmd::plugin::command_id; + let placed = r#"[{"id":"low","label":"Low Area","menu":{"path":["Select"],"after":"Inverse"}}]"#; + app.run("plugin.install", json!({"dataBase64": placing_kind(eff, "Glow", "effect", placed)})).unwrap(); + app.run("plugin.install", json!({"dataBase64": placing_plugin(twin, "Glow", placed)})).unwrap(); + + let entries = menus::menu_entries(&app); + let (low, twin_low) = (command(eff, "low"), command(twin, "low")); + let in_select: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["Select"] && e.label == "Low Area (Glow)").collect(); + assert_eq!(in_select.len(), 1, "the label is listed once"); + assert_eq!(in_select[0].command.as_deref(), Some(low.as_str()), "the plug-in with the lower id takes the spot"); + let own = entry(&entries, &["Effect", "Plug-ins"], "Glow").expect("the effect is a single item"); + assert!(own.command.as_deref().is_some_and(|c| !vectorcraft_engine::cmd::plugin::is_command_id(c)), "{:?}", own.command); + assert!(entries.iter().all(|e| e.path != ["Effect", "Plug-ins", "Glow"]), "no submenu is left"); + assert!(entry(&entries, &["Object", "Plug-ins", "Glow"], "Low Area").is_some_and(|e| e.command.as_deref() == Some(twin_low.as_str()))); + let listed = crate::shortcut_editor::entry(&twin_low).expect("in Keyboard Shortcuts"); + assert_eq!((listed.label.as_str(), listed.group.as_str()), ("Low Area", "Object › Plug-ins › Glow")); + + // An item whose two labels share no first word is matched by either label too. + let global = "test.ui.place.global"; + let after_stop = r#"[{"id":"next","label":"Next","menu":{"path":["Select"],"after":"Stop Global Edit"}}]"#; + app.run("plugin.install", json!({"dataBase64": placing_plugin(global, "Global", after_stop)})).unwrap(); + let entries = menus::menu_entries(&app); + let select: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["Select"]).collect(); + let toggle = select.iter().position(|e| e.command.as_deref() == Some("select.globalEdit")).expect("Start Global Edit is listed"); + assert_eq!(select.get(toggle + 1).and_then(|e| e.command.clone()), Some(command(global, "next"))); + app.run("plugin.remove", json!({"id": global})).unwrap(); + + let unplaced = placing_kind(eff, "Glow", "effect", r#"[{"id":"low","label":"Low Area"}]"#); + app.run("plugin.install", json!({"dataBase64": unplaced, "replace": true})).unwrap(); + let entries = menus::menu_entries(&app); + assert_eq!(entries.iter().filter(|e| e.command.as_deref() == Some(low.as_str())).count(), 1, "listed once"); + assert!(entry(&entries, &["Effect", "Plug-ins", "Glow"], "Low Area").is_some(), "back in its submenu"); + assert!( + entry(&entries, &["Select"], "Low Area (Glow)").is_some_and(|e| e.command.as_deref() == Some(twin_low.as_str())), + "the filter's takes the spot" + ); + for id in [eff, twin] { + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} + +/// Every menu a manifest's `menu` may name is a built-in menu of the menu bar, so a command placed +/// there is never left in its plug-in's submenu while Keyboard Shortcuts lists it under that menu. +#[test] +fn every_menu_a_plugin_may_name_is_in_the_menu_bar() { + fn find<'a>(items: &'a [menus::Item], label: &str) -> Option<&'a [menus::Item]> { + items.iter().find_map(|it| match it { + menus::Item::Sub(l, children) if *l == label => Some(children.as_slice()), + _ => None, + }) + } + let tree = menus::menu_tree(); + for place in vectorcraft_plugins::manifest::MENU_PLACES { + let (first, rest) = place.split_first().unwrap(); + let mut menu = tree.iter().find(|(title, _)| title == first).map(|(_, items)| items.as_slice()); + for segment in rest { + menu = menu.and_then(|m| find(m, segment)); + } + assert!(menu.is_some(), "{place:?} is in the menu bar"); + } +} + +/// Every engine command whose menu item switches between two labels is in the engine's +/// `SWITCHING_LABELS`, so a placed plug-in command that reads like its other label stays in its +/// plug-in's submenu without the desktop app too. +#[test] +fn engine_commands_with_two_labels_are_known_to_the_engine() { + use vectorcraft_engine::cmd::plugin::{SWITCHING_LABELS, other_state}; + for spec in vectorcraft_engine::cmd::command_specs() { + let switches = menus::DYNAMIC_LABELS.contains(&spec.label) + && other_state(spec.label).is_some_and(|other| menus::DYNAMIC_LABELS.contains(&other.as_str())); + assert_eq!(SWITCHING_LABELS.contains(&spec.label), switches, "{} ({})", spec.id, spec.label); + } +} + +/// Every item of a menu a plug-in command may be placed in, other than an engine command of that +/// menu, is in the engine's `DESKTOP_MENU_ITEMS` with both of its labels, so a placed plug-in +/// command that reads like it stays in its plug-in's submenu without the desktop app too. +#[test] +fn desktop_items_of_placeable_menus_are_known_to_the_engine() { + use vectorcraft_engine::cmd::plugin::{DESKTOP_MENU_ITEMS, SWITCHING_LABELS, other_state}; + let key = |l: &str| l.chars().filter(|ch| ch.is_alphanumeric()).flat_map(char::to_lowercase).collect::(); + let tree = menus::menu_tree(); + let mut missing = Vec::new(); + for place in vectorcraft_plugins::manifest::MENU_PLACES { + let (first, rest) = place.split_first().unwrap(); + let mut items = tree.iter().find(|(title, _)| title == first).map(|(_, items)| items.as_slice()).unwrap(); + for segment in rest { + items = items + .iter() + .find_map(|it| match it { + menus::Item::Sub(l, children) if l == segment => Some(children.as_slice()), + _ => None, + }) + .unwrap(); + } + let engine_reads = |label: &str| { + vectorcraft_engine::cmd::command_specs().iter().any(|s| { + s.menu == *place + && (key(s.label) == key(label) + || SWITCHING_LABELS.contains(&s.label) && other_state(s.label).is_some_and(|o| key(&o) == key(label))) + }) + }; + for it in items { + let label = match it { + menus::Item::Cmd(l, id, p) if !menus::lists_plugin(id, p) => *l, + menus::Item::Sub(l, children) if !menus::holds_plugin_commands(children) => *l, + menus::Item::Todo(l, _) => *l, + _ => continue, + }; + let mut labels = vec![label.to_string()]; + if menus::DYNAMIC_LABELS.contains(&label) { + labels.extend(other_state(label)); + } + for l in labels { + let known = DESKTOP_MENU_ITEMS.iter().any(|(path, d)| path == place && key(d) == key(&l)); + if !engine_reads(&l) && !known && !missing.contains(&(place, l.clone())) { + missing.push((place, l)); + } + } + } + } + let rows: Vec = missing.iter().map(|(place, l)| format!(" (&{place:?}, {l:?}),")).collect(); + assert!(missing.is_empty(), "missing from DESKTOP_MENU_ITEMS:\n{}", rows.join("\n")); +} + /// A shortcut the user gives a plug-in command runs it. #[test] fn a_shortcut_runs_a_plugin_command() { diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..914f26f211 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13362,7 +13362,9 @@ changes nothing when a new `pluginsFolder` is missing, is not a folder or can't value or the folder the preference already holds, and the web build does not check folders. A filter or live effect may declare commands of its own ([plugins.md](plugins.md#commands)): each is the command `plugin..` while the plug-in is installed, listed by `command_list` and in its `plugin.list` entry -(`commands: [{id, command, label, params, paramsSchema}]`). Run it with `{ids?, params?}` (its parameters may also +(`commands: [{id, command, label, params, paramsSchema, menu?}]`; `menu`, `{path, after?, placed?}`, is the menu its +manifest places it in, with `placed: false` when the command stays in its plug-in's submenu, see +[plugins.md](plugins.md#placing-a-command-in-another-menu)). Run it with `{ids?, params?}` (its parameters may also be top-level keys): the parameters are checked before the plug-in runs, a run is one undo step named after the command, and a run that traps or runs out of its instruction budget returns an error that starts with the plug-in's name and the command's label and leaves the document and the undo history as they were. For `plugin.run` and plug-in diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..bd1a5b6073 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -88,14 +88,15 @@ replaced by a module without it. - **Menus.** A plug-in with commands is a submenu of **Object › Plug-ins** (a live effect: **Effect › Plug-ins**) named after the plug-in. The submenu holds the plug-in's own item, then its commands. A command with parameters has - an ellipsis and opens a dialog for them, with a live preview, as a filter's own item does. A manifest cannot put a - command in another menu: a `menu` key in a command is ignored. -- **Keyboard Shortcuts.** Edit › Keyboard Shortcuts lists each command under its submenu, and the user can give it a + an ellipsis and opens a dialog for them, with a live preview, as a filter's own item does. A command whose manifest + gives a `menu` is listed in that menu instead ([below](#placing-a-command-in-another-menu)). +- **Keyboard Shortcuts.** Edit › Keyboard Shortcuts lists each command under its menu, and the user can give it a shortcut. A manifest cannot give a command a shortcut. - **Actions and agents.** A command run is recorded in an action like any other command and plays back with its parameters. `run`, MCP and `command.batch` call it as `plugin..` with `{"ids"?: [...], "params"?: {…}}` (its parameters may also be top-level keys). MCP's `command_list` and `list_commands` list it, and `plugin.list` - lists a plug-in's commands as `commands: [{id, command, label, params, paramsSchema}]`. + lists a plug-in's commands as `commands: [{id, command, label, params, paramsSchema, menu?}]`, with `menu` for a + command whose manifest places it in another menu. - **Runs.** The parameters are checked against the command's declarations before the plug-in runs. The plug-in runs through `vc_run` on the selection (or `ids`) as a filter run does, with `_context.mode` `"command"` and `_context.command` set to the command's id ([Parameters](#parameters)), under the plug-in's @@ -105,6 +106,40 @@ replaced by a module without it. document and the undo history as they were, and the error starts with the plug-in's name and the command's label (`“Cmd Test” › Grow: …`). +#### Placing a command in another menu + +At `api` 2 a command may name the menu it is listed in with `menu`: `{"path": [menu, …], "after"?: item}`. For +example, `"menu": {"path": ["Select"], "after": "Inverse"}` lists the command in the Select menu right after +Inverse. + +- `path` is one of these menus, by their English labels: `["Edit"]`, `["Edit", "Edit Colors"]`, `["Object"]`, + `["Object", "Transform"]`, `["Object", "Arrange"]`, `["Object", "Path"]`, `["Object", "Compound Path"]`, + `["Object", "Clipping Mask"]`, `["Type"]`, `["Select"]`, `["Select", "Same"]`, `["Select", "Object"]`, `["Effect"]` + and `["View"]`. The File, Window and Help menus, the application menu, Edit › Preferences and the submenus that list + files, fonts, panels or plug-ins cannot be named. Any other `path`, a `menu` that is not an object or is given twice, + a key other than `path` and `after`, and an `after` that is not 1–64 printable characters are refused when the + module is installed, and the error names the command. +- `after` is the English label of a built-in item or submenu of that menu, with or without its closing ellipsis + (`"Inverse"`). The command is listed right after it. An item that switches between two labels is matched by either + of them (`"Show Edges"` and `"Hide Edges"`, `"Start Global Edit"` and `"Stop Global Edit"`). Without `after`, or when no + built-in item of the menu has that label, the command is listed at the end of the menu, and the module still + installs. Items of plug-ins are never matched. +- The item's label is the command's label followed by the plug-in's name in parentheses (`Low Area Closed Paths + (Tidy)`). Keyboard Shortcuts, the command palette and `command_list` list the command under that menu with that + label. +- A command stays in its plug-in's submenu, under its own label, when its label with the plug-in's name has the same + letters and digits, ignoring case, as a built-in item or submenu of that menu (`Paste (in Place)` and Edit › Paste + in Place, `Hide (Edges)` and View › Hide Edges; either label of one that switches between two), or as a command that + a plug-in with a lower id, or an earlier command of the same plug-in, places in that menu. The desktop app and + `vectorcraft-cli` give the same result. `plugin.list` then gives the command's `menu` with + `"placed": false`. +- Commands of several plug-ins placed at the same spot are listed in plug-in id order, then in manifest order. A + plug-in whose commands all name another menu is listed in Object › Plug-ins (or Effect › Plug-ins) as a single item, + without a submenu. Commands without `menu` stay in the plug-in's submenu. +- A placed command leaves the menus when its plug-in is removed or replaced by a module without the command. Turning + the plug-in off (`plugin.setEnabled`) removes it at the next launch. +- At `api` 1 a `menu` key, repeated or not, is ignored and the command stays in the plug-in's submenu. + **Preference folder.** Edit › Preferences › Plug-ins & Scratch Disks › *Additional Plug-ins Folder*: when set, every `*.wasm` in that folder (not recursive) is installed at startup and whenever the preference changes (desktop builds; the web build installs from bytes). On the desktop, Choose… beside the field picks the folder; the dialog refuses a @@ -566,10 +601,12 @@ the module's start function, in a run that isn't a filter's run on a document, o list (`svg`): `document.export` then writes the exporter's format only when asked for by its format id, and `document.open` reads a file with the importer only when `importer` names it. - `commands` (filters and live effects; not heavy filters): up to 32 commands of the plug-in's own - ([Commands](#commands)), each `{"id": "grow", "label": "Grow", "params"?: {…}}`. An `id` is 1–32 characters from - `a-z 0-9 _` that starts with a letter, and appears once. A `label` is 1–64 printable characters; menus show it with - control and bidirectional characters escaped. `params` are declared as the plug-in's own `params` are. A malformed - entry is refused when the module is installed, and the error names the command by its id (or its place, `[0]`). + ([Commands](#commands)), each `{"id": "grow", "label": "Grow", "params"?: {…}, "menu"?: {…}}`. An `id` is 1–32 + characters from `a-z 0-9 _` that starts with a letter, and appears once. A `label` is 1–64 printable characters; + menus show it with control and bidirectional characters escaped. `params` are declared as the plug-in's own `params` + are. `menu` (`api` 2 and later; ignored at `api` 1) places the command in [another menu](#placing-a-command-in-another-menu). + A malformed entry is refused when the module is installed, and the error names the command by its id (or its place, + `[0]`). - `commandAllowlist` (filters at `api` 2 with the usual budget, and only with the `commands` permission, which needs it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist": ["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..e352be65f6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2672,7 +2672,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. - **A grant that can't be forgotten stops counting in the whole process (G17):** when such a grant can't be removed from `grants.json`, no session in the process that uses the same `Plug-ins` folder, by any path to it, counts it for `plugin.inspect`, `plugin.install` or loading plug-ins, until `grants.json` can be written for that plug-in; another process on the folder reads `grants.json` as it is. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. -- **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) whatever menu the manifest names, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. +- **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) unless its manifest places it in another menu, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. +- **Plug-in commands in other menus (G17):** at plug-in API level 2 a command's `menu` (`{path, after?}`) lists it in one of 14 menus of Edit, Object, Type, Select, Effect and View (never File, Window, Help, the application menu or a submenu that lists files, fonts, panels or plug-ins), right after the built-in item `after` names or at the end of the menu, with the plug-in's name in parentheses after its label. Keyboard Shortcuts, the command palette and `command_list` list it under that menu, and `plugin.list` gives its `menu`. Commands of several plug-ins at one spot keep plug-in id order; a plug-in whose commands are all placed elsewhere is a single item in Object › Plug-ins. A command whose label with the plug-in's name reads like a built-in item or submenu of that menu, or like a command a plug-in with a lower id places there, stays in its plug-in's submenu. Any other `menu` is refused by command when the module is installed; at API level 1 the key is still ignored. VectorCraft's own rule. Regressions: `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. A command counts as taking a file or folder when its params description or schema names a file key as a param; a word in the description's prose or result does not count. Each exemption for a key that names part of the document names a param its command takes, which `every_command_is_sorted` checks, and Image Trace's path fidelity setting (`params.paths`, `savedPreset.paths`) is exempt only inside those settings. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **The command sweep sends file and folder params into its temp folder by the command catalog:** the sweeps in `crates/engine/tests/command_sweep.rs` take each command's file and folder keys from the catalog (`cmd::location_keys`, the same key list the plug-in call rules use, less the keys that name part of the document in a command), read every key a params description names (`{path | name …}`, `{folder? (…)}` included) and its schema's params, and send every string under such a key, in arrays and in objects inside them (`paths: [{ids, path}]`), as a location in the temp folder, so a command added later is swept and checked without editing the sweep. `diffPath` counts as a file key, and Slice Options' `url` and Export for Screens' `folders` do not. Regressions: `sweep_cases_name_files_only_inside_the_temp_folder` and `sweep_cases_send_the_file_keys_of_the_command_catalog` in `command_sweep`, `location_keys_come_from_the_command_catalog` in `cmd::plugin_call`. Scores and hours unchanged. - **A drag ended by a command with Real-time Drawing off:** when Undo, Redo, a filter that calls commands or a plug-in command that calls commands ends a drag whose preview Real-time Drawing off has not applied yet, the preview is applied first and kept as an undo step of its own, as releasing the drag keeps it; a preview that fails cancels the drag. The filter or plug-in command is then given the objects where the drag left them. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`. Scores and hours unchanged. From 5f2649aa63ed2df53f97dcfdf40bbf6136e89a41 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:49:11 -0800 Subject: [PATCH 44/78] Tests: the filter shortcut test no longer sees plug-ins another test installs Installed plug-ins are process-wide, and the shortcut test each_filter_plugin_takes_a_shortcut_of_its_own and the palette test filter_plugins_with_one_name_show_their_ids both install two filter plug-ins named Same Name. When the two ran at the same time, the shortcut test counted 4 Same Name lines in the exported shortcuts instead of its own 2, and its own row took an id suffix. The tests that install filter plug-ins under a shared name, or that check how plug-ins sharing a name are told apart, now hold one test lock (SHARED_PLUGIN_NAMES in the ui-egui test module) while their plug-ins are installed: the shortcut test and both palette tests (each_filter_plugin_is_a_result_of_its_own checks the exact labels of two filters named Group). Running the two tests together with --test-threads=8, 50 times on Linux: 0 of 50 passed before, 50 of 50 after. --- crates/ui-egui/src/palette.rs | 2 ++ crates/ui-egui/src/shortcuts/tests.rs | 1 + crates/ui-egui/src/tests.rs | 5 +++++ 3 files changed, 8 insertions(+) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index a3c5fed207..29cc18bf69 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -3230,6 +3230,7 @@ mod tests { #[test] fn each_filter_plugin_is_a_result_of_its_own() { use vectorcraft_plugins::wat as tpl; + let _names = crate::tests::SHARED_PLUGIN_NAMES.lock().unwrap_or_else(|e| e.into_inner()); let (one, two) = ("test.UI.palette_filter-one", "test.UI.palette_filter-two"); let (key_one, key_two) = (format!("plugin:{one}"), format!("plugin:{two}")); let install = |id: &str, params: &str| { @@ -3509,6 +3510,7 @@ mod tests { #[test] fn filter_plugins_with_one_name_show_their_ids() { use vectorcraft_plugins::wat as tpl; + let _names = crate::tests::SHARED_PLUGIN_NAMES.lock().unwrap_or_else(|e| e.into_inner()); let (one, two) = ("test.UI.palette_same-one", "test.UI.palette_same-two"); for id in [one, two] { let manifest = format!(r#"{{"id":"{id}","name":"Same Name","version":"1","kind":"filter","params":{{"wiggle":{{"type":"bool"}}}}}}"#); diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 063d63bb14..45314702b8 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -3391,6 +3391,7 @@ fn a_live_effect_plugin_installed_later_takes_a_shortcut_of_its_own() { fn each_filter_plugin_takes_a_shortcut_of_its_own() { use serde_json::Value; use vectorcraft_plugins::wat as tpl; + let _names = crate::tests::SHARED_PLUGIN_NAMES.lock().unwrap_or_else(|e| e.into_inner()); let (one, two) = ("test.UI.key_filter-one", "test.UI.key_filter-two"); let (key_one, key_two) = (format!("plugin:{one}"), format!("plugin:{two}")); let install = |id: &str, name: &str, params: &str| { diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e0619ddaf7..36a9cdc17b 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -62,3 +62,8 @@ mod toolescape; mod trace_runs; mod transparencygrid; mod widthtool; + +/// Installed plug-ins are process-wide. Tests that install filter plug-ins under a name another +/// test also installs, or that check how plug-ins sharing a name are told apart, hold this lock +/// while their plug-ins are installed, so each sees only its own plug-ins under that name. +pub(super) static SHARED_PLUGIN_NAMES: std::sync::Mutex<()> = std::sync::Mutex::new(()); From 2eef47e7e2e8458f66dfaec8cce94e5d5aea7823 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:10:11 -0800 Subject: [PATCH 45/78] Plug-ins: commands placed after either label of a switching item keep their order MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A placed command's spot is now the matched item's own label rather than the label its `after` names, so commands whose `after` names the two labels of one Show/Hide item (Show Bounding Box and Hide Bounding Box) share one spot and keep plug-in id order and then manifest order. The parity line now says a live effect whose commands are all placed elsewhere is a single item in Effect › Plug-ins. --- crates/ui-egui/src/dialogs/plugin.rs | 29 +++++++++++++++------------- crates/ui-egui/src/tests/plugins.rs | 25 ++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 42 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 4e42b33a1a..14573a611d 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -92,11 +92,11 @@ pub fn place_commands(tree: &mut [(&'static str, Vec)]) { continue; } // An `after` that names no built-in item of the menu means the end of it, as no `after` does. - let after = place - .after - .as_deref() - .map(|a| anchor_key(a).to_string()) - .filter(|a| menu_at(tree, place.path).is_some_and(|menu| menu.iter().any(|it| is_anchor(it, a)))); + // The spot is the item's own label, so both labels of an item that switches are one spot. + let after = place.after.as_deref().and_then(|a| { + let menu = menu_at(tree, place.path)?; + menu.iter().find(|it| is_anchor(it, anchor_key(a))).and_then(own_key).map(str::to_string) + }); let id = registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &c.id)); let item = Item::Cmd(label(&c.menu_label(&m.name), !c.params.is_empty()), id, Value::Null); match spots.iter_mut().find(|s| s.0 == place.path && s.1 == after) { @@ -123,7 +123,7 @@ pub fn place_commands(tree: &mut [(&'static str, Vec)]) { } for (path, after, items) in spots { let Some(menu) = menu_at(tree, path) else { continue }; - let at = after.and_then(|a| menu.iter().position(|it| is_anchor(it, &a))).map_or(menu.len(), |i| i + 1); + let at = after.and_then(|a| menu.iter().position(|it| own_key(it) == Some(a.as_str()))).map_or(menu.len(), |i| i + 1); menu.splice(at..at, items); } } @@ -137,14 +137,17 @@ fn anchor_key(label: &str) -> &str { /// [`crate::menus::DYNAMIC_LABELS`] matches by the label of either of its states /// ([`vectorcraft_engine::cmd::plugin::other_state`]). Items that list a plug-in are never an anchor. fn is_anchor(it: &Item, key: &str) -> bool { + let other = |l: &str| crate::menus::DYNAMIC_LABELS.contains(&l) && vectorcraft_engine::cmd::plugin::other_state(l).is_some_and(|o| o == key); + own_key(it).is_some_and(|own| own == key || matches!(it, Item::Cmd(l, _, _) if other(l))) +} + +/// The label of `it` as [`anchor_key`] reads it, when `it` is a built-in item or submenu that can be +/// an anchor; `None` for an item that lists a plug-in. +fn own_key(it: &Item) -> Option<&str> { match it { - Item::Cmd(l, id, p) => { - let toggles = crate::menus::DYNAMIC_LABELS.contains(l); - let other = || vectorcraft_engine::cmd::plugin::other_state(l).is_some_and(|o| o == key); - !crate::menus::lists_plugin(id, p) && (anchor_key(l) == key || toggles && other()) - } - Item::Sub(l, children) => !crate::menus::holds_plugin_commands(children) && anchor_key(l) == key, - _ => false, + Item::Cmd(l, id, p) if !crate::menus::lists_plugin(id, p) => Some(anchor_key(l)), + Item::Sub(l, children) if !crate::menus::holds_plugin_commands(children) => Some(anchor_key(l)), + _ => None, } } diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 7a57447356..a8cf4ccb5e 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -695,6 +695,31 @@ fn a_plugin_command_is_placed_in_the_menu_its_manifest_names() { assert!(crate::shortcut_editor::entries().iter().all(|e| e.key != low(bee))); } +/// Commands placed after an item that switches between two labels are one spot whichever label +/// their `after` names: they keep manifest order within a plug-in and plug-in id order across +/// plug-ins. +#[test] +fn both_labels_of_a_switching_item_are_one_spot() { + let mut app = app(); + let (ape, bat) = ("test.ui.place.ape", "test.ui.place.bat"); + let command = vectorcraft_engine::cmd::plugin::command_id; + let ape_commands = r#"[{"id":"first","label":"First","menu":{"path":["View"],"after":"Hide Bounding Box"}}, + {"id":"second","label":"Second","menu":{"path":["View"],"after":"Show Bounding Box"}}]"#; + let bat_commands = r#"[{"id":"third","label":"Third","menu":{"path":["View"],"after":"Hide Bounding Box"}}]"#; + // Bat is installed first; Ape's id sorts first. + app.run("plugin.install", json!({"dataBase64": placing_plugin(bat, "Bat", bat_commands)})).unwrap(); + app.run("plugin.install", json!({"dataBase64": placing_plugin(ape, "Ape", ape_commands)})).unwrap(); + + let entries = menus::menu_entries(&app); + let view: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["View"]).collect(); + let toggle = view.iter().position(|e| e.command.as_deref() == Some("view.boundingBox")).expect("Hide Bounding Box is listed"); + let after: Vec> = (1..=3).map(|i| view.get(toggle + i).and_then(|e| e.command.clone())).collect(); + assert_eq!(after, [Some(command(ape, "first")), Some(command(ape, "second")), Some(command(bat, "third"))]); + for id in [ape, bat] { + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} + /// A live effect whose commands are all placed elsewhere is a single item in Effect › Plug-ins. A /// filter with the same name placing a command with the same label at the same spot keeps it in its /// own submenu, so the menu shows that label once. Replaced by a module whose command has no diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e352be65f6..4179c3b5f4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2673,7 +2673,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. - **A grant that can't be forgotten stops counting in the whole process (G17):** when such a grant can't be removed from `grants.json`, no session in the process that uses the same `Plug-ins` folder, by any path to it, counts it for `plugin.inspect`, `plugin.install` or loading plug-ins, until `grants.json` can be written for that plug-in; another process on the folder reads `grants.json` as it is. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) unless its manifest places it in another menu, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. -- **Plug-in commands in other menus (G17):** at plug-in API level 2 a command's `menu` (`{path, after?}`) lists it in one of 14 menus of Edit, Object, Type, Select, Effect and View (never File, Window, Help, the application menu or a submenu that lists files, fonts, panels or plug-ins), right after the built-in item `after` names or at the end of the menu, with the plug-in's name in parentheses after its label. Keyboard Shortcuts, the command palette and `command_list` list it under that menu, and `plugin.list` gives its `menu`. Commands of several plug-ins at one spot keep plug-in id order; a plug-in whose commands are all placed elsewhere is a single item in Object › Plug-ins. A command whose label with the plug-in's name reads like a built-in item or submenu of that menu, or like a command a plug-in with a lower id places there, stays in its plug-in's submenu. Any other `menu` is refused by command when the module is installed; at API level 1 the key is still ignored. VectorCraft's own rule. Regressions: `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. +- **Plug-in commands in other menus (G17):** at plug-in API level 2 a command's `menu` (`{path, after?}`) lists it in one of 14 menus of Edit, Object, Type, Select, Effect and View (never File, Window, Help, the application menu or a submenu that lists files, fonts, panels or plug-ins), right after the built-in item `after` names or at the end of the menu, with the plug-in's name in parentheses after its label. Keyboard Shortcuts, the command palette and `command_list` list it under that menu, and `plugin.list` gives its `menu`. Commands at one spot keep plug-in id order and then manifest order; a filter whose commands are all placed elsewhere is a single item in Object › Plug-ins, and such a live effect is a single item in Effect › Plug-ins. A command whose label with the plug-in's name reads like a built-in item or submenu of that menu, or like a command a plug-in with a lower id places there, stays in its plug-in's submenu. Any other `menu` is refused by command when the module is installed; at API level 1 the key is still ignored. VectorCraft's own rule. Regressions: `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. A command counts as taking a file or folder when its params description or schema names a file key as a param; a word in the description's prose or result does not count. Each exemption for a key that names part of the document names a param its command takes, which `every_command_is_sorted` checks, and Image Trace's path fidelity setting (`params.paths`, `savedPreset.paths`) is exempt only inside those settings. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **The command sweep sends file and folder params into its temp folder by the command catalog:** the sweeps in `crates/engine/tests/command_sweep.rs` take each command's file and folder keys from the catalog (`cmd::location_keys`, the same key list the plug-in call rules use, less the keys that name part of the document in a command), read every key a params description names (`{path | name …}`, `{folder? (…)}` included) and its schema's params, and send every string under such a key, in arrays and in objects inside them (`paths: [{ids, path}]`), as a location in the temp folder, so a command added later is swept and checked without editing the sweep. `diffPath` counts as a file key, and Slice Options' `url` and Export for Screens' `folders` do not. Regressions: `sweep_cases_name_files_only_inside_the_temp_folder` and `sweep_cases_send_the_file_keys_of_the_command_catalog` in `command_sweep`, `location_keys_come_from_the_command_catalog` in `cmd::plugin_call`. Scores and hours unchanged. - **A drag ended by a command with Real-time Drawing off:** when Undo, Redo, a filter that calls commands or a plug-in command that calls commands ends a drag whose preview Real-time Drawing off has not applied yet, the preview is applied first and kept as an undo step of its own, as releasing the drag keeps it; a preview that fails cancels the drag. The filter or plug-in command is then given the objects where the drag left them. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`. Scores and hours unchanged. From 17c2f4348503ac2448ae062c6bd35c1cc62909f3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:53:53 -0800 Subject: [PATCH 46/78] Direct Selection: optional preference keeps paths joined when Delete removes anchors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The new General preference Delete Removes Anchor Points and Keeps Paths Joined (`deleteKeepsPathsJoined`, off by default) is the default of a new `keepJoined` param of edit.clear (Delete, Backspace, Edit › Clear, and the Layers panel's Delete button while no row is highlighted). With it on, Delete removes the direct-selected anchors of each path as Remove Anchor Points does, refitting the curve around each one, so a closed path stays closed and an open path stays in one piece. The next anchor along is selected (the one before at an open path's end), so the next Delete goes on along the path. - Objects selected whole are deleted and paths with a selected segment are cut there, as before, in the same undo step. A path left with fewer than two anchors is deleted; a compound path keeps its other members. When no changed subpath keeps two anchors, the path stays selected whole, as Remove Anchor Points leaves it. - The value used joins the journal entry, so a replay removes the anchors the same way whatever the preference is at the time; a saved step without it opens the paths as it did when it was recorded. A keepJoined value that is not a boolean is an error, also with ids, where the param has no other effect. path.deleteAnchors and Cut are unchanged. - The Smart Pen does not take the Delete key, so Delete follows the preference with it chosen too. - The label and its description have a row in every catalog. Without keepJoined and with the preference off, edit.clear gives the same result as before. Part of #8326 Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/draw2.rs | 1 + crates/engine/src/cmd/draw2/anchors.rs | 4 +- crates/engine/src/cmd/edit.rs | 17 +- crates/engine/src/cmd/path.rs | 36 ++- crates/engine/src/cmd/prefscmds.rs | 1 + crates/engine/src/prefs.rs | 7 + crates/engine/src/tests.rs | 1 + .../engine/src/tests/delete_keeps_joined.rs | 227 ++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + .../ui-egui/src/prefs_dialog/descriptions.rs | 1 + crates/ui-egui/src/tests/removeanchors.rs | 60 +++++ docs/mcp.md | 16 ++ docs/target-app-parity.md | 1 + 40 files changed, 423 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/tests/delete_keeps_joined.rs diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 885fd35988..1054ca3ddc 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -31,6 +31,7 @@ mod freehand; mod quickpen; mod smooth; +pub(super) use anchors::{following_anchors, remove_anchors_of}; pub use commands::specs; pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt}; pub(super) use cut::{components, erase_outline}; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index 5b80fcc80f..8068418edd 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -166,7 +166,7 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result { /// end. Indexes are those after the removal, without the subpaths left with fewer than two anchors. /// `removed` is in ascending order without repeats, as a selection holds it, and each subpath reads /// only its own pairs. -fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { +pub(in crate::cmd) fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { let mut next = BTreeSet::new(); let mut kept = 0; let mut rest = removed; @@ -202,7 +202,7 @@ fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTr /// ([`vectorcraft_tools::draw2::curvature_remove`]). A subpath left with one anchor is removed, /// and a path left with no subpath is removed through `emptied`; the caller then takes it out of /// the selection. True when the path went. -fn remove_anchors_of( +pub(in crate::cmd) fn remove_anchors_of( d: &mut Document, sel: &mut Selection, emptied: &mut Beside, diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a20a6c47e4..1ebe52817e 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -225,7 +225,7 @@ pub fn specs() -> Vec { "Clear", ["Edit"], Some("Delete"), - "{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected", + "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected", has_selection_or_guides, clear ), @@ -1221,6 +1221,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; + switch_or(p, "keepJoined", false, "edit.clear")?; let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; // An object of a symbol instance's art can't be removed from the instance alone. if explicit.is_none() && s.doc()?.selection.symbol_part.is_some() { @@ -1228,7 +1229,8 @@ fn clear(s: &mut Session, p: &Value) -> Result { } // Direct-selected anchors or segments: remove those, and any objects selected whole with them. if explicit.is_none() && (!s.doc()?.selection.anchors.is_empty() || !s.doc()?.selection.segments.is_empty()) { - return super::path::delete_anchors(s, p); + let keep_joined = keeps_paths_joined(s, p)?; + return super::path::delete_anchors_joined(s, p, keep_joined); } // Selected ruler guides (selected on their own). if explicit.is_none() && s.doc()?.selection.is_empty() { @@ -1275,6 +1277,17 @@ fn clear(s: &mut Session, p: &Value) -> Result { ok() } +/// Does Clear remove direct-selected anchors without opening their paths (`keepJoined` param, else +/// General › Delete Removes Anchor Points and Keeps Paths Joined)? Noted in the journal, so a +/// replay removes them the same way whatever the preference is at the time. A saved step without `keepJoined` +/// was recorded before the preference existed, so it opens the paths as it did then. +fn keeps_paths_joined(s: &mut Session, p: &Value) -> Result { + let default = s.prefs.delete_keeps_paths_joined && !s.replaying(); + let on = switch_or(p, "keepJoined", default, "edit.clear")?; + s.note_journal("keepJoined", json!(on)); + Ok(on) +} + /// Document ids scope node ids: two tabs may contain objects with the same node id. fn drop_selection(s: &mut Session, p: &Value) -> Result { const CMD: &str = "edit.dropSelection"; diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index d32594d92d..feb1c0ad10 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Delete Anchor Points", [], None, - "{} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key)", + "{} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key, unless the deleteKeepsPathsJoined preference is on)", has_anchors, delete_anchors ), @@ -1652,6 +1652,17 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result { /// Layers are retained, and an object removed with a selected ancestor is not removed twice. /// Returns JSON `null` on success; selection is replaced by the surviving object IDs. pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { + delete_anchors_joined(s, p, false) +} + +/// [`delete_anchors`], and with `keep_joined` (General › Delete Removes Anchor Points and Keeps +/// Paths Joined) a path with direct-selected anchors and no selected segment loses those anchors +/// as Remove Anchor Points takes them, without opening it, and stays selected with the next +/// anchor along (the one before at an open subpath's end), so the next Delete goes on along the +/// path. When no subpath it changed keeps two anchors, the path stays selected whole, as Remove +/// Anchor Points leaves it. Paths with a selected segment are cut there, as without `keep_joined` +/// (their selected anchors stay in the path), and objects selected whole are deleted, in the same undo step. +pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: bool) -> Result { // `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step. let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?; let st = s.doc()?; @@ -1681,6 +1692,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { d.remove_many(&whole_ids)?; } let mut survivors = vec![]; + let mut following = vec![]; let remaining: Vec = sel.keys().copied().filter(|id| d.node(*id).is_some()).collect(); let mut emptied = Beside::replacing(d, &remaining); for (id, set) in &sel { @@ -1688,6 +1700,23 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { if d.node(*id).is_none() { continue; } + if keep_joined + && !set.is_empty() + && !segments.contains_key(id) + && let Some(path) = d.node(*id).and_then(|n| match &n.kind { + NodeKind::Path { path, .. } => Some(path), + _ => None, + }) + { + let shape: Vec<(usize, bool)> = path.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect(); + let anchors: Vec<(usize, usize)> = set.iter().copied().collect(); + let next = super::draw2::following_anchors(&shape, &anchors); + if !super::draw2::remove_anchors_of(d, selection, &mut emptied, *id, anchors, false)? { + survivors.push(*id); + following.push((*id, next)); + } + continue; + } let original = deletion_source(d, *id)?; let subpaths: Vec = { let path = path_mut(d, *id)?; @@ -1731,6 +1760,11 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { } } selection.set(survivors); + for (id, next) in following { + if !next.is_empty() { + selection.anchors.insert(id, next); + } + } Ok(()) })?; ok() diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 46cdee28a5..51b5e943db 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -140,6 +140,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("pasteOffset", "General", "", "Paste Offset", len(0.0, 1296.0, General)), p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool), p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool), + p!("deleteKeepsPathsJoined", "General", "Options", "Delete Removes Anchor Points and Keeps Paths Joined", bool), p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool), p!("showToolTips", "General", "Options", "Show Tool Tips", bool), p!("showToolCards", "General", "Options", "Show Tool Cards", bool), diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 2e0d0f9fe4..12dcb1518f 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -55,6 +55,12 @@ pub struct Prefs { /// re-mapped by the turn, scale and move that take its old ends to its new ends. Off (the /// default), the handles of a moved anchor move with it and the other handles stay. pub interpolate_control_points: bool, + /// General › Delete Removes Anchor Points and Keeps Paths Joined: the default of the + /// `keepJoined` param of `edit.clear` (the Delete and Backspace keys and Edit › Clear). On, + /// Clear removes the direct-selected anchors of a path as Remove Anchor Points does, refitting + /// the curve around each one, instead of deleting them with their segments. Off (the default), + /// Clear opens the path there. + pub delete_keeps_paths_joined: bool, pub use_precise_cursors: bool, pub show_tool_tips: bool, /// General › Show Tool Cards: with tool tips on, a tool button's tool tip is a card with what the @@ -464,6 +470,7 @@ impl Default for Prefs { corner_radius: 12.0, disable_auto_add_delete: false, interpolate_control_points: false, + delete_keeps_paths_joined: false, use_precise_cursors: false, show_tool_tips: true, show_tool_cards: false, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..6ae53a583d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -49,6 +49,7 @@ mod curvature_circle; mod cut; mod dashalign; mod dcs; +mod delete_keeps_joined; mod distort; mod docsetup; mod document_close; diff --git a/crates/engine/src/tests/delete_keeps_joined.rs b/crates/engine/src/tests/delete_keeps_joined.rs new file mode 100644 index 0000000000..8a0b625e8e --- /dev/null +++ b/crates/engine/src/tests/delete_keeps_joined.rs @@ -0,0 +1,227 @@ +//! General › Delete Removes Anchor Points and Keeps Paths Joined (`deleteKeepsPathsJoined`). With +//! it on, Delete (`edit.clear`) removes the direct-selected anchors of a path as Remove Anchor +//! Points does, without opening the path. Off (the default), Delete removes them with their +//! segments. + +use serde_json::json; +use vectorcraft_geom::{PathData, Point}; + +use super::history; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn keep_joined(s: &mut Session, on: bool) { + s.execute("prefs.set", &json!({"key": "deleteKeepsPathsJoined", "value": on})).unwrap(); +} + +fn path_of(s: &Session, id: NodeId) -> Option { + s.doc().unwrap().doc.node(id).and_then(|n| n.path_data().cloned()) +} + +fn points(s: &Session, id: NodeId) -> Vec { + path_of(s, id).unwrap().subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect() +} + +fn create(s: &mut Session, anchors: serde_json::Value, closed: bool) -> NodeId { + NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": closed })).unwrap()["id"].as_u64().unwrap()) +} + +fn square(s: &mut Session, x: f64) -> NodeId { + create(s, json!([{"x": x, "y": 100}, {"x": x + 100.0, "y": 100}, {"x": x + 100.0, "y": 200}, {"x": x, "y": 200}]), true) +} + +fn line(s: &mut Session, y: f64) -> NodeId { + create(s, json!([{"x": 100, "y": y}, {"x": 150, "y": y - 20.0}, {"x": 200, "y": y}, {"x": 250, "y": y + 20.0}, {"x": 300, "y": y}]), false) +} + +fn select(s: &mut Session, id: NodeId, anchors: serde_json::Value, mode: &str) { + s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": mode})).unwrap(); +} + +fn objects(s: &Session) -> usize { + s.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |c| c.len())).sum() +} + +#[test] +fn off_by_default_delete_opens_a_closed_path() { + let mut s = session(); + assert!(!s.prefs.delete_keeps_paths_joined); + let id = square(&mut s, 100.0); + select(&mut s, id, json!([[0, 1]]), "set"); + s.execute("edit.clear", &json!({})).unwrap(); + let path = path_of(&s, id).unwrap(); + assert!(!path.subpaths[0].closed, "the path opens where the anchor was"); + assert_eq!(path.subpaths[0].anchors.len(), 3); +} + +#[test] +fn with_the_preference_on_delete_keeps_a_closed_path_closed_and_selects_the_next_anchor() { + let mut s = session(); + keep_joined(&mut s, true); + let id = square(&mut s, 100.0); + select(&mut s, id, json!([[0, 1]]), "set"); + let before = history(&s).0; + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(history(&s).0, before + 1, "one undo step"); + let path = path_of(&s, id).unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(path.subpaths[0].closed, "the path stays closed"); + assert!(!points(&s, id).contains(&Point::new(200.0, 100.0)), "the selected anchor is gone"); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, vec![id], "the path stays selected"); + assert_eq!(st.selection.anchors[&id], [(0, 1)].into(), "the anchor after the removed one is selected"); + // A second Delete goes on along the path. + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(points(&s, id), vec![Point::new(100.0, 100.0), Point::new(100.0, 200.0)]); +} + +#[test] +fn an_open_path_loses_an_end_anchor_and_an_interior_anchor_without_splitting() { + let mut s = session(); + keep_joined(&mut s, true); + let id = line(&mut s, 300.0); + select(&mut s, id, json!([[0, 0], [0, 2]]), "set"); + s.execute("edit.clear", &json!({})).unwrap(); + let path = path_of(&s, id).unwrap(); + assert_eq!(path.subpaths.len(), 1, "one piece"); + assert!(!path.subpaths[0].closed); + assert_eq!( + points(&s, id), + vec![Point::new(150.0, 280.0), Point::new(250.0, 320.0), Point::new(300.0, 300.0)], + "the path is shorter at its start" + ); + assert_eq!(objects(&s), 1, "no new object"); + assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1)].into(), "the anchor after the last removed one is selected"); + // Removing the last anchor of an open path selects the one before it. + select(&mut s, id, json!([[0, 2]]), "set"); + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(points(&s, id), vec![Point::new(150.0, 280.0), Point::new(250.0, 320.0)], "the path is shorter at its end"); + assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1)].into(), "the new end anchor is selected"); +} + +#[test] +fn a_subpath_left_with_one_anchor_goes_and_the_path_stays_selected_whole() { + let mut s = session(); + keep_joined(&mut s, true); + let id = square(&mut s, 100.0); + let sq = json!({"closed": true, "anchors": [{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]}); + let pair = json!({"closed": false, "anchors": [{"x": 300, "y": 100}, {"x": 400, "y": 100}]}); + s.execute("path.setAnchors", &json!({"id": id.0, "subpaths": [sq, pair]})).unwrap(); + select(&mut s, id, json!([[1, 0]]), "set"); + s.execute("edit.clear", &json!({})).unwrap(); + let path = path_of(&s, id).unwrap(); + assert_eq!(path.subpaths.len(), 1, "the subpath left with one anchor goes"); + assert!(path.subpaths[0].closed && path.subpaths[0].anchors.len() == 4, "the other subpath is untouched"); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, vec![id], "the path stays selected"); + assert!(st.selection.anchors.get(&id).is_none_or(|a| a.is_empty()), "no anchor is left to go on from"); +} + +#[test] +fn a_path_left_with_fewer_than_two_anchors_is_deleted() { + let mut s = session(); + keep_joined(&mut s, true); + let id = create(&mut s, json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}]), false); + let other = square(&mut s, 400.0); + select(&mut s, id, json!([[0, 1]]), "set"); + select(&mut s, other, json!([[0, 0]]), "add"); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(path_of(&s, id).is_none(), "a single anchor is no path"); + assert!(path_of(&s, other).unwrap().subpaths[0].closed, "the other path keeps its other anchors joined"); + assert_eq!(s.doc().unwrap().selection.objects, vec![other]); +} + +#[test] +fn several_paths_and_an_object_selected_whole_change_in_one_undo_step() { + let mut s = session(); + keep_joined(&mut s, true); + let (a, b, whole) = (square(&mut s, 100.0), line(&mut s, 400.0), square(&mut s, 500.0)); + select(&mut s, a, json!([[0, 0]]), "set"); + select(&mut s, b, json!([[0, 1], [0, 3]]), "add"); + s.execute("select.add", &json!({"ids": [whole.0]})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let before = history(&s).0; + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(history(&s).0, before + 1, "one undo step"); + assert!(path_of(&s, whole).is_none(), "the object selected whole is deleted"); + assert!(path_of(&s, a).unwrap().subpaths[0].closed); + assert_eq!(path_of(&s, a).unwrap().subpaths[0].anchors.len(), 3); + assert_eq!(points(&s, b), vec![Point::new(100.0, 400.0), Point::new(200.0, 400.0), Point::new(300.0, 400.0)]); + let st = s.doc().unwrap(); + assert!(st.selection.anchors.contains_key(&a) && st.selection.anchors.contains_key(&b), "both paths keep an anchor selected"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, doc, "Undo restores every path"); +} + +#[test] +fn a_compound_path_keeps_its_members_and_loses_one_left_with_no_segment() { + let mut s = session(); + keep_joined(&mut s, true); + let (outer, inner) = (square(&mut s, 100.0), create(&mut s, json!([{"x": 130, "y": 150}, {"x": 170, "y": 150}]), false)); + s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, outer, json!([[0, 2]]), "set"); + select(&mut s, inner, json!([[0, 0]]), "add"); + s.execute("edit.clear", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(inner).is_none(), "the member left with one anchor goes"); + assert_eq!(d.parent_of(outer), Some(compound), "the other member stays in the compound path"); + assert!(path_of(&s, outer).unwrap().subpaths[0].closed); + assert_eq!(path_of(&s, outer).unwrap().subpaths[0].anchors.len(), 3); +} + +#[test] +fn a_selected_segment_is_still_cut() { + let mut s = session(); + keep_joined(&mut s, true); + let id = square(&mut s, 100.0); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 0]]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let path = path_of(&s, id).unwrap(); + assert!(!path.subpaths[0].closed, "the segment's connection is removed"); + assert_eq!(path.subpaths[0].anchors.len(), 4, "every anchor stays"); +} + +#[test] +fn the_keep_joined_param_overrides_the_preference_and_must_be_a_boolean() { + let mut s = session(); + let id = square(&mut s, 100.0); + select(&mut s, id, json!([[0, 1]]), "set"); + assert!(s.execute("edit.clear", &json!({"keepJoined": "yes"})).is_err()); + assert_eq!(path_of(&s, id).unwrap().subpaths[0].anchors.len(), 4, "a refused call changes nothing"); + s.execute("edit.clear", &json!({"keepJoined": true})).unwrap(); + assert!(path_of(&s, id).unwrap().subpaths[0].closed); + keep_joined(&mut s, true); + s.execute("edit.clear", &json!({"keepJoined": false})).unwrap(); + assert!(!path_of(&s, id).unwrap().subpaths[0].closed, "false opens the path with the preference on"); +} + +#[test] +fn a_replay_removes_anchors_as_the_recorded_step_did() { + let mut s = session(); + keep_joined(&mut s, true); + let id = square(&mut s, 100.0); + select(&mut s, id, json!([[0, 1]]), "set"); + let start = s.journal.len(); + s.execute("edit.clear", &json!({})).unwrap(); + let removed = path_of(&s, id); + assert!(removed.as_ref().is_some_and(|p| p.subpaths[0].closed), "the path stays closed"); + let (cmd, params) = s.journal.since(start).last().cloned().unwrap(); + assert_eq!(params["keepJoined"], json!(true), "{cmd}: journaled"); + s.execute("edit.undo", &json!({})).unwrap(); + keep_joined(&mut s, false); + select(&mut s, id, json!([[0, 1]]), "set"); + s.replay(&cmd, ¶ms).unwrap(); + assert_eq!(path_of(&s, id), removed); + // A step saved before the preference existed has no `keepJoined` and still opens the path. + s.execute("edit.undo", &json!({})).unwrap(); + keep_joined(&mut s, true); + select(&mut s, id, json!([[0, 1]]), "set"); + s.replay("edit.clear", &json!({})).unwrap(); + assert!(!path_of(&s, id).unwrap().subpaths[0].closed); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..19ccb5c613 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -895,6 +895,7 @@ font-technology Variable Променливи Direct Selection Tool Инструмент „Директен избор“ Direction Handles Маркери за посока Disable Auto Add/Delete Изключване на автоматично добавяне/изтриване + Delete Removes Anchor Points and Keeps Paths Joined Delete премахва опорните точки и запазва контурите свързани Interpolate Control Points When Moving Anchors Интерполиране на маркерите за посока при преместване на опорни точки Disable Opacity Mask Изключване на маска за непрозрачност Discard Отхвърляне @@ -3220,6 +3221,7 @@ digits Malayalam Малаялам A two-finger rotate gesture on a trackpad rotates the canvas view. Жест за завъртане с два пръста върху тъчпад завърта изгледа на платното. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Задържането на клавиш изпълнява инструмента или командата от колоната „Задръжте“ в „Клавишни комбинации“; краткото натискане изпълнява обичайната му комбинация. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Колко секунди трябва да се задържи клавиш, преди вместо обичайната му комбинация да се изпълни комбинацията му със задържане. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete премахва избраните опорни точки и напасва кривата около всяка от тях, вместо да отваря контура там. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Когато премествате котвени точки, всяка крива с една преместена крайна точка запазва формата си спрямо краищата си. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Задържането на клавишната комбинация на инструмент го избира, докато я пуснете, а след това отново се избира предишният инструмент. Shows the bounding box while you move the selection or draw a shape. Показва ограничителната рамка, докато премествате селекцията или рисувате форма. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..77017db1fb 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4126,6 +4126,7 @@ theme Appearance Izgled Data Recovery Oporavak podataka Default Language Zadani jezik Disable Auto Add/Delete Onemogući automatsko dodavanje/brisanje + Delete Removes Anchor Points and Keeps Paths Joined Delete uklanja sidrene tačke i zadržava putanje spojenim Interpolate Control Points When Moving Anchors Interpoliraj ručke smjera pri pomjeranju sidrenih tačaka Display All Blacks Accurately Prikaži sve crne tačno Display All Blacks as Rich Black Prikaži sve crne kao bogatu crnu @@ -4707,6 +4708,7 @@ font-technology Variable Varijabilni A two-finger rotate gesture on a trackpad rotates the canvas view. Pokret rotacije s dva prsta na dodirnoj podlozi rotira prikaz platna. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Držanje tipke pokreće alat ili naredbu iz njene kolone „Zadrži“ u Prečicama na tastaturi; kratki pritisak pokreće njenu uobičajenu prečicu. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Koliko sekundi tipka mora biti pritisnuta prije nego što se umjesto uobičajene prečice pokrene njena prečica zadržavanjem. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete uklanja odabrane sidrene tačke i ponovo prilagođava krivu oko svake od njih, umjesto da tamo otvori putanju. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Kada pomjerate sidrene tačke, svaka kriva s jednim pomjerenim krajem zadržava svoj oblik u odnosu na svoje krajeve. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Držanje prečice alata bira taj alat dok je ne pustite, a zatim se ponovo bira prethodni alat. Shows the bounding box while you move the selection or draw a shape. Prikazuje granični okvir dok pomjerate odabir ili crtate oblik. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..04eccfe9cf 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1330,6 +1330,7 @@ arrowhead Target Diana Direction: Direcció: Directives Directrius Disable Auto Add/Delete Desactiva l’addició i la supressió automàtiques + Delete Removes Anchor Points and Keeps Paths Joined Suprimir elimina els punts d’ancoratge i manté els camins units Interpolate Control Points When Moving Anchors Interpola les manetes de direcció en moure punts d’ancoratge Disable Opacity Mask Desactiva la màscara d’opacitat Discard Descarta @@ -4078,6 +4079,7 @@ digits Malayalam Malaiàlam A two-finger rotate gesture on a trackpad rotates the canvas view. Un gest de rotació amb dos dits al trackpad gira la vista del llenç. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Mantenir premuda una tecla executa l’eina o l’ordre de la seva columna Mantén a Dreceres de teclat; una pulsació breu executa la seva drecera habitual. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Quants segons cal mantenir premuda una tecla perquè s’executi la seva drecera de pulsació llarga en lloc de la drecera habitual. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Suprimir elimina els punts d’ancoratge seleccionats i reajusta la corba al voltant de cadascun, en lloc d’obrir-hi el camí. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quan moveu punts d’ancoratge, cada corba amb un extrem desplaçat conserva la forma respecte dels seus extrems. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Mantenir premuda la drecera d’una eina la tria fins que la deixeu anar, i després es torna a triar l’eina anterior. Shows the bounding box while you move the selection or draw a shape. Mostra el quadre delimitador mentre moveu la selecció o dibuixeu una forma. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..fff65f95a3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4231,6 +4231,7 @@ theme Appearance Motiv Data Recovery Obnovení dat Default Language Výchozí jazyk Disable Auto Add/Delete Vypnout automatické přidávání/odstraňování + Delete Removes Anchor Points and Keeps Paths Joined Delete odstraní kotevní body a ponechá cesty spojené Interpolate Control Points When Moving Anchors Interpolovat směrové úchyty při přesouvání kotevních bodů Display All Blacks Accurately Zobrazovat všechny černé přesně Display All Blacks as Rich Black Zobrazovat všechny černé jako sytou černou @@ -4816,6 +4817,7 @@ font-technology Variable Variabilní A two-finger rotate gesture on a trackpad rotates the canvas view. Gesto otočení dvěma prsty na trackpadu otáčí zobrazení plátna. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Podržení klávesy spustí nástroj nebo příkaz ze sloupce Podržení v Klávesových zkratkách; krátký stisk spustí její obvyklou zkratku. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Jak dlouho v sekundách je nutné klávesu podržet, než se místo obvyklé zkratky spustí její zkratka podržením. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete odstraní vybrané kotevní body a znovu přizpůsobí křivku kolem každého z nich, místo aby tam cestu otevřel. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Když přesouváte kotvové body, každá křivka s jedním přesunutým koncem si zachová tvar vůči svým koncům. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Podržení zkratky nástroje vybere nástroj, dokud ji nepustíte, a pak se znovu vybere předchozí nástroj. Shows the bounding box while you move the selection or draw a shape. Zobrazí ohraničovací rámeček, když přesouváte výběr nebo kreslíte tvar. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..48b9851f66 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6704,6 +6704,7 @@ theme Appearance Udseende Data Recovery Datgendannelse Default Language Standardsprog Disable Auto Add/Delete Deaktivér automatisk tilføjelse/sletning + Delete Removes Anchor Points and Keeps Paths Joined Delete fjerner ankerpunkter og holder stier samlet Interpolate Control Points When Moving Anchors Interpolér retningshåndtag ved flytning af ankerpunkter Display All Blacks Accurately Vis alle sorte nøjagtigt Display All Blacks as Rich Black Vis alle sorte som rich black @@ -7264,6 +7265,7 @@ font-technology Variable Variable A two-finger rotate gesture on a trackpad rotates the canvas view. En rotationsbevægelse med to fingre på en pegeplade roterer visningen af lærredet. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Når du holder en tast nede, køres værktøjet eller kommandoen i dens Hold-kolonne i Tastaturgenveje; et kort tryk kører dens sædvanlige genvej. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Hvor mange sekunder en tast skal holdes nede, før dens holdegenvej køres i stedet for dens sædvanlige genvej. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete fjerner de markerede ankerpunkter og tilpasser kurven omkring hvert af dem i stedet for at åbne stien der. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Når du flytter ankerpunkter, beholder hver kurve med ét flyttet endepunkt sin form i forhold til sine endepunkter. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Når du holder et værktøjs genvejstast nede, er værktøjet valgt, indtil du slipper, og derefter vælges det forrige værktøj igen. Shows the bounding box while you move the selection or draw a shape. Viser afgrænsningsboksen, mens du flytter markeringen eller tegner en form. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..1929336a01 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -908,6 +908,7 @@ font-technology Variable Variabel Direct Selection Tool Direktauswahl-Werkzeug Direction Handles Richtungsgriffe Disable Auto Add/Delete Automatisches Hinzufügen/Löschen deaktivieren + Delete Removes Anchor Points and Keeps Paths Joined Entf entfernt Ankerpunkte und lässt Pfade verbunden Interpolate Control Points When Moving Anchors Richtungsgriffe beim Verschieben von Ankerpunkten interpolieren Disable Opacity Mask Deckkraftmaske deaktivieren Discard Verwerfen @@ -3290,6 +3291,7 @@ digits Malayalam Malayalam A two-finger rotate gesture on a trackpad rotates the canvas view. Eine Drehgeste mit zwei Fingern auf einem Trackpad dreht die Ansicht der Arbeitsfläche. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Halten Sie eine Taste, wird das Werkzeug oder der Befehl aus ihrer Spalte „Halten“ unter „Tastaturbefehle“ ausgeführt; ein kurzer Druck führt ihren üblichen Tastaturbefehl aus. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Wie viele Sekunden eine Taste gehalten werden muss, bevor statt ihres üblichen Tastaturbefehls ihr Halte-Tastaturbefehl ausgeführt wird. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Entf entfernt die ausgewählten Ankerpunkte und passt die Kurve um jeden davon neu an, statt den Pfad dort zu öffnen. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Wenn Sie Ankerpunkte verschieben, behält jede Kurve mit einem verschobenen Ende ihre Form relativ zu ihren Enden. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Solange Sie das Tastaturkürzel eines Werkzeugs gedrückt halten, ist dieses Werkzeug gewählt; danach wird wieder das vorherige gewählt. Shows the bounding box while you move the selection or draw a shape. Zeigt den Begrenzungsrahmen an, während Sie die Auswahl verschieben oder eine Form zeichnen. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..a73cac3078 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -880,6 +880,7 @@ font-technology Variable Μεταβλητές Direct Selection Tool Άμεση επιλογή (Direct Selection Tool) Direction Handles Λαβές κατεύθυνσης Disable Auto Add/Delete Απενεργοποίηση αυτόματης προσθήκης/διαγραφής + Delete Removes Anchor Points and Keeps Paths Joined Το Delete αφαιρεί σημεία αγκύρωσης και διατηρεί τις διαδρομές ενωμένες Interpolate Control Points When Moving Anchors Παρεμβολή λαβών κατεύθυνσης κατά τη μετακίνηση σημείων αγκύρωσης Disable Opacity Mask Απενεργοποίηση μάσκας αδιαφάνειας Discard Απόρριψη @@ -4143,6 +4144,7 @@ digits Malayalam Μαλαγιάλαμ A two-finger rotate gesture on a trackpad rotates the canvas view. Μια κίνηση περιστροφής με δύο δάχτυλα σε επιφάνεια αφής περιστρέφει την προβολή του καμβά. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Το παρατεταμένο πάτημα ενός πλήκτρου εκτελεί το εργαλείο ή την εντολή της στήλης «Κρατήστε πατημένο» στις Συντομεύσεις πληκτρολογίου· ένα σύντομο πάτημα εκτελεί τη συνηθισμένη συντόμευσή του. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Πόσα δευτερόλεπτα πρέπει να μένει πατημένο ένα πλήκτρο πριν εκτελεστεί η συντόμευση παρατεταμένου πατήματος αντί για τη συνηθισμένη συντόμευσή του. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Το Delete αφαιρεί τα επιλεγμένα σημεία αγκύρωσης και προσαρμόζει ξανά την καμπύλη γύρω από το καθένα, αντί να ανοίγει τη διαδρομή εκεί. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Όταν μετακινείτε σημεία αγκύρωσης, κάθε καμπύλη με ένα μετακινημένο άκρο διατηρεί το σχήμα της σε σχέση με τα άκρα της. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Όσο κρατάτε πατημένη τη συντόμευση ενός εργαλείου, το εργαλείο είναι επιλεγμένο, και μετά επιλέγεται ξανά το προηγούμενο εργαλείο. Shows the bounding box while you move the selection or draw a shape. Εμφανίζει το πλαίσιο οριοθέτησης όσο μετακινείτε την επιλογή ή σχεδιάζετε ένα σχήμα. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..ce59cdface 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -926,6 +926,7 @@ font-technology Variable Variables Direct Selection Tool Herramienta Selección directa Direction Handles Manejadores de dirección Disable Auto Add/Delete Desactivar agregar/eliminar automático + Delete Removes Anchor Points and Keeps Paths Joined Suprimir quita puntos de ancla y mantiene los trazados unidos Interpolate Control Points When Moving Anchors Interpolar manejadores de dirección al mover puntos de ancla Disable Opacity Mask Desactivar máscara de opacidad Discard Descartar @@ -3326,6 +3327,7 @@ digits Malayalam Malayálam A two-finger rotate gesture on a trackpad rotates the canvas view. Un gesto de giro con dos dedos en un trackpad gira la vista del lienzo. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Mantener pulsada una tecla ejecuta la herramienta o el comando de su columna Mantener pulsado en Métodos abreviados de teclado; una pulsación breve ejecuta su método abreviado habitual. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Cuántos segundos hay que mantener pulsada una tecla para que se ejecute su método abreviado de pulsación larga en lugar del habitual. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Suprimir quita los puntos de ancla seleccionados y reajusta la curva alrededor de cada uno, en lugar de abrir el trazado ahí. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Al mover puntos de ancla, cada curva con un extremo movido conserva su forma respecto a sus extremos. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Mantener pulsado el atajo de una herramienta la elige hasta que lo suelta, y después vuelve a elegirse la herramienta anterior. Shows the bounding box while you move the selection or draw a shape. Muestra el cuadro delimitador mientras mueve la selección o dibuja una forma. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..8037e7b9d4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4162,6 +4162,7 @@ theme Appearance Ulkoasu Data Recovery Tietojen palautus Default Language Oletuskieli Disable Auto Add/Delete Poista automaattinen lisäys/poisto käytöstä + Delete Removes Anchor Points and Keeps Paths Joined Delete poistaa ankkuripisteet ja pitää polut yhtenäisinä Interpolate Control Points When Moving Anchors Interpoloi suuntakahvat siirrettäessä ankkuripisteitä Display All Blacks Accurately Näytä kaikki mustat tarkasti Display All Blacks as Rich Black Näytä kaikki mustat syvämustina @@ -4726,6 +4727,7 @@ font-technology Variable Muuttuvat A two-finger rotate gesture on a trackpad rotates the canvas view. Kahden sormen kiertoele kosketuslevyllä kiertää piirtopinnan näkymää. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Näppäimen pitäminen painettuna suorittaa työkalun tai komennon sen Pidä pohjassa -sarakkeesta Pikanäppäimissä; lyhyt painallus suorittaa sen tavallisen pikanäppäimen. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Kuinka monta sekuntia näppäintä on pidettävä painettuna, ennen kuin tavallisen pikanäppäimen sijaan suoritetaan sen pitkän painalluksen pikanäppäin. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete poistaa valitut ankkuripisteet ja sovittaa käyrän uudelleen kunkin ympärille sen sijaan, että avaisi polun siitä kohdasta. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Kun siirrät ankkuripisteitä, jokainen käyrä, jonka toinen pää siirtyy, säilyttää muotonsa suhteessa päihinsä. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Työkalun pikanäppäimen pitäminen painettuna valitsee työkalun, kunnes päästät irti, ja sitten edellinen työkalu valitaan uudelleen. Shows the bounding box while you move the selection or draw a shape. Näyttää rajausruudun, kun siirrät valintaa tai piirrät muotoa. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..f7cfd6e586 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -929,6 +929,7 @@ font-technology Variable Variables Direct Selection Tool Outil Sélection directe Direction Handles Poignées de direction Disable Auto Add/Delete Désactiver l’ajout/suppression automatique + Delete Removes Anchor Points and Keeps Paths Joined Suppr supprime les points d’ancrage et garde les tracés joints Interpolate Control Points When Moving Anchors Interpoler les poignées de direction lors du déplacement des points d’ancrage Disable Opacity Mask Désactiver le masque d’opacité Discard Ignorer @@ -3314,6 +3315,7 @@ digits Malayalam Malayalam A two-finger rotate gesture on a trackpad rotates the canvas view. Un geste de rotation à deux doigts sur un pavé tactile fait pivoter la vue de la zone de travail. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Maintenir une touche exécute l’outil ou la commande de sa colonne Maintenir dans Raccourcis clavier. Un appui bref exécute son raccourci habituel. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Durée, en secondes, pendant laquelle une touche doit être maintenue pour que son raccourci de maintien s’exécute à la place de son raccourci habituel. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Suppr supprime les points d’ancrage sélectionnés et réajuste la courbe autour de chacun, au lieu d’ouvrir le tracé à cet endroit. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quand vous déplacez des points d’ancrage, chaque courbe dont une extrémité bouge garde sa forme par rapport à ses extrémités. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Maintenir le raccourci d’un outil choisit cet outil jusqu’à ce que vous le relâchiez, puis l’outil précédent est de nouveau choisi. Shows the bounding box while you move the selection or draw a shape. Affiche le cadre de sélection pendant que vous déplacez la sélection ou dessinez une forme. diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..a98c2bdad8 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1072,6 +1072,7 @@ Direction: દિશા: Directives નિર્દેશો Disable Auto Add/Delete ઑટો ઍડ/ડિલીટ બંધ કરો + Delete Removes Anchor Points and Keeps Paths Joined Delete એન્કર બિંદુઓ દૂર કરે છે અને પાથને જોડાયેલા રાખે છે Interpolate Control Points When Moving Anchors એન્કર બિંદુઓ ખસેડતી વખતે દિશા હેન્ડલ્સ ઇન્ટરપોલેટ કરો Disable Opacity Mask ઓપેસિટી માસ્ક બંધ કરો Disable and Continue બંધ કરો અને ચાલુ રાખો @@ -3381,6 +3382,7 @@ arrowhead Feather પીંછું A two-finger rotate gesture on a trackpad rotates the canvas view. ટ્રેકપેડ પર બે આંગળીથી ફેરવવાનો હાવભાવ કેનવાસનું દૃશ્ય ફેરવે છે. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. કી દબાવી રાખવાથી કીબોર્ડ શૉર્ટકટમાં તેની હોલ્ડ કૉલમનું ટૂલ અથવા કમાન્ડ ચાલે છે; ટૂંકું દબાણ તેનો સામાન્ય શોર્ટકટ ચલાવે છે. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. કીનો હોલ્ડ શોર્ટકટ તેના સામાન્ય શોર્ટકટને બદલે ચાલે તે પહેલાં કીને કેટલી સેકન્ડ દબાવી રાખવી પડે. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete પસંદ કરેલા એન્કર પોઇન્ટ દૂર કરે છે અને ત્યાં પાથ ખોલવાને બદલે દરેકની આસપાસ વળાંકને ફરી ગોઠવે છે. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. જ્યારે તમે એન્કર પોઇન્ટ ખસેડો છો, ત્યારે એક ખસેલા છેડાવાળો દરેક વળાંક તેના છેડાઓની સાપેક્ષે પોતાનો આકાર જાળવે છે. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ટૂલની શોર્ટકટ કી દબાવી રાખવાથી છોડો ત્યાં સુધી તે ટૂલ પસંદ રહે છે, પછી અગાઉનું ટૂલ ફરી પસંદ થાય છે. Shows the bounding box while you move the selection or draw a shape. તમે પસંદગી ખસેડો કે આકાર દોરો ત્યારે બાઉન્ડિંગ બોક્સ બતાવે છે. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..1bf2a7a623 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1745,6 +1745,7 @@ arrowhead Feather पंख Direction: दिशा: Directives निर्देश Disable Auto Add/Delete ऑटो जोड़ना/हटाना अक्षम करें + Delete Removes Anchor Points and Keeps Paths Joined Delete एंकर पॉइंट हटाता है और पाथ को जुड़ा रखता है Interpolate Control Points When Moving Anchors एंकर पॉइंट खिसकाते समय निर्देशन हैंडल इंटरपोलेट करें Disable Opacity Mask ओपेसिटी मास्क अक्षम करें Discard डिस्कर्ड @@ -4709,6 +4710,7 @@ arrowhead Feather पंख A two-finger rotate gesture on a trackpad rotates the canvas view. ट्रैकपैड पर दो उंगलियों से घुमाने का जेस्चर कैनवास के व्यू को घुमाता है। Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. किसी कुंजी को दबाए रखने पर कीबोर्ड शॉर्टकट में उसके होल्ड कॉलम का टूल या कमांड चलता है; जल्दी दबाने पर उसका सामान्य शॉर्टकट चलता है। How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. किसी कुंजी को कितने सेकंड दबाए रखना होगा, ताकि उसके सामान्य शॉर्टकट के बजाय उसका होल्ड शॉर्टकट चले। + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete चुने गए एंकर पॉइंट हटाता है और वहाँ पाथ खोलने के बजाय हर एक के आसपास वक्र को फिर से फिट करता है। When you move anchor points, each curve with one moved end keeps its shape relative to its ends. जब आप एंकर पॉइंट हिलाते हैं, तो एक हिले हुए सिरे वाला हर वक्र अपने सिरों के सापेक्ष अपना आकार बनाए रखता है। Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. किसी टूल की शॉर्टकट कुंजी दबाए रखने पर वह टूल छोड़ने तक चुना रहता है, फिर पिछला टूल दोबारा चुना जाता है। Shows the bounding box while you move the selection or draw a shape. सिलेक्शन खिसकाते या आकार ड्रॉ करते समय बाउंडिंग बॉक्स दिखाता है। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..16d8f438f7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1195,6 +1195,7 @@ arrowhead Target Céltábla Direction Handles Iránykezelő fogantyúk Direction: Irány: Disable Auto Add/Delete Automatikus hozzáadás és törlés kikapcsolása + Delete Removes Anchor Points and Keeps Paths Joined A Delete eltávolítja a horgonypontokat, és egyben tartja az útvonalakat Interpolate Control Points When Moving Anchors Iránykezelő fogantyúk interpolálása horgonypontok mozgatásakor Disable Opacity Mask Átlátszósági maszk kikapcsolása Discard Elvetés @@ -3914,6 +3915,7 @@ mark-style Japanese Japán A two-finger rotate gesture on a trackpad rotates the canvas view. Az érintőpadon végzett kétujjas forgató kézmozdulat elforgatja a vászon nézetét. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Egy billentyű nyomva tartása a Billentyűparancsok Nyomva tartás oszlopában lévő eszközt vagy parancsot futtatja; egy rövid lenyomás a szokásos billentyűparancsát futtatja. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Hány másodpercig kell nyomva tartani egy billentyűt, hogy a szokásos billentyűparancsa helyett a nyomva tartásos billentyűparancsa fusson. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. A Delete eltávolítja a kijelölt horgonypontokat, és mindegyik körül újraigazítja a görbét ahelyett, hogy ott megnyitná az útvonalat. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Horgonypontok mozgatásakor minden olyan görbe, amelynek egyik vége elmozdul, megtartja az alakját a végeihez képest. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Egy eszköz billentyűparancsát lenyomva tartva az eszköz a felengedésig ki van választva, utána ismét az előző eszköz lesz kiválasztva. Shows the bounding box while you move the selection or draw a shape. Megjeleníti a befoglaló keretet, miközben a kijelölést mozgatja vagy alakzatot rajzol. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..1d8647ddf9 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4572,6 +4572,7 @@ theme Appearance Tampilan Data Recovery Pemulihan data Default Language Bahasa standar Disable Auto Add/Delete Nonaktifkan tambah/hapus otomatis + Delete Removes Anchor Points and Keeps Paths Joined Delete menghapus titik jangkar dan menjaga jalur tetap tersambung Interpolate Control Points When Moving Anchors Interpolasikan gagang arah saat memindahkan titik jangkar Display All Blacks Accurately Tampilkan semua warna hitam secara akurat Display All Blacks as Rich Black Tampilkan semua warna hitam sebagai rich black @@ -5130,6 +5131,7 @@ font-technology Variable Variabel A two-finger rotate gesture on a trackpad rotates the canvas view. Gerakan putar dua jari pada trackpad memutar tampilan kanvas. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Menahan tombol menjalankan alat atau perintah di kolom Tahan pada Pintasan papan ketik; tekanan singkat menjalankan pintasan biasanya. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Berapa detik tombol harus ditahan sebelum pintasan tahannya berjalan sebagai ganti pintasan biasanya. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete menghapus titik jangkar yang dipilih dan menyesuaikan ulang kurva di sekitar masing-masing, alih-alih membuka jalur di sana. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Saat Anda memindahkan titik jangkar, setiap kurva dengan satu ujung yang dipindahkan mempertahankan bentuknya terhadap ujung-ujungnya. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Menahan tombol pintasan alat memilih alat itu sampai Anda melepasnya, lalu alat sebelumnya dipilih lagi. Shows the bounding box while you move the selection or draw a shape. Menampilkan kotak pembatas saat Anda memindahkan seleksi atau menggambar bentuk. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..0d811ec478 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -929,6 +929,7 @@ font-technology Variable Variabili Direct Selection Tool Strumento Selezione diretta Direction Handles Maniglie di direzione Disable Auto Add/Delete Disattiva aggiunta/eliminazione automatica + Delete Removes Anchor Points and Keeps Paths Joined Canc rimuove i punti di ancoraggio e mantiene i tracciati uniti Interpolate Control Points When Moving Anchors Interpola le maniglie di direzione durante lo spostamento dei punti di ancoraggio Disable Opacity Mask Disattiva maschera di opacità Discard Scarta @@ -3375,6 +3376,7 @@ digits Malayalam Malayalam A two-finger rotate gesture on a trackpad rotates the canvas view. Un gesto di rotazione con due dita sul trackpad ruota la vista dell'area di lavoro. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Tenere premuto un tasto esegue lo strumento o il comando della sua colonna Tieni premuto in Scelte rapide da tastiera; una pressione breve esegue la sua scorciatoia abituale. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Per quanti secondi va tenuto premuto un tasto prima che venga eseguita la sua scorciatoia a pressione prolungata invece di quella abituale. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Canc rimuove i punti di ancoraggio selezionati e riadatta la curva attorno a ciascuno, invece di aprire lì il tracciato. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quando sposti i punti di ancoraggio, ogni curva con un’estremità spostata mantiene la propria forma rispetto alle sue estremità. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Tenere premuta la scorciatoia di uno strumento lo sceglie finché non la rilasci, poi viene scelto di nuovo lo strumento precedente. Shows the bounding box while you move the selection or draw a shape. Mostra il riquadro di delimitazione mentre sposti la selezione o disegni una forma. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..b90644b618 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1693,6 +1693,7 @@ antiAlias Sharp シャープ Dimensions 寸法 Direct Selection Tool ダイレクト選択ツール Disable Auto Add/Delete 自動追加/削除機能を使用しない + Delete Removes Anchor Points and Keeps Paths Joined Delete でアンカーポイントを削除してパスをつなげたままにする Interpolate Control Points When Moving Anchors アンカーポイントの移動時に方向線ハンドルを補間 Disable Opacity Mask 不透明マスクを無効にする Discard 破棄 @@ -3343,6 +3344,7 @@ mark-style Japanese 日本式 A two-finger rotate gesture on a trackpad rotates the canvas view. トラックパッドで 2 本指の回転ジェスチャーをすると、カンバスの表示が回転します。 Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. キーを長押しすると、キーボードショートカットの長押し列にあるツールまたはコマンドを実行します。短く押すと通常のショートカットを実行します。 How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. 通常のショートカットの代わりに長押しショートカットを実行するまで、キーを押し続ける秒数です。 + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete キーで選択したアンカーポイントを削除し、パスをそこで開かずに、各ポイントの周りの曲線を合わせ直します。 When you move anchor points, each curve with one moved end keeps its shape relative to its ends. アンカーポイントを移動すると、一方の端が移動した各曲線は、両端に対する形状を保ちます。 Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ツールのショートカットキーを押している間はそのツールを選び、離すと前のツールに戻ります。 Shows the bounding box while you move the selection or draw a shape. 選択範囲の移動中や図形の描画中にバウンディングボックスを表示します。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..6e5e84063d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5983,6 +5983,7 @@ theme Appearance იერსახე Data Recovery მონაცემების აღდგენა Default Language ნაგულისხმევი ენა Disable Auto Add/Delete ავტომატური დამატება/წაშლის გამორთვა + Delete Removes Anchor Points and Keeps Paths Joined Delete შლის ღუზის წერტილებს და ინარჩუნებს კონტურებს შეერთებულად Interpolate Control Points When Moving Anchors სახელურების ინტერპოლაცია საყრდენი წერტილების გადაადგილებისას Display All Blacks Accurately ყველა შავის ზუსტად ჩვენება Display All Blacks as Rich Black ყველა შავის მდიდარ შავად ჩვენება @@ -6518,6 +6519,7 @@ font-technology Variable ცვლადი A two-finger rotate gesture on a trackpad rotates the canvas view. ტრეკპადზე ორი თითით მობრუნების ჟესტი ტილოს ხედს აბრუნებს. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. კლავიშის ხანგრძლივი დაჭერა უშვებს ხელსაწყოს ან ბრძანებას კლავიატურის მალსახმობების დაჭერის სვეტიდან; მოკლე დაჭერა უშვებს მის ჩვეულ მალსახმობს. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. რამდენი წამი უნდა იყოს კლავიში დაჭერილი, სანამ ჩვეული მალსახმობის ნაცვლად მისი ხანგრძლივი დაჭერის მალსახმობი გაეშვება. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete შლის არჩეულ ღუზის წერტილებს და თითოეულის გარშემო მრუდს ხელახლა არგებს, ნაცვლად იმისა, რომ იქ კონტური გახსნას. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. როცა ღუზის წერტილებს გადაადგილებთ, ყოველი მრუდი, რომლის ერთი ბოლოც გადაადგილდა, ინარჩუნებს ფორმას თავის ბოლოებთან მიმართებით. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. სანამ ხელსაწყოს მალსახმობ კლავიშს დაჭერილს გიჭირავთ, ეს ხელსაწყოა არჩეული; კლავიშის აშვების შემდეგ ისევ წინა ხელსაწყო აირჩევა. Shows the bounding box while you move the selection or draw a shape. აჩვენებს შემომსაზღვრელ ჩარჩოს, სანამ მონიშნულს გადაადგილებთ ან ფიგურას ხატავთ. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..4a6dbb2ec0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1683,6 +1683,7 @@ antiAlias Sharp 날카롭게 Dimensions 치수 Direct Selection Tool 직접 선택 도구 Disable Auto Add/Delete 자동 추가/삭제 사용 안 함 + Delete Removes Anchor Points and Keeps Paths Joined Delete로 고정점을 제거하고 패스를 연결된 상태로 유지 Interpolate Control Points When Moving Anchors 앵커 포인트 이동 시 방향 핸들 보간 Disable Opacity Mask 불투명 마스크 사용 안 함 Discard 삭제 @@ -3332,6 +3333,7 @@ mark-style Japanese 일본식 A two-finger rotate gesture on a trackpad rotates the canvas view. 트랙패드에서 두 손가락으로 회전하는 동작을 하면 캔버스 보기가 회전합니다. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. 키를 누르고 있으면 키보드 단축키의 누르고 있기 열에 있는 도구나 명령이 실행되고, 짧게 누르면 평소 단축키가 실행됩니다. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. 평소 단축키 대신 길게 누르기 단축키가 실행되기 전까지 키를 누르고 있어야 하는 시간(초)입니다. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete는 선택한 고정점을 제거하고 각 점 주위의 곡선을 다시 맞추며, 그 위치에서 패스를 열지 않습니다. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. 고정점을 이동하면 한쪽 끝이 이동한 각 곡선은 양 끝을 기준으로 모양을 유지합니다. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 도구의 바로 가기 키를 누르고 있는 동안 그 도구가 선택되고, 키를 놓으면 이전 도구가 다시 선택됩니다. Shows the bounding box while you move the selection or draw a shape. 선택 영역을 이동하거나 모양을 그리는 동안 테두리 상자를 표시합니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..52fdc0fec0 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4570,6 +4570,7 @@ theme Appearance Vormgeving Data Recovery Gegevensherstel Default Language Standaardtaal Disable Auto Add/Delete Automatisch toevoegen/verwijderen uitschakelen + Delete Removes Anchor Points and Keeps Paths Joined Delete verwijdert ankerpunten en houdt paden verbonden Interpolate Control Points When Moving Anchors Richtingsgrepen interpoleren bij het verplaatsen van ankerpunten Display All Blacks Accurately Alle zwarttinten nauwkeurig weergeven Display All Blacks as Rich Black Alle zwarttinten weergeven als rijk zwart @@ -5130,6 +5131,7 @@ font-technology Variable Variabel A two-finger rotate gesture on a trackpad rotates the canvas view. Een draaigebaar met twee vingers op een trackpad draait de weergave van het canvas. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Als u een toets vasthoudt, wordt het gereedschap of de opdracht uit de kolom Houd in Sneltoetsen uitgevoerd; kort drukken voert de gewone sneltoets uit. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Hoeveel seconden u een toets moet vasthouden voordat de vasthoudsneltoets wordt uitgevoerd in plaats van de gewone sneltoets. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete verwijdert de geselecteerde ankerpunten en past de curve rond elk ervan opnieuw aan, in plaats van het pad daar te openen. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Als u ankerpunten verplaatst, behoudt elke curve met één verplaatst uiteinde zijn vorm ten opzichte van zijn uiteinden. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Als u de sneltoets van een gereedschap ingedrukt houdt, is dat gereedschap gekozen tot u loslaat, en daarna wordt het vorige gereedschap weer gekozen. Shows the bounding box while you move the selection or draw a shape. Toont het begrenzingskader terwijl u de selectie verplaatst of een vorm tekent. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..83b8ffc8ec 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4110,6 +4110,7 @@ theme Appearance Wygląd Data Recovery Odzyskiwanie danych Default Language Język domyślny Disable Auto Add/Delete Wyłącz automatyczne dodawanie/usuwanie + Delete Removes Anchor Points and Keeps Paths Joined Delete usuwa punkty kontrolne i zachowuje ścieżki połączone Interpolate Control Points When Moving Anchors Interpoluj uchwyty kierunkowe podczas przesuwania punktów kontrolnych Display All Blacks Accurately Wyświetlaj wszystkie czernie dokładnie Display All Blacks as Rich Black Wyświetlaj wszystkie czernie jako czerń głęboką @@ -4659,6 +4660,7 @@ font-technology Variable Zmienne A two-finger rotate gesture on a trackpad rotates the canvas view. Gest obrotu dwoma palcami na gładziku obraca widok obszaru roboczego. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Przytrzymanie klawisza uruchamia narzędzie lub polecenie z jego kolumny Przytrzymaj w Skrótach klawiaturowych; krótkie naciśnięcie uruchamia jego zwykły skrót. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Ile sekund trzeba przytrzymać klawisz, zanim zamiast zwykłego skrótu zostanie uruchomiony jego skrót przytrzymania. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete usuwa zaznaczone punkty kontrolne i ponownie dopasowuje krzywą wokół każdego z nich, zamiast otwierać tam ścieżkę. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Podczas przesuwania punktów kontrolnych każda krzywa z jednym przesuniętym końcem zachowuje kształt względem swoich końców. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Przytrzymanie skrótu narzędzia wybiera je do momentu puszczenia klawisza, a potem ponownie wybierane jest poprzednie narzędzie. Shows the bounding box while you move the selection or draw a shape. Pokazuje obwiednię podczas przesuwania zaznaczenia lub rysowania kształtu. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..37c14a6755 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -853,6 +853,7 @@ antiAlias Sharp Nítido Direct Selection Tool Ferramenta Seleção Direta Direction Handles Alças de Direção Disable Auto Add/Delete Desativar Adicionar/Excluir Automático + Delete Removes Anchor Points and Keeps Paths Joined Delete Remove Pontos de Ancoragem e Mantém os Demarcadores Unidos Interpolate Control Points When Moving Anchors Interpolar Alças de Direção ao Mover Pontos de Ancoragem Disable Opacity Mask Desativar Máscara de Opacidade Discard Descartar @@ -2781,6 +2782,7 @@ digits Malayalam Malaiala A two-finger rotate gesture on a trackpad rotates the canvas view. Um gesto de rotação com dois dedos no trackpad gira a visualização da tela. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Manter uma tecla pressionada executa a ferramenta ou o comando da coluna Manter pressionado em Atalhos de Teclado; um toque rápido executa o atalho habitual. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Quantos segundos uma tecla precisa ficar pressionada até que seu atalho de pressionamento longo seja executado no lugar do atalho habitual. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete remove os pontos de ancoragem selecionados e reajusta a curva em torno de cada um, em vez de abrir o demarcador ali. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Ao mover pontos de ancoragem, cada curva com uma extremidade movida mantém sua forma em relação às extremidades. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Manter pressionado o atalho de uma ferramenta a escolhe até você soltar, e então a ferramenta anterior é escolhida de novo. Shows the bounding box while you move the selection or draw a shape. Mostra a caixa delimitadora enquanto você move a seleção ou desenha uma forma. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..8fbefb1157 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -924,6 +924,7 @@ font-technology Variable Вариативные Direct Selection Tool Инструмент «Прямое выделение» Direction Handles Маркеры направления Disable Auto Add/Delete Отключить авто-добавление/удаление + Delete Removes Anchor Points and Keeps Paths Joined Delete удаляет опорные точки и оставляет контуры соединёнными Interpolate Control Points When Moving Anchors Интерполировать маркеры направления при перемещении опорных точек Disable Opacity Mask Отключить непрозрачную маску Discard Отменить @@ -3357,6 +3358,7 @@ digits Malayalam Малаялам A two-finger rotate gesture on a trackpad rotates the canvas view. Жест поворота двумя пальцами на трекпаде поворачивает вид холста. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Удержание клавиши запускает инструмент или команду из её столбца «Удерживать» в «Сочетаниях клавиш»; короткое нажатие запускает её обычное сочетание. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Сколько секунд нужно удерживать клавишу, прежде чем вместо её обычного сочетания сработает сочетание удержания. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete удаляет выбранные опорные точки и заново подгоняет кривую вокруг каждой из них, вместо того чтобы размыкать контур в этом месте. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. При перемещении опорных точек каждая кривая с одним перемещённым концом сохраняет форму относительно своих концов. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Пока вы удерживаете клавишу инструмента, он остаётся выбранным, а после отпускания снова выбирается предыдущий инструмент. Shows the bounding box while you move the selection or draw a shape. Показывает ограничивающую рамку, пока вы перемещаете выделение или рисуете фигуру. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..3fa181a310 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -909,6 +909,7 @@ font-technology Variable Variabla Direct Selection Tool Direktmarkeringsverktyg Direction Handles Riktningshandtag Disable Auto Add/Delete Inaktivera Lägg till/radera automatiskt + Delete Removes Anchor Points and Keeps Paths Joined Delete tar bort ankarpunkter och håller banor sammanhängande Interpolate Control Points When Moving Anchors Interpolera riktningshandtag vid flyttning av ankarpunkter Disable Opacity Mask Inaktivera opacitetsmask Discard Släng @@ -3246,6 +3247,7 @@ digits Malayalam Malayalam A two-finger rotate gesture on a trackpad rotates the canvas view. En rotationsgest med två fingrar på en styrplatta roterar arbetsytans vy. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Om du håller ned en tangent körs verktyget eller kommandot i dess Håll-kolumn i Kortkommandon; ett kort tryck kör dess vanliga kortkommando. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Hur många sekunder en tangent måste hållas ned innan dess hållkortkommando körs i stället för dess vanliga kortkommando. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete tar bort de markerade ankarpunkterna och anpassar om kurvan runt var och en i stället för att öppna banan där. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. När du flyttar ankarpunkter behåller varje kurva med en flyttad ände sin form i förhållande till sina ändar. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. När du håller ned ett verktygs kortkommando är verktyget valt tills du släpper, och sedan väljs det föregående verktyget igen. Shows the bounding box while you move the selection or draw a shape. Visar avgränsningsramen medan du flyttar markeringen eller ritar en form. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..c0901678fc 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -905,6 +905,7 @@ font-technology Variable Değişken Direct Selection Tool Doğrudan Seçim Aracı Direction Handles Yön Kolları Disable Auto Add/Delete Otomatik Ekleme/Silmeyi Devre Dışı Bırak + Delete Removes Anchor Points and Keeps Paths Joined Delete Bağlantı Noktalarını Kaldırır ve Yolları Birleşik Tutar Interpolate Control Points When Moving Anchors Bağlantı Noktalarını Taşırken Yön Kollarını Enterpole Et Disable Opacity Mask Opaklık Maskesini Devre Dışı Bırak Discard At @@ -3091,6 +3092,7 @@ digits Malayalam Malayalam A two-finger rotate gesture on a trackpad rotates the canvas view. İzleme dörtgeninde iki parmakla döndürme hareketi tuvalin görünümünü döndürür. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Bir tuşu basılı tutmak, Klavye Kısayolları'ndaki Basılı tutun sütununda bulunan aracı veya komutu çalıştırır; kısa basış olağan kısayolunu çalıştırır. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Olağan kısayolu yerine basılı tutma kısayolunun çalışması için bir tuşun kaç saniye basılı tutulması gerektiği. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete, seçili bağlantı noktalarını kaldırır ve yolu orada açmak yerine her birinin çevresindeki eğriyi yeniden uydurur. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Bağlantı noktalarını taşıdığınızda, bir ucu taşınan her eğri uçlarına göre şeklini korur. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Bir aracın kısayol tuşunu basılı tutmak, tuşu bırakana kadar o aracı seçer, ardından önceki araç yeniden seçilir. Shows the bounding box while you move the selection or draw a shape. Seçimi taşırken veya bir şekil çizerken sınırlayıcı kutuyu gösterir. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..7e1f1e54e0 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -923,6 +923,7 @@ font-technology Variable Варіативні Direct Selection Tool Інструмент «Пряме виділення» Direction Handles Маркери напряму Disable Auto Add/Delete Вимкнути авто-додавання/видалення + Delete Removes Anchor Points and Keeps Paths Joined Delete вилучає опорні точки й залишає контури з’єднаними Interpolate Control Points When Moving Anchors Інтерполювати маркери напряму під час переміщення опорних точок Disable Opacity Mask Вимкнути маску непрозорості Discard Відкинути @@ -3367,6 +3368,7 @@ digits Malayalam Малаялам A two-finger rotate gesture on a trackpad rotates the canvas view. Жест обертання двома пальцями на трекпаді обертає вигляд полотна. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Утримання клавіші запускає інструмент або команду з її стовпця «Утримувати» в «Поєднаннях клавіш»; коротке натискання запускає її звичайне поєднання. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Скільки секунд потрібно утримувати клавішу, перш ніж замість її звичайного поєднання спрацює поєднання утримання. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete вилучає вибрані опорні точки й заново припасовує криву навколо кожної з них, замість розмикати контур у цьому місці. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Коли ви переміщуєте опорні точки, кожна крива з одним переміщеним кінцем зберігає форму відносно своїх кінців. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Поки ви утримуєте клавішу інструмента, його вибрано, а після відпускання знову вибирається попередній інструмент. Shows the bounding box while you move the selection or draw a shape. Показує обмежувальну рамку, поки ви переміщуєте виділення або малюєте фігуру. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..7c812a2a78 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1088,6 +1088,7 @@ font-technology Variable Biến thiên Direction Handles Tay nắm hướng Direction: Hướng: Disable Auto Add/Delete Tắt tự động thêm/xóa + Delete Removes Anchor Points and Keeps Paths Joined Delete xóa điểm neo và giữ các đường dẫn liền mạch Interpolate Control Points When Moving Anchors Nội suy tay nắm hướng khi di chuyển điểm neo Disable Opacity Mask Tắt mặt nạ độ mờ Discard Loại bỏ @@ -3687,6 +3688,7 @@ mark-style Japanese Kiểu Nhật A two-finger rotate gesture on a trackpad rotates the canvas view. Cử chỉ xoay bằng hai ngón trên bàn di chuột sẽ xoay khung nhìn của khung vẽ. Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. Giữ một phím sẽ chạy công cụ hoặc lệnh trong cột Giữ của Phím tắt; nhấn nhanh sẽ chạy phím tắt thông thường của phím đó. How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. Số giây phải giữ một phím trước khi phím tắt nhấn giữ của nó chạy thay cho phím tắt thông thường. + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete xóa các điểm neo đã chọn và khớp lại đường cong quanh từng điểm, thay vì mở đường dẫn tại đó. When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Khi bạn di chuyển điểm neo, mỗi đường cong có một đầu bị di chuyển sẽ giữ hình dạng so với các đầu của nó. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Giữ phím tắt của một công cụ sẽ chọn công cụ đó cho đến khi bạn thả ra, rồi công cụ trước đó được chọn lại. Shows the bounding box while you move the selection or draw a shape. Hiển thị hộp giới hạn khi bạn di chuyển vùng chọn hoặc vẽ một hình. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..b3ff343f92 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -869,6 +869,7 @@ antiAlias Sharp 锐利 Direct Selection Tool 直接选择工具 Direction Handles 方向手柄 Disable Auto Add/Delete 禁用自动添加/删除锚点 + Delete Removes Anchor Points and Keeps Paths Joined Delete 删除锚点并保持路径连接 Interpolate Control Points When Moving Anchors 移动锚点时插值方向手柄 Disable Opacity Mask 禁用不透明度蒙版 Discard 不存储 @@ -3216,6 +3217,7 @@ digits Malayalam 马拉雅拉姆数字 A two-finger rotate gesture on a trackpad rotates the canvas view. 在触控板上用双指旋转手势可旋转画布视图。 Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. 按住某个键会运行键盘快捷键中其按住列的工具或命令;快速按下则运行其常规快捷键。 How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. 按住某个键多少秒后,运行其按住快捷键而不是常规快捷键。 + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete 会删除所选锚点并重新拟合每个锚点周围的曲线,而不会在该处断开路径。 When you move anchor points, each curve with one moved end keeps its shape relative to its ends. 移动锚点时,只有一端移动的每条曲线都会保持其相对于两端的形状。 Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 按住工具的快捷键时选择该工具,松开后重新选择之前的工具。 Shows the bounding box while you move the selection or draw a shape. 移动所选对象或绘制形状时显示定界框。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..4550077abf 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -891,6 +891,7 @@ font-technology Variable 可變 Direct Selection Tool 直接選取工具 Direction Handles 控制把手 Disable Auto Add/Delete 停用自動增加/刪除 + Delete Removes Anchor Points and Keeps Paths Joined Delete 刪除錨點並保持路徑連接 Interpolate Control Points When Moving Anchors 移動錨點時內插控制把手 Disable Opacity Mask 停用不透明度遮色片 Discard 捨棄 @@ -4665,6 +4666,7 @@ digits Malayalam 馬來亞拉姆數字 A two-finger rotate gesture on a trackpad rotates the canvas view. 在觸控式軌跡板上以雙指旋轉手勢可旋轉畫布檢視。 Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut. 按住某個鍵會執行鍵盤快速鍵中其按住欄的工具或命令;快速按下則執行其一般快速鍵。 How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut. 按住某個鍵多少秒後,執行其按住快速鍵而不是一般快速鍵。 + Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there. Delete 會刪除所選錨點並重新擬合每個錨點周圍的曲線,而不會在該處斷開路徑。 When you move anchor points, each curve with one moved end keeps its shape relative to its ends. 移動錨點時,只有一端移動的每條曲線都會保持其相對於兩端的形狀。 Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 按住工具的快速鍵時選擇該工具,放開後重新選擇之前的工具。 Shows the bounding box while you move the selection or draw a shape. 移動選取範圍或繪製形狀時顯示邊框。 diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index ec8aea7063..a9b6e39e28 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -41,6 +41,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ("scrubNumericFields", "Dragging sideways on a numeric field's label changes the field's value."), ("trackpadRotateView", "A two-finger rotate gesture on a trackpad rotates the canvas view."), ("interpolateControlPoints", "When you move anchor points, each curve with one moved end keeps its shape relative to its ends."), + ("deleteKeepsPathsJoined", "Delete removes the selected anchor points and refits the curve around each one, instead of opening the path there."), ("holdToolKeys", "Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again."), ("holdShortcuts", "Holding a key runs the tool or command in its Hold column in Keyboard Shortcuts; a quick press runs its usual shortcut."), ("keyHoldDelay", "How long, in seconds, a key must be held before its hold shortcut runs instead of its usual shortcut."), diff --git a/crates/ui-egui/src/tests/removeanchors.rs b/crates/ui-egui/src/tests/removeanchors.rs index 44bf492ccb..77011602fb 100644 --- a/crates/ui-egui/src/tests/removeanchors.rs +++ b/crates/ui-egui/src/tests/removeanchors.rs @@ -311,3 +311,63 @@ fn open_anchor_delete_and_backspace_cut_the_clicked_anchor_then_clear() { assert!(pieces.iter().all(|piece| app.session.doc().unwrap().doc.node(*piece).is_none()), "the next {key:?} clears every piece"); } } + +/// With General › Delete Removes Anchor Points and Keeps Paths Joined on, both deletion keys +/// remove the clicked anchor of a closed path and leave it closed, in one undo step. +#[test] +fn with_the_preference_on_delete_and_backspace_keep_the_path_joined() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = app(); + app.run("prefs.set", json!({"key": "deleteKeepsPathsJoined", "value": true})).unwrap(); + let id = rect(&mut app); + app.select_tool("directSelection"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + for _ in 0..3 { + anchor_delete_frame(&mut app, &ctx, vec![]); + } + let at = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(Point::new(150.0, 50.0)); + let click = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + anchor_delete_frame(&mut app, &ctx, vec![Event::PointerMoved(at), click(true)]); + anchor_delete_frame(&mut app, &ctx, vec![click(false)]); + let st = app.session.doc().unwrap(); + assert_eq!(st.selection.anchors.get(&id).map(|a| a.len()), Some(1), "the real canvas click selected one anchor"); + let (before, undo) = (st.doc.clone(), st.history.undo.len()); + let press = |pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + anchor_delete_frame(&mut app, &ctx, vec![press(true)]); + anchor_delete_frame(&mut app, &ctx, vec![press(false)]); + let st = app.session.doc().unwrap(); + let path = st.doc.node(id).and_then(|n| n.path_data()).unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(path.subpaths[0].closed, "{key:?} keeps the path closed"); + assert_eq!(anchor_count(&app, id), 3); + assert_eq!(st.history.undo.len(), undo + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + } +} + +/// The Smart Pen does not take Delete, so with it chosen Delete follows the preference too. +#[test] +fn with_the_smart_pen_chosen_delete_follows_the_preference() { + for on in [false, true] { + let mut app = app(); + app.run("prefs.set", json!({"key": "deleteKeepsPathsJoined", "value": on})).unwrap(); + let id = rect(&mut app); + app.select_tool("smartPen"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + for _ in 0..3 { + anchor_delete_frame(&mut app, &ctx, vec![]); + } + app.run("select.anchors", json!({"id": id.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + let press = |pressed| Event::Key { key: egui::Key::Delete, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + anchor_delete_frame(&mut app, &ctx, vec![press(true)]); + anchor_delete_frame(&mut app, &ctx, vec![press(false)]); + assert_eq!(app.session.tool_id(), "smartPen"); + let st = app.session.doc().unwrap(); + let closed = st.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.subpaths.len() == 1 && p.subpaths[0].closed); + assert_eq!(closed, on, "with the preference {on}, Delete keeps the path closed: {on}"); + assert_eq!(anchor_count(&app, id), 3, "Delete removed one anchor"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..192472362d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3297,6 +3297,14 @@ are kept, and selecting an ancestor together with its descendants deletes that s Without `ids`, direct-selected anchors or selected ruler guides retain their usual Clear behavior. With `ids`, `guides: true` also deletes the selected ruler guides. The command rejects a `guides` value that is not a boolean. +Without `ids`, `keepJoined: true` removes the direct-selected anchors of each path that has no selected segment as +`path.removeAnchors` does (see Removing anchor points): the path stays joined, and the next anchor along is selected +(the one before at an open path's end). When no subpath that lost an anchor keeps two anchors, the path stays selected +whole, as `path.removeAnchors` leaves it, so the next Delete removes the whole path. Paths with a selected segment are +cut there, and their selected anchors stay in the path, as with `keepJoined: false`; and objects selected whole are deleted, in the +same undo step. `keepJoined` defaults to the `deleteKeepsPathsJoined` preference, and the value used joins the journal +entry; a saved step without it opens the paths, as it did when it was recorded. With `ids`, `keepJoined` has no +effect. A `keepJoined` value that is not a boolean is an error, with or without `ids`. `edit.copy` takes a compound-path member selected on its own (whole or in part, with Direct or Group Selection) as an ordinary path with the compound's paint, transparency, opacity mask and fill rule. The path is linked to the compound's @@ -6932,6 +6940,8 @@ The anchor after each removed one is then selected (the one before at an open pa `path.removeAnchors` again goes on along the path. `path.removeAnchor {id, subpath?, anchor}` (the Delete Anchor Point tool) removes one anchor the same way, and `path.deleteAnchors {}` (the Delete key) deletes the selected anchors with their segments, opening closed paths there. +With the `deleteKeepsPathsJoined` preference on, the Delete key (`edit.clear`) removes them as `path.removeAnchors` +does instead. ```json {"name":"run_command","arguments":{"command":"select.anchors","params":{"id":12,"anchors":[[0,1],[0,3]]}}} @@ -8332,6 +8342,12 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture as it did when it was recorded. Align and Distribute, and the anchors of type paths and area type frames (`text.reshapePath`, `text.reshapeArea`), move as before. Off, the handles of a moved anchor move with it and the other handles stay where they are. +- `deleteKeepsPathsJoined` (General › Delete Removes Anchor Points and Keeps Paths Joined, off by default): the + default of the `keepJoined` param of `edit.clear` (Delete, Backspace, Edit › Clear, and the Layers panel's Delete + button while no row is highlighted). On, Delete removes the direct-selected anchors of a path as `path.removeAnchors` does, refitting the curve + around each one, so a closed path stays closed and an open path stays in one piece; a path left with fewer than two + anchors is deleted. The next anchor along (the one before at an open path's end) is then selected, so the next + Delete goes on along the path. Off, Delete deletes the anchors with their segments and opens the path there. - `hideCornerWidgetAbove` (177° by default): corners wider than this show no Live Corners widget (a rectangle's right angles hide below 90°). - `transformPatternTiles` (off by default): the default of the transforms' `patterns` param (`object.transform`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..3c62f4050b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1483,6 +1483,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Direct Selection (#1278):** clicking a segment picks its connection, with hollow endpoint anchors and only that curve's direction handles. Delete leaves the neighboring curves and appearance intact, opens/splits contours in one undo step, and another Delete removes the remaining selected path. A whole-path drag and deliberate anchor selection keep their existing behavior; egui frames and native control/art checked, OS mouse/visual QA pending. Where anchors of overlapping objects coincide, a click or drag takes the anchor of the selected object, also when another object lies over it (#1509, fixes #1508). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Double-clicking type (including type nested inside a group) switches to the Type tool and puts the caret at the clicked character. With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group. VectorCraft's own preference General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`, off by default, fixes #7832): on, a Direct Selection drag, an arrow-key nudge, a Move or a Transform Again of selected anchors re-maps both handles of each segment with one moved end by the turn, uniform scale and move that take its old ends to its new ends, so a segment between corner anchors keeps its shape; a segment with both ends moved, or with its ends at the same place before or after the move, moves rigidly, and a smooth anchor keeps its handles in line. The commands take an `interpolate` param that defaults to the preference, and the value used joins the journal and Transform Again. Each drag or nudge is one undo step (`a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment`, `a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step`, `a_smooth_anchor_keeps_its_handles_in_line`). + VectorCraft's own preference General › Delete Removes Anchor Points and Keeps Paths Joined (`deleteKeepsPathsJoined`, off by default, part of #8326): on, Delete, Backspace and Edit › Clear remove the direct-selected anchors of each path as Remove Anchor Points does, refitting the curve around each one, so a closed path stays closed and an open path stays in one piece; the next anchor along (the one before at an open path's end) is selected, so the next Delete goes on along the path. Paths with a selected segment are still cut there, objects selected whole are still deleted, and a path left with fewer than two anchors goes, in one undo step. `edit.clear` takes a `keepJoined` param that defaults to the preference, and the value used joins the journal (`with_the_preference_on_delete_keeps_a_closed_path_closed_and_selects_the_next_anchor`, `several_paths_and_an_object_selected_whole_change_in_one_undo_step`, `with_the_preference_on_delete_and_backspace_keep_the_path_joined`). A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included). With Direct Selection, the Pen and the anchor tools, a group, compound path or clip group selected whole shows the anchors of its paths filled, as a path selected whole does; the direction handles still show only on a path that is selected itself. Public references: [Adjust anchor point, handle, and bounding box display size](https://web.archive.org/web/20251114182206/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/adjust-anchor-point-handle-and-bounding-box-display-size.html) and [Drawing basics](https://web.archive.org/web/20231130064834/https://helpx.adobe.com/illustrator/using/drawing-basics.html) (archived copies). When the Add Anchor Point tool, the Pen's Auto Add, the Smart Pen's Alt-click on a segment or Alt-click with the Scissors adds an anchor to a path with direct-selected anchors or segments (`path.insertAnchor`), the same points stay selected: the anchors and segments after the new anchor are numbered one higher, and a selected segment that the new anchor splits stays selected as its two halves. From f6bbab4b6e482185696e7ebfc5da2d6bb98fa0ba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 09:50:00 -0800 Subject: [PATCH 47/78] Swatch libraries: swatches a pattern brings skip the library's numbered names Add to Swatches now passes the clipboard importer the library's numbered swatch names that a picked pattern's swatches and patterns can come in under. A swatch or pattern that the import brings under a numbered name skips those names. This replaces the placeholder and copy swatches that held the names around the import. Paste and Use Library Item pass none and number swatches as before. - A tint or gradient of a numbered library name that the art brings, such as a tint "Ink 2" of "Ink", keeps that name. Before, in a document with another "Ink", the art's "Ink" came in as "Ink 2", the tint as "Ink 2 2", and adding the library's "Ink 2" next added it again. - A swatch of a numbered library name that the document does not use comes in under that name instead of as the document's identical copy ("Ink 2 2"). A copy of it that the import already brought is not reused for another library color of the same paint. - Of two library swatches with one numbered name, the first one in the library keeps the name when the other is a swatch the art brings or a pattern swatch. - A pattern that the art is painted with, and its swatch, skip the library's names when they come in numbered. A pattern of a numbered name whose library swatch places it otherwise keeps its name, and the swatch that comes with it gets another, so adding the library swatch next finds its name free. - A pattern swatch's numbered name skips the library's names, as a color's does, and a pattern swatch takes the library swatch's name when it is free, also when its pattern is reused. - A pattern pasted into the document is still found: when skipping the names would add the pattern again, or would reuse it only by merging colors, an import that does not skip them is used if it reuses the pasted pattern and gives none of those names to another swatch. - The paint and kind check on the colors a pattern's art brings or takes has a test: a library whose spot "Ink" shares its name with a global "Ink" in a color group, so that the art brings both. docs/mcp.md is rewrapped and says that a library color is numbered beside a document color of the same name and paint of another kind (process, global or spot), not only beside a process color. The params text of swatch.library.add, docs/mcp.md and the docs/target-app-parity.md line describe these rules and name their tests. --- crates/engine/src/cmd/clipboard/resources.rs | 134 +++- crates/engine/src/cmd/library.rs | 2 +- crates/engine/src/cmd/patternlib.rs | 102 ++- crates/engine/src/cmd/swatchlib.rs | 100 ++- crates/engine/src/tests/swatchlib.rs | 714 +++++++++++++++++++ docs/mcp.md | 37 +- docs/target-app-parity.md | 2 +- 7 files changed, 981 insertions(+), 110 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index c20c763495..6303eababe 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -14,13 +14,14 @@ //! the document's Spot Colors option says. Pasting back into the document the objects came from //! uses its resources as they are now. -use std::cell::OnceCell; +use std::cell::{Cell, OnceCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; use serde_json::{Map, Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::pattern::pattern_paint; use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX}; use vectorcraft_doc::{ Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, @@ -606,6 +607,9 @@ pub(crate) enum SwatchChoice { pub(crate) struct SwatchChoices { all: SwatchChoice, by_name: BTreeMap, + /// Names a swatch or pattern that comes in under a numbered name skips, each with the swatch + /// it is reserved for, which still comes in under it when the document does not use it. + reserved: Arc>, } impl SwatchChoices { @@ -617,16 +621,22 @@ impl SwatchChoices { }; match p.get("swatchConflict") { None | Some(Value::Null) => Ok(Self::default()), - Some(Value::Object(m)) => { - Ok(Self { all: SwatchChoice::Merge, by_name: m.iter().map(|(k, v)| Ok((k.clone(), one(v)?))).collect::>()? }) - } - Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }), + Some(Value::Object(m)) => Ok(Self { + all: SwatchChoice::Merge, + by_name: m.iter().map(|(k, v)| Ok((k.clone(), one(v)?))).collect::>()?, + reserved: Arc::default(), + }), + Some(v) => Ok(Self { all: one(v)?, ..Self::default() }), } } /// Add for every conflict: each pasted swatch whose name the document gives another color /// comes in renamed. pub(crate) fn add_all() -> Self { - Self { all: SwatchChoice::Add, by_name: BTreeMap::new() } + Self { all: SwatchChoice::Add, ..Self::default() } + } + /// These choices, with numbered names skipping the names of `names` ([`SwatchChoices::reserved`]). + pub(crate) fn reserving(self, names: &Arc>) -> Self { + Self { reserved: Arc::clone(names), ..self } } fn of(&self, name: &str) -> SwatchChoice { self.by_name.get(name).copied().unwrap_or(self.all) @@ -1145,6 +1155,9 @@ pub(crate) struct Imported { pub added_designs: BTreeSet, /// The global and spot colors that took the document's color (merged). merged_swatches: BTreeSet, + /// Whether a name [`SwatchChoices::reserving`] reserves changed the name a swatch or pattern + /// came in under. + pub reserved_named: bool, } impl Imported { @@ -1411,9 +1424,27 @@ impl Clipboard { let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() }; let same = |n: &str| !fresh && d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art)); let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| { - // Its swatch comes along under the same name. - let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n)); + // Its swatch comes along under the same name, which skips the reserved swatch + // names too, except its own name when that is reserved for a swatch of it. + let skipped = Cell::new(false); + let ours = |w: &Swatch| matches!(&w.paint, Paint::Pattern { pattern, .. } if *pattern == def.name); + let name = unique_name(&def.name, |n| { + let used = d.pattern(n).is_some() || d.swatch_name_taken(n); + let held = !used && choices.reserved.get(n).is_some_and(|w| n != def.name || !ours(w)); + skipped.set(skipped.get() || held); + used || held + }); + out.reserved_named |= skipped.get(); add_pattern(d, PatternDef { name: name.clone(), ..def.clone() }); + // The name is left to a swatch it is reserved for that places the pattern + // otherwise; the swatch the pattern comes with gets another. + let placed = choices.reserved.get(&name).is_some_and(|w| ours(w) && w.paint != pattern_paint(&def.name)); + if placed && d.swatches.last().is_some_and(|w| w.name == name) { + let other = unique_name(&name, |n| n == name || d.swatch_name_taken(n) || choices.reserved.contains_key(n)); + if let Some(w) = d.swatches.last_mut() { + w.name = other; + } + } Placed::added(&def.name, name) }); added_patterns.extend(p.new_name(&def.name)); @@ -1639,13 +1670,21 @@ impl Clipboard { let conflicts: BTreeSet = if same_doc { BTreeSet::new() } else { self.conflicts(d, used).into_iter().map(|(w, _)| w.name.clone()).collect() }; let bases: Vec<&Swatch> = self.swatches.iter().filter(|w| is_base(w) && used.has(Res::Swatch, &w.name)).collect(); + // The swatches this import brings, for the names reserved for them. + let brought: Vec<&Swatch> = if choices.reserved.is_empty() { + vec![] + } else { + self.swatches.iter().filter(|w| if is_base(w) { used.has(Res::Swatch, &w.name) } else { used.carries(w) }).collect() + }; for w in &bases { let p = if conflicts.contains(&w.name) && choices.of(&w.name) == SwatchChoice::Merge { out.merged += 1; out.merged_swatches.insert(w.name.clone()); Placed::Existing } else { - add_swatch(d, w, same_doc) + let (p, reserved_named) = add_swatch(d, w, w, same_doc, &choices.reserved, &brought, &out.relink); + out.reserved_named |= reserved_named; + p }; out.placed(Res::Swatch, &w.name, &p); } @@ -1660,7 +1699,8 @@ impl Clipboard { for def in self.swatches.iter().filter(|w| !is_base(w) && used.carries(w)) { let mut w = def.clone(); out.relink.paint(&mut w.paint); - let p = add_swatch(d, &w, same_doc); + let (p, reserved_named) = add_swatch(d, &w, def, same_doc, &choices.reserved, &brought, &out.relink); + out.reserved_named |= reserved_named; out.placed(Res::Swatch, &def.name, &p); } } @@ -1862,13 +1902,73 @@ pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[St clip.import_used(d, &used, &SwatchChoices::default(), false) } +/// Whether `name` ends in a space and a number, as a numbered copy's name ("Ink 2") does. +pub(crate) fn numbered_name(name: &str) -> bool { + name.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())) +} + /// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups -/// share one namespace). -fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed { +/// share one namespace) → where it went, and whether `reserved` changed its name. `source` is the +/// pasted swatch `w` stands for, before its links were relinked. A numbered name skips the names +/// in `reserved`. A numbered name in `reserved` ("Ink 2") that `d` does not use is kept for the +/// swatch it is reserved for: that swatch comes in under it, not as a numbered copy of it that `d` +/// has, and another swatch of that name gets a number. A numbered copy in `d` whose name is +/// reserved for another swatch that the import brings (`brought`), and that is that swatch with +/// its links as `relink` gives them, is left to it. +fn add_swatch( + d: &mut Document, + w: &Swatch, + source: &Swatch, + same_doc: bool, + reserved: &BTreeMap, + brought: &[&Swatch], + relink: &Relink, +) -> (Placed, bool) { let same = |n: &str| d.swatch(n).is_some_and(|t| *t == Swatch { name: n.to_string(), ..w.clone() }); - existing(&w.name, d.swatches_iter().map(|t| t.name.as_str()), same_doc, same).unwrap_or_else(|| { - let name = d.free_swatch_name(&w.name); - d.swatches.push(Swatch { name: name.clone(), ..w.clone() }); - Placed::added(&w.name, name) - }) + let kept = (!same_doc && numbered_name(&w.name) && !d.swatch_name_taken(&w.name)).then(|| reserved.get(&w.name)).flatten(); + let (owns, held) = (kept.is_some_and(|o| o == source), kept.is_some_and(|o| o != source)); + let is_owner = |t: &Swatch, o: &Swatch| { + let mut o = o.clone(); + relink.paint(&mut o.paint); + *t == o + }; + let theirs = |n: &str| { + n != w.name + && copy_of(&w.name, n) + && reserved.get(n).is_some_and(|o| o != source && brought.contains(&o) && d.swatch(n).is_some_and(|t| is_owner(t, o))) + }; + let names = || d.swatches_iter().map(|t| t.name.as_str()); + let excluded = Cell::new(false); + let found = existing( + &w.name, + names().filter(|n| { + let t = theirs(n); + excluded.set(excluded.get() || t); + !t + }), + same_doc, + same, + ); + let reused = |p: &Option| match p { + Some(Placed::Reused(n)) => Some(n.clone()), + _ => None, + }; + let passed_over = excluded.get() && reused(&found) != reused(&existing(&w.name, names(), same_doc, same)); + let over_copy = match found { + Some(p) if !owns => return (p, passed_over), + found => found.is_some(), + }; + let mut skipped = held; + let name = if d.swatch_name_taken(&w.name) || held { + let mut free = |n: &String| { + let taken = d.swatch_name_taken(n); + skipped |= !taken && reserved.contains_key(n); + !taken && !reserved.contains_key(n) + }; + (2..).map(|i| format!("{} {i}", w.name)).find(&mut free).unwrap_or_else(|| d.free_swatch_name(&w.name)) + } else { + w.name.clone() + }; + d.swatches.push(Swatch { name: name.clone(), ..w.clone() }); + (Placed::added(&w.name, name), over_copy || skipped || passed_over) } diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index ecbfa760bb..d04b038a7d 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -1356,7 +1356,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result { // or spot color the pattern's art links to keeps the library's color, as Add to Swatches brings // a library pattern's colors. let current = s.doc()?.doc.clone(); - let (choices, probe, imported) = super::patternlib::probe_import(¤t, &doc, &name, &clip)?; + let (choices, probe, imported) = super::patternlib::probe_import(¤t, &doc, &name, &clip, &Default::default())?; drop(current); let target = super::patternlib::imported_name(&imported, &name); let paint = vectorcraft_doc::pattern::pattern_paint(&target); diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 64342b21dd..53fc83b7c9 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -3,6 +3,7 @@ //! document holding its patterns, drawn here from plain shapes ([`PATTERN_LIBRARIES`]). //! `swatch.library.add` copies a pattern into the document with its swatch. +use std::collections::BTreeMap; use std::sync::{Arc, LazyLock}; use vectorcraft_color::{Color, Paint, Swatch, SwatchLibrary}; @@ -15,6 +16,10 @@ use super::clipboard::Clipboard; use super::clipboard::resources::{Imported, SwatchChoices}; use super::swatchlib::LibraryInfo; +/// Names that swatches and patterns coming in under a numbered name skip, each with the library +/// swatch it is reserved for ([`SwatchChoices::reserving`]). +pub(crate) type Reserved = Arc>; + /// A built-in pattern library: a stable id, its menu name and the function that adds its patterns. pub struct BuiltinPatternLibrary { pub id: &'static str, @@ -96,17 +101,18 @@ pub(crate) type SwatchNames = Vec<(String, String)>; /// A global or spot color whose name `d` gives another color comes in under a free name, as Add /// to Swatches adds such a color, so that the pattern keeps the library's colors. Those colors /// merge instead when that reuses a pattern of `d` that keeping them would add again -/// ([`probe_import`]). -pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, SwatchNames, SwatchNames)> { +/// ([`probe_import`]). A swatch that comes in under a numbered name skips the names in +/// `reserved`. +pub(crate) fn import(d: &mut Document, lib: &Document, name: &str, reserved: &Reserved) -> Result<(String, SwatchNames, SwatchNames)> { let gathered = gather(lib, name); let had: std::collections::HashSet = d.swatches_iter().map(|w| w.name.clone()).collect(); // Without a color to merge or a pattern to reuse, the document is not copied. let imported = if !gathered.swatches.is_empty() && has_candidate(d, lib, name) { - let (_, probed, imported) = probe_import(d, lib, name, &gathered)?; + let (_, probed, imported) = probe_import(d, lib, name, &gathered, reserved)?; *d = probed; imported } else { - gathered.import_into(d, &SwatchChoices::add_all(), false)? + gathered.import_into(d, &SwatchChoices::add_all().reserving(reserved), false)? }; let from = |to: &str| { let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str()); @@ -138,9 +144,11 @@ pub(crate) fn brought_names(lib: &Document, name: &str) -> std::collections::Has gather(lib, name).swatches.into_iter().map(|w| w.name).collect() } -/// The names in `lib` of pattern `name` and of the patterns its art brings. -pub(crate) fn brought_patterns(lib: &Document, name: &str) -> std::collections::HashSet { - gather(lib, name).patterns.into_iter().map(|p| p.name).collect() +/// The names in `lib` of the swatches and patterns that pattern `name` of `lib` brings, itself +/// included. +pub(crate) fn brought_resource_names(lib: &Document, name: &str) -> std::collections::HashSet { + let gathered = gather(lib, name); + gathered.swatches.into_iter().map(|w| w.name).chain(gathered.patterns.into_iter().map(|p| p.name)).collect() } /// The name pattern `name` has in the document `imported` went into. @@ -154,8 +162,8 @@ pub(crate) fn imported_name(imported: &Imported, name: &str) -> String { /// name than its own, as [`import`] lists them. A pattern whose art uses no other resource is /// compared as [`existing_pattern`] does. One whose art uses other resources, such as a pattern it /// is painted with, is imported into a copy of `d` as [`probe_import`] does, so that those -/// resources are compared too. -pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<(String, SwatchNames)> { +/// resources are compared too, with numbered names skipping `reserved`. +pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str, reserved: &Reserved) -> Option<(String, SwatchNames)> { let gathered = gather(lib, name); let only_pattern = gathered.patterns.len() == 1 && gathered.symbols.is_empty() @@ -173,7 +181,7 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio if !has_candidate(d, lib, name) { return None; } - let (_, _, imported) = probe_import(d, lib, name, &gathered).ok()?; + let (_, _, imported) = probe_import(d, lib, name, &gathered, reserved).ok()?; if imported.added != 0 { return None; } @@ -203,19 +211,73 @@ pub(crate) fn has_candidate(d: &Document, lib: &Document, name: &str) -> bool { /// another color comes in under a free name (Add). Those colors merge instead when Add would add /// the pattern again while merging reuses a pattern of `d`: such a pattern has its art linked to /// the document's own colors of those names, as pasting with Merge, or adding it from a library -/// before, leaves it. -pub(crate) fn probe_import(d: &Document, lib: &Document, name: &str, gathered: &Clipboard) -> Result<(SwatchChoices, Document, Imported)> { +/// before, leaves it. A swatch or pattern that comes in under a numbered name skips the names in +/// `reserved` ([`SwatchChoices::reserving`]). When that changed a name and the pattern would come +/// in again, or would be reused only by merging colors, an import that does not skip them is used +/// if it reuses a pattern of `d` (one pasted there), without merging in the second case, and uses +/// none of those names that `d` does not use, other than for the swatch a name is reserved for. +pub(crate) fn probe_import( + d: &Document, + lib: &Document, + name: &str, + gathered: &Clipboard, + reserved: &Reserved, +) -> Result<(SwatchChoices, Document, Imported)> { let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some(); - let mut with_add = d.clone(); - let added = gathered.import_into(&mut with_add, &SwatchChoices::add_all(), false)?; - if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) { - let mut merged = d.clone(); - let found = gathered.import_into(&mut merged, &SwatchChoices::default(), false)?; - if reused(&found) { - return Ok((SwatchChoices::default(), merged, found)); + let found = probe_skipping(d, lib, name, gathered, reserved)?; + // A reuse that merges colors gives the pattern the document's colors, so one that keeps the + // library's is tried too. + let merged = |i: &Imported| reused(i) && i.merged != 0; + if found.2.reserved_named && (!reused(&found.2) || merged(&found.2)) && has_candidate(d, lib, name) { + let pasted = probe_skipping(d, lib, name, gathered, &Reserved::default())?; + let better = !reused(&found.2) || !merged(&pasted.2); + if reused(&pasted.2) && better && !takes_reserved(d, &pasted.1, &pasted.2, gathered, reserved) { + return Ok(pasted); } } - Ok((SwatchChoices::add_all(), with_add, added)) + Ok(found) +} + +/// Whether `probed`, the import of `gathered` into a copy of `d` that `imported` describes, gives a +/// name in `reserved` that `d` does not use to a pattern, or to a swatch other than the one the name +/// is reserved for coming in under its own name. +fn takes_reserved(d: &Document, probed: &Document, imported: &Imported, gathered: &Clipboard, reserved: &Reserved) -> bool { + let had: std::collections::HashSet<&str> = + d.swatches_iter().map(|w| w.name.as_str()).chain(d.swatch_groups.iter().map(|g| g.name.as_str())).collect(); + let renamed_to = |n: &str| imported.renamed.iter().any(|r| r["kind"] == "swatch" && r["to"] == n && r["from"] != n); + let owner_only = |n: &str, owner: &Swatch| gathered.swatches.iter().filter(|w| w.name == n).all(|w| w == owner); + let swatch = probed + .swatches_iter() + .map(|w| w.name.as_str()) + .filter(|n| !had.contains(n)) + .any(|n| reserved.get(n).is_some_and(|owner| !owner_only(n, owner) || renamed_to(n))); + let patterns: std::collections::HashSet<&str> = d.patterns.iter().map(|p| p.name.as_str()).collect(); + swatch || probed.patterns.iter().any(|p| !patterns.contains(p.name.as_str()) && reserved.contains_key(&p.name)) +} + +/// [`probe_import`] with numbered names skipping `reserved`. +fn probe_skipping( + d: &Document, + lib: &Document, + name: &str, + gathered: &Clipboard, + reserved: &Reserved, +) -> Result<(SwatchChoices, Document, Imported)> { + let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some(); + let (add, merge) = (SwatchChoices::add_all().reserving(reserved), SwatchChoices::default().reserving(reserved)); + let mut with_add = d.clone(); + let mut added = gathered.import_into(&mut with_add, &add, false)?; + if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) { + let mut merged = d.clone(); + let mut found = gathered.import_into(&mut merged, &merge, false)?; + // Whether a reservation changed a name counts for either import. + found.reserved_named |= added.reserved_named; + if reused(&found) { + return Ok((merge, merged, found)); + } + added.reserved_named |= found.reserved_named; + } + Ok((add, with_add, added)) } /// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 341a26a4b1..1176bc586c 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -17,6 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches}; use vectorcraft_doc::pattern::pattern_paint; +use super::clipboard::resources::numbered_name; use super::fileio::{create_dir, extension, read_file, read_file_head, write_file, write_new_file}; use super::menucmds::squash; use super::package::free_name; @@ -49,7 +50,7 @@ pub fn specs() -> Vec { "Add to Swatches", ["Window", "Swatch Libraries"], None, - "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}", + "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it; a swatch of a numbered library name that the art brings, such as a tint \"Ink 2\", keeps that name when the document does not use it, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}", has_doc, add ), @@ -1023,55 +1024,27 @@ fn free_copy_in(taken: &mut HashSet, base: &str, reserved: impl Fn(&str) name } -/// [`patternlib::import`] of pattern `pattern` of `src` into `d`, keeping the library's numbered -/// swatch names (the keys of `names`, such as "Ink 2") that `d` does not use for the library's own -/// swatches of those names, so that a color the art brings under a numbered name does not take one -/// of them. While the import runs, a placeholder swatch holds each such name the art does not -/// bring, and a copy of the library's color holds each one the art brings, which the art then -/// takes. The placeholders are removed before it returns, and so is a copy the art did not take; -/// a copy the art took is listed with the colors the import brought. Names of the patterns the -/// import brings are not held. -fn import_holding( - d: &mut vectorcraft_doc::Document, - src: &vectorcraft_doc::Document, - pattern: &str, - names: &HashMap<&str, &Swatch>, -) -> Result<(String, patternlib::SwatchNames, patternlib::SwatchNames)> { - let numbered = |n: &str| n.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())); - let taken = taken_names(d); - let mut free: Vec<&str> = names.keys().copied().filter(|n| numbered(n) && !taken.contains(*n)).collect(); - free.sort_unstable(); - let (mut held, mut copies): (Vec, Vec) = (vec![], vec![]); - if !free.is_empty() { - let brings = patternlib::brought_names(src, pattern); - let patterns = patternlib::brought_patterns(src, pattern); - for n in free.into_iter().filter(|n| !patterns.contains(*n)) { - if !brings.contains(n) { - held.push(Swatch { name: n.to_string(), paint: Paint::None, global: false, spot: false }); - } else if let Some(w) = names.get(n).filter(|w| w.paint.color().is_some() && linked_names(&w.paint).is_empty()) { - copies.push((*w).clone()); - } +/// The name of the document's swatch for library pattern swatch `w`, whose pattern came in as +/// `target`, the import having made swatch `made` for it (removed again). A numbered name skips +/// the names of the library's other swatches (`lib_by_name`), as for a color; so does a swatch +/// named after its pattern when the pattern's name is one of them. The swatch takes the library +/// swatch's name when it is free and the library has no other swatch of that name, and leaves a +/// numbered name the library gives an earlier swatch to that one. +fn pattern_swatch_name(w: &Swatch, target: &str, made: Option, taken: &mut HashSet, lib_by_name: &HashMap<&str, &Swatch>) -> String { + let reserved = |n: &str| lib_by_name.contains_key(n); + let owns = lib_by_name.get(w.name.as_str()).is_some_and(|o| *o == w); + let named_after = matches!(&w.paint, Paint::Pattern { pattern, .. } if *pattern == w.name); + match made { + _ if named_after && owns && !taken.contains(&w.name) => w.name.clone(), + _ if !owns && numbered_name(&w.name) && !taken.contains(&w.name) => { + let mut held = taken.clone(); + held.insert(w.name.clone()); + free_copy_in(&mut held, &w.name, reserved) } + Some(made) if named_after => made, + None if named_after && (target == w.name || !reserved(target)) => free_copy_in(taken, target, reserved), + _ => free_copy_in(taken, &w.name, reserved), } - let start = d.swatches.len(); - d.swatches.extend(held.iter().chain(&copies).cloned()); - let imported = patternlib::import(d, src, pattern); - let used = |n: &str| { - imported - .as_ref() - .is_ok_and(|(_, colors, took)| !colors.iter().any(|(from, _)| from == n) && !took.iter().any(|(from, to)| from == n && to != n)) - }; - let used: HashSet = copies.iter().map(|w| w.name.clone()).filter(|n| used(n)).collect(); - let mut i = 0; - d.swatches.retain(|w| { - i += 1; - let ours = held.iter().chain(&copies).any(|h| h.name == w.name && h.paint == w.paint); - !(i > start && ours && !used.contains(&w.name)) - }); - let (target, mut colors, mut took) = imported?; - took.retain(|(from, _)| !used.contains(from)); - colors.extend(copies.into_iter().map(|w| w.name).filter(|n| used.contains(n)).map(|n| (n.clone(), n))); - Ok((target, colors, took)) } /// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors @@ -1195,6 +1168,25 @@ fn add(s: &mut Session, p: &Value) -> Result { for w in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| &g.swatches)) { lib_by_name.entry(w.name.as_str()).or_insert(w); } + // A swatch a pattern's art brings under a numbered name skips the library's numbered names, + // which a later add looks up as those swatches'. Only the names a picked pattern's swatches and + // patterns can come in under, their own or one numbered after them, are needed. + let mut brings_names: HashSet = HashSet::new(); + if let Some(src) = patterns.as_ref().filter(|_| lib_by_name.keys().any(|n| numbered_name(n))) { + let picked_patterns: BTreeSet<&str> = picked + .iter() + .filter_map(|(_, w)| match &w.paint { + Paint::Pattern { pattern, .. } => Some(pattern.as_str()), + _ => None, + }) + .collect(); + for pattern in picked_patterns { + brings_names.extend(patternlib::brought_resource_names(src, pattern)); + } + } + let can_take = |n: &str| brings_names.contains(n) || n.rsplit_once(' ').is_some_and(|(base, _)| brings_names.contains(base)); + let lib_names: patternlib::Reserved = + Arc::new(lib_by_name.iter().filter(|(n, _)| numbered_name(n) && can_take(n)).map(|(n, w)| (n.to_string(), (*w).clone())).collect()); let group_names: HashSet<&str> = d.swatch_groups.iter().map(|g| g.name.as_str()).collect(); // A color whose name the document gives another color, or a color group, is the numbered copy // of it that an earlier add or a pattern's art brought in, when that copy is the same color. A @@ -1226,7 +1218,7 @@ fn add(s: &mut Session, p: &Value) -> Result { if let Some(src) = &patterns { for (_, w) in &picked { let Paint::Pattern { pattern, .. } = &w.paint else { continue }; - present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern)); + present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern, &lib_names)); } } // Whether the document's swatch `x` of the name of library swatch `w` is `w` with its colors @@ -1431,7 +1423,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let mut learned = vec![]; if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) { let mut probe = d.clone(); - let (_, colors, took) = import_holding(&mut probe, src, pattern, &lib_by_name)?; + let (_, colors, took) = patternlib::import(&mut probe, src, pattern, &lib_names)?; for (from, to) in colors_of(&probe, &colors, &took) { if let std::collections::hash_map::Entry::Vacant(e) = links.entry(from.clone()) { e.insert(to); @@ -1441,7 +1433,7 @@ fn add(s: &mut Session, p: &Value) -> Result { } let settled = settle(d, &mut pending, &links); let had = taken_names(d); - let (target, colors, took) = import_holding(d, src, pattern, &lib_by_name)?; + let (target, colors, took) = patternlib::import(d, src, pattern, &lib_names)?; // Those colors are the ones the library's tints of them link to, unless the // document already has one for them. A name the copy gave that the import // into the document did not give is replaced, and the tints linked to it are @@ -1476,11 +1468,7 @@ fn add(s: &mut Session, p: &Value) -> Result { d.swatches.retain(|x| x.name != *made); } taken = taken_names(d); - let name = match made { - Some(made) if w.name == *pattern => made, - None if w.name == *pattern => d.free_swatch_name(&target), - _ => free_in(&mut taken, &w.name), - }; + let name = pattern_swatch_name(w, &target, made, &mut taken, &lib_by_name); taken.insert(name.clone()); // The library swatch's placement of its pattern is kept. let paint = match &w.paint { diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 5d94eecc69..6e9c8ea8a8 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -1313,6 +1313,720 @@ fn a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone() { assert!(doc(&s).swatch("Ink 2").is_none(), "{r}"); } +/// A tint or gradient of a numbered library name ("Ink 2") that a library pattern's art brings +/// keeps that name when the document gives the art's color "Ink" another color, so adding the +/// library's "Ink 2" next finds it. +#[test] +fn a_numbered_tint_or_gradient_a_pattern_brings_keeps_the_librarys_name() { + let tint = json!({"name": "Ink 2", "swatch": "Ink", "tint": 50}); + let gradient = json!({"name": "Ink 2", "gradient": {"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]}}); + for numbered in [tint, gradient] { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", numbered.clone()); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{numbered}: {first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{numbered}: {first} {r}"); + } +} + +/// A library pattern swatch that comes in under a numbered name skips the names the library gives +/// its other swatches: adding the library's "Dots 2" next adds it under its own name. +#[test] +fn a_library_pattern_swatchs_copy_skips_the_librarys_other_names() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + s.edit("Dots", |d, _| { + let paint = vectorcraft_doc::pattern::pattern_paint("Squares"); + d.swatches.push(vectorcraft_color::Swatch { name: "Dots".into(), paint, global: false, spot: false }); + Ok(()) + }) + .unwrap(); + run(&mut s, "swatch.new", json!({"name": "Dots 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Dots", "color": "#ff0000"})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Dots"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Dots 2"]})); + assert_eq!(r["added"], json!(["Dots 2"]), "{first} {r}"); + assert!(is_global(&s, "Dots 2", "#00ff00"), "{first} {r}"); +} + +/// A library whose spot color "Ink" shares its name with a global color in a color group: a +/// pattern's art painted with both brings both. A library tint of the spot color, picked before +/// the pattern, links to the document's copy of the spot color the art takes, not to the global +/// color the art brings under a numbered name, whether that color has another paint or the same. +#[test] +fn a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings() { + for global_color in ["#ff0000", "#0000ff"] { + a_library_tint_skips_a_namesake_the_pattern_brings(global_color); + } +} + +fn a_library_tint_skips_a_namesake_the_pattern_brings(global_color: &str) { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + run(&mut s, "swatch.new", json!({"name": "Crimson", "color": global_color, "global": true})); + let blue = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 6}))["id"].clone(); + let red = run(&mut s, "shape.rectangle", json!({"x": 3, "y": 0, "width": 3, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [blue]})); + run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [red]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [blue, red]})); + run(&mut s, "select.set", json!({"ids": [blue, red]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + // The global color becomes "Ink" in a color group, and the pattern's art links to it by that name. + s.edit("Rename", |d, _| { + let i = d.swatches.iter().position(|w| w.name == "Crimson").unwrap(); + let mut global = d.swatches.remove(i); + global.name = "Ink".into(); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Reds".into(), swatches: vec![global] }); + let def = d.pattern_mut("Tiles").unwrap(); + for node in &mut def.art { + for it in &mut std::sync::Arc::make_mut(node).appearance.items { + it.paint_mut().map_links(&mut |_, link, _| { + let red = link.as_deref() == Some("Crimson"); + if red { + *link = Some("Ink".into()); + } + red + }); + } + } + Ok(()) + }) + .unwrap(); + let art_links: Vec> = doc(&s).pattern("Tiles").unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect(); + assert_eq!(art_links, [Some("Ink".to_string()), Some("Ink".to_string())]); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "spot": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Tiles"]})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{global_color}: {r}"); + assert!(doc(&s).swatch("Ink 2").is_some_and(|w| w.spot), "{global_color}: {r}"); +} + +/// A color of a numbered library name ("Ink 2") that a pattern's art brings comes in under that +/// name when the document does not use it, not as the document's copy of it ("Ink 2 2"), so +/// adding the library's "Ink 2" next finds it. +#[test] +fn a_numbered_color_a_pattern_brings_keeps_its_name_beside_a_copy_of_it() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink 2 2", "color": "#00ff00", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 2", "#00ff00"), "{first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{first} {r}"); +} + +/// A pattern that a library pattern's art is painted with ("Inner"), brought under a numbered name +/// because the document has a swatch "Inner", skips the name "Inner 2" that the library gives a +/// color, as does the swatch that comes with it. +#[test] +fn a_nested_pattern_a_library_pattern_brings_skips_the_librarys_names() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Inner", "ids": [tile]})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.new", json!({"name": "Inner 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Inner", "color": "#ff0000"})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]})); + assert!(doc(&s).pattern("Inner 2").is_none(), "{first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]})); + assert_eq!(r["added"], json!(["Inner 2"]), "{first} {r}"); + assert!(is_global(&s, "Inner 2", "#00ff00"), "{first} {r}"); +} + +/// A library pattern that was pasted into the document with its art linked to the document's +/// copy of a numbered library color ("Ink 2 2" for "Ink 2") is found when it is added from the +/// library, not added again. +#[test] +fn a_pasted_pattern_linked_to_a_copy_of_a_numbered_color_is_found() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink 2 2", "color": "#00ff00", "global": true})); + run(&mut s, "edit.paste", json!({})); + assert!(doc(&s).swatch("Ink 2").is_none(), "the paste reused the copy"); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!(doc(&s).patterns.len(), 1, "{r}"); +} + +/// A library pattern swatch named after its pattern ("Tiles 2") that comes in with a new pattern +/// under a numbered name ("Tiles 2 2"), because the document has another pattern of that name +/// without a swatch, takes the library swatch's name. +#[test] +fn a_new_patterns_swatch_takes_the_library_swatchs_free_name() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [own]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]})); + assert!(doc(&s).pattern("Tiles 2").is_some(), "the document keeps its pattern"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(r["added"], json!(["Tiles 2"]), "{r}"); + let paint = doc(&s).swatch("Tiles 2").map(|w| w.paint.clone()); + assert!(matches!(&paint, Some(Paint::Pattern { pattern, .. }) if pattern != "Tiles 2"), "{r} {paint:?}"); + // Added again after its swatch is deleted, it reuses the pattern under the same swatch name. + run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]})); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(again["added"], json!(["Tiles 2"]), "{r} {again}"); + assert_eq!(doc(&s).swatch("Tiles 2").map(|w| w.paint.clone()), paint, "{r} {again}"); +} + +/// A library whose process color "Ink 2" shares its name with a global color in a color group +/// that a pattern's art is painted with: the global color comes in numbered, so adding the +/// library's "Ink 2" next adds the process color under its own name. +#[test] +fn a_numbered_name_is_kept_for_the_library_swatch_it_names() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00"})); + run(&mut s, "swatch.new", json!({"name": "Crimson", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + group_as(&mut s, "Crimson", "Ink 2"); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{first} {r}"); + assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{first} {r}"); +} + +/// A library pattern pasted with Add, whose color came in as "Ink 2" and was then deleted without +/// unlinking the art, is not reused through a new "Ink 2" when the library gives that name another +/// color: adding that color next adds it under its own name. This holds too when the document has +/// a pattern "Ink 2" without a swatch. +#[test] +fn a_pasted_pattern_is_not_reused_by_taking_a_librarys_name() { + for bare in [false, true] { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + if bare { + let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [own]})); + run(&mut s, "object.pattern.make", json!({"name": "Ink 2", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"]})); + assert!(doc(&s).pattern("Ink 2").is_some(), "the document keeps its pattern"); + } + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "add"})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the blue color as Ink 2 ({bare})"); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{bare} {first} {r}"); + assert!(is_global(&s, "Ink 2", "#00ff00"), "{bare} {first} {r}"); + } +} + +/// A library pattern painted with two global colors of one paint, "Ink" and "Ink 2", added beside +/// the document's red "Ink" brings them as "Ink 3" and "Ink 2". Adding the pattern again finds it, +/// in either order of the library's colors: "Ink" does not reuse the library's "Ink 2". +#[test] +fn a_color_a_pattern_brings_again_does_not_reuse_a_copy_the_library_names() { + for ink_first in [true, false] { + let mut s = session(); + let names = if ink_first { ["Ink", "Ink 2"] } else { ["Ink 2", "Ink"] }; + for n in names { + run(&mut s, "swatch.new", json!({"name": n, "color": "#0000ff", "global": true})); + } + let mut dots = vec![]; + for (i, n) in ["Ink", "Ink 2"].iter().enumerate() { + let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + dots.push(dot); + } + run(&mut s, "select.set", json!({"ids": dots})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 2", "#0000ff") && is_global(&s, "Ink 3", "#0000ff"), "{ink_first} {first}"); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!(doc(&s).patterns.len(), 1, "{ink_first} {first} {r}"); + } +} + +/// A library pattern painted with a blue global "Ink" and a green global "Ink 2", added to a +/// document with a red "Ink" and a blue global "Ink 2": the art's "Ink" is the document's "Ink 2", +/// since that is not the library's "Ink 2", and no third copy comes in. +#[test] +fn a_color_a_pattern_brings_reuses_a_copy_that_is_not_the_librarys_namesake() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let mut dots = vec![]; + for (i, n) in ["Ink", "Ink 2"].iter().enumerate() { + let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + dots.push(dot); + } + run(&mut s, "select.set", json!({"ids": dots})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(doc(&s).swatch("Ink 3").is_none(), "{r}"); + assert!(is_global(&s, "Ink 2", "#0000ff") && is_global(&s, "Ink 2 2", "#00ff00"), "{r}"); +} + +/// A library pattern painted with a blue global "Ink", pasted beside the document's red "Ink" and +/// then left without its color "Ink 2" (deleted without unlinking), is not reused by bringing the +/// library's "Ink" back as "Ink 2" when the library has its own blue "Ink 2": the pattern links to +/// another copy. +#[test] +fn a_pasted_pattern_is_not_reused_by_giving_a_librarys_name_to_another_color() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "add"})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the blue color as Ink 2"); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let pattern = match doc(&s).swatch("Tiles").map(|w| w.paint.clone()) { + Some(Paint::Pattern { pattern, .. }) => pattern, + p => panic!("{r} {p:?}"), + }; + let links: Vec> = doc(&s).pattern(&pattern).unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect(); + assert!(!links.contains(&Some("Ink 2".to_string())), "{r} {links:?}"); +} + +/// A library pattern painted with two alike gradients of its blue global "Ink", "Ramp 2" and then +/// "Ramp", added beside the document's red "Ink": the color comes in as "Ink 2", and both +/// gradients come in under their own names, linked to it, instead of "Ramp" taking "Ramp 2". +#[test] +fn alike_gradients_a_pattern_brings_keep_their_names_when_their_color_is_renamed() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let ramp = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]}); + run(&mut s, "swatch.new", json!({"name": "Ramp 2", "gradient": ramp})); + run(&mut s, "swatch.new", json!({"name": "Ramp", "gradient": ramp})); + let mut dots = vec![]; + for (i, n) in ["Ramp 2", "Ramp"].iter().enumerate() { + let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + dots.push(dot); + } + run(&mut s, "select.set", json!({"ids": dots})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}"); + assert!(doc(&s).swatch("Ramp").is_some() && doc(&s).swatch("Ramp 2").is_some(), "{r}"); +} + +/// A library pattern painted with blue globals "Ink" and "Ink 2", pasted twice beside the +/// document's red "Ink" and blue "Ink 2" (with Add, both fills on "Ink 2"; with Merge, one on the +/// red "Ink"), is found again as the copy that keeps its blue, not the merged one. +#[test] +fn a_pattern_pasted_with_add_and_with_merge_is_found_as_the_copy_with_its_colors() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let mut dots = vec![]; + for (i, n) in ["Ink", "Ink 2"].iter().enumerate() { + let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + dots.push(dot); + } + run(&mut s, "select.set", json!({"ids": dots})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "add"})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + let links = |s: &Session, p: &str| -> Vec> { + doc(s).pattern(p).unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect() + }; + let kept: Vec = doc(&s).patterns.iter().map(|p| p.name.clone()).filter(|p| !links(&s, p).contains(&Some("Ink".into()))).collect(); + assert_eq!((doc(&s).patterns.len(), kept.len()), (2, 1), "one pasted copy keeps the blue color"); + for w in doc(&s).swatches.clone().iter().filter(|w| matches!(w.paint, Paint::Pattern { .. })) { + run(&mut s, "swatch.delete", json!({"names": [w.name]})); + } + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let pattern = match doc(&s).swatch("Tiles").map(|w| w.paint.clone()) { + Some(Paint::Pattern { pattern, .. }) => pattern, + p => panic!("{r} {p:?}"), + }; + assert_eq!((doc(&s).patterns.len(), &pattern), (2, &kept[0]), "{r}"); +} + +/// A library whose color "Tiles 2" shares its name with a pattern swatch in a color group: adding +/// the group gives the pattern swatch another name, so adding the color next adds it under its own. +#[test] +fn a_grouped_pattern_swatch_leaves_a_numbered_name_to_the_librarys_color() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Dots", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.new", json!({"name": "Tiles 2", "color": "#00ff00", "global": true})); + s.edit("Group", |d, _| { + let i = d.swatches.iter().position(|w| w.name == "Dots").unwrap(); + let mut w = d.swatches.remove(i); + w.name = "Tiles 2".into(); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] }); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(r["added"], json!(["Tiles 2"]), "{first} {r}"); + assert!(is_global(&s, "Tiles 2", "#00ff00"), "{first} {r}"); +} + +/// As above, with the grouped swatch named after its pattern "Tiles 2", which the document holds +/// (pasted there) without a swatch: the reused pattern's swatch leaves the name to the color too. +#[test] +fn a_grouped_swatch_of_a_reused_pattern_leaves_a_numbered_name_to_the_librarys_color() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles 2", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "swatch.new", json!({"name": "Bright", "color": "#00ff00", "global": true})); + s.edit("Group", |d, _| { + let i = d.swatches.iter().position(|w| w.name == "Tiles 2").unwrap(); + let w = d.swatches.remove(i); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] }); + d.swatches.iter_mut().find(|w| w.name == "Bright").unwrap().name = "Tiles 2".into(); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "edit.paste", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]})); + assert!(doc(&s).pattern("Tiles 2").is_some() && doc(&s).swatch("Tiles 2").is_none(), "the pasted pattern stays"); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(r["added"], json!(["Tiles 2"]), "{first} {r}"); + assert!(is_global(&s, "Tiles 2", "#00ff00"), "{first} {r}"); +} + +/// A pattern "Inner 2" that a library pattern's art is painted with, whose library swatch "Inner 2" +/// places it with an offset, leaves the name to that swatch: adding the library's "Inner 2" next +/// adds it under its own name with its placement. Picked first, "Inner 2" comes in under its own +/// name too. +#[test] +fn a_nested_pattern_leaves_its_name_to_a_library_swatch_that_places_it_otherwise() { + for outer_first in [true, false] { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + let offset = Paint::Pattern { pattern: "Inner 2".into(), xf: kurbo::Affine::translate((3.0, 0.0)) }; + let lib_paint = offset.clone(); + s.edit("Offset", move |d, _| { + d.swatches.iter_mut().find(|w| w.name == "Inner 2").unwrap().paint = lib_paint; + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let picks = if outer_first { ["Outer", "Inner 2"] } else { ["Inner 2", "Outer"] }; + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": [picks[0]]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": [picks[1]]})); + assert_eq!(doc(&s).swatch("Inner 2").map(|w| w.paint.clone()), Some(offset), "{outer_first} {first} {r}"); + assert_eq!(doc(&s).patterns.len(), 2, "{outer_first} {first} {r}"); + } +} + +/// A library with a pattern swatch "Tiles 2" and, in a color group, a swatch of the same name that +/// places the same pattern with an offset: adding the group first leaves the name to the +/// ungrouped swatch, which comes in under it next. +#[test] +fn a_grouped_namesake_of_a_pattern_swatch_leaves_it_the_name() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + s.edit("Group", |d, _| { + let offset = Paint::Pattern { pattern: "Tiles 2".into(), xf: kurbo::Affine::translate((3.0, 0.0)) }; + let w = vectorcraft_color::Swatch { name: "Tiles 2".into(), paint: offset, global: false, spot: false }; + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] }); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + let paint = doc(&s).swatch("Tiles 2").map(|w| w.paint.clone()); + assert!(matches!(&paint, Some(Paint::Pattern { xf, .. }) if *xf == kurbo::Affine::IDENTITY), "{first} {r} {paint:?}"); +} + +/// A pattern "Inner 2" that a library pattern's art is painted with, whose swatch the library +/// deleted before giving the name "Inner 2" to a color, comes in under another name, so adding +/// that color next adds it under its own name. +#[test] +fn a_nested_pattern_does_not_take_a_name_the_library_gives_a_color() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Inner 2"]})); + assert!(doc(&s).pattern("Inner 2").is_some(), "the library keeps the pattern"); + run(&mut s, "swatch.new", json!({"name": "Inner 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]})); + assert_eq!(r["added"], json!(["Inner 2"]), "{first} {r}"); + assert!(is_global(&s, "Inner 2", "#00ff00"), "{first} {r}"); +} + +/// A library pattern pasted into the document, whose global color "Ink 2" (in a color group) was +/// then deleted without unlinking the art, is not reused by bringing that color back as "Ink 2" +/// when the library also has a process color "Ink 2": adding that color next adds it under its +/// own name. +#[test] +fn a_pasted_pattern_is_not_reused_by_bringing_back_a_librarys_name() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00"})); + run(&mut s, "swatch.new", json!({"name": "Crimson", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + group_as(&mut s, "Crimson", "Ink 2"); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "edit.paste", json!({})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the global color as Ink 2"); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{first} {r}"); + assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{first} {r}"); +} + +/// Move swatch `name` of `s`'s document into a new color group under the name `to`, and link the +/// art of every pattern linked to it to `to`. +fn group_as(s: &mut Session, name: &str, to: &str) { + s.edit("Group", |d, _| { + let i = d.swatches.iter().position(|w| w.name == name).unwrap(); + let mut w = d.swatches.remove(i); + w.name = to.into(); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] }); + for def in &mut d.patterns { + for node in &mut def.art { + for it in &mut std::sync::Arc::make_mut(node).appearance.items { + it.paint_mut().map_links(&mut |_, link, _| { + let hit = link.as_deref() == Some(name); + if hit { + *link = Some(to.into()); + } + hit + }); + } + } + } + Ok(()) + }) + .unwrap(); +} + +/// The swatch paint `p` links to. +fn tint_link(p: &Paint) -> Option { + match p { + Paint::Solid { swatch, .. } => swatch.clone(), + _ => None, + } +} + +/// A library pattern "Tiles" added beside the document's own swatch "Tiles" does not take the name +/// "Tiles 2" that the library gives a color, neither for the pattern nor for its swatch; nor does +/// its swatch when the document holds the pattern as "Tiles 2" (pasted there) without a swatch. +#[test] +fn a_pattern_swatch_named_after_its_numbered_pattern_skips_the_librarys_names() { + for pasted in [false, true] { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.new", json!({"name": "Tiles 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Tiles", "color": "#ff0000"})); + if pasted { + run(&mut s, "edit.paste", json!({})); + assert!(doc(&s).pattern("Tiles 2").is_some(), "the paste numbers the pattern"); + let names: Vec = doc(&s) + .swatches_iter() + .filter(|w| matches!(&w.paint, Paint::Pattern { pattern, .. } if pattern == "Tiles 2")) + .map(|w| w.name.clone()) + .collect(); + run(&mut s, "swatch.delete", json!({"names": names})); + } + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(r["added"], json!(["Tiles 2"]), "{pasted}: {first} {r}"); + assert!(is_global(&s, "Tiles 2", "#00ff00"), "{pasted}: {first} {r}"); + } +} + /// A library tint added without its global color to a document that has no swatch of the color's /// name brings the color along under its own name. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 1253778638..5fe5561778 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5833,21 +5833,28 @@ From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and art, into the document as a pattern swatch under the library swatch's name and in its color group. A global or spot color the pattern's art links to keeps the library's color: when the document gives its name another color, it comes -in under a numbered name ("Ink 2") and the pattern links to that. That numbered name skips the names the library -gives its other swatches. A library color whose name the document gives -another color is the document's numbered copy of the same color when it has one, so adding the pattern and its color -again adds nothing. A pattern the document already holds with its art linked to the document's own color of that name -is used as it is. A library tint or gradient whose global or spot color comes in under a numbered name, or is in the -document as such a numbered copy, links to that copy, whether the color is picked before or after it, was added -earlier or came with a pattern's art. A library global color is not the document's process color of the same name and -paint: it comes in numbered. A global or spot color that a library tint or gradient links to and the document lacks -comes in with the tint or gradient, under a numbered name when the document gives its name another swatch. The -document's tint or gradient of the library one's name is that swatch when it links to the copy of the color that the -art of a pattern picked with it takes; a numbered copy that the library also names stands for that library swatch -otherwise. When the document's tint or gradient links to a color the document no longer has (deleted without -unlinking), that color comes back under its own name. A pattern is found again when it was pasted with Add or Merge for all of its colors; one pasted -with Merge for some colors and Add for others is added again as a copy. `added` lists the colors the pattern's art, a -tint or a gradient brings too. A document with +in under a numbered name ("Ink 2") and the pattern links to that. That numbered name, and the numbered names of a +pattern swatch and of a pattern the art is painted with, skip the names the library gives its other swatches. A swatch +of a numbered library name, such as a color or tint "Ink 2", that the pattern's art brings keeps that name when the +document does not use it. Of two library swatches with one numbered name, the first one in the library keeps the name +when the other is a swatch the pattern's art brings or a pattern swatch. A pattern the art is painted with keeps a +numbered name; when the library's swatch of that name places the pattern otherwise, the swatch that comes with the +pattern gets another name. A library color whose name the document gives another +color is the document's numbered copy +of the same color when it has one, so adding the pattern and its color again adds nothing. A pattern the document +already holds with its art linked to the document's own color of that name, or to a numbered copy of the color as +pasting leaves it, is used as it is, unless using it would give another swatch a name the library uses. A library +tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered +copy, links to that copy, whether the color is picked before or after it, was added earlier or came with a pattern's +art. A library global or spot color is not the document's color of the same name and paint when that color is of +another kind (process, global or spot): it comes in numbered. A global or spot color that a library tint or gradient +links to and the document lacks comes in with the tint or gradient, under a numbered name when the document gives its +name another swatch. The document's tint or gradient of the library one's name is that swatch when it links to the +copy of the color that the art of a pattern picked with it takes; a numbered copy that the library also names stands +for that library swatch otherwise. When the document's tint or gradient links to a color the document no longer has +(deleted without unlinking), that color comes back under its own name. A pattern is found again when it was pasted +with Add or Merge for all of its colors; one pasted with Merge for some colors and Add for others is added again as a +copy. `added` lists the colors the pattern's art, a tint or a gradient brings too. A document with no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with "`` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` (`.epsf`) files as well as the library files. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 16b1fc7ab3..748b978927 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2247,7 +2247,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). - Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name that skips the names of the library's other swatches, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `a_color_a_pattern_brings_skips_the_librarys_numbered_names`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name that skips the names of the library's other swatches, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it, or when the document deleted it without unlinking the tint. A swatch of a numbered library name that a pattern's art brings, a tint or gradient included, keeps that name, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `a_library_tint_whose_color_the_document_deleted_brings_the_color_back`, `a_color_a_pattern_brings_skips_the_librarys_numbered_names`, `a_pattern_bringing_a_color_and_its_numbered_namesake_keeps_the_librarys_name`, `a_numbered_tint_or_gradient_a_pattern_brings_keeps_the_librarys_name`, `a_numbered_color_a_pattern_brings_keeps_its_name_beside_a_copy_of_it`, `a_numbered_library_pattern_keeps_its_name`, `a_library_pattern_swatchs_copy_skips_the_librarys_other_names`, `a_pattern_swatch_named_after_its_numbered_pattern_skips_the_librarys_names`, `a_nested_pattern_a_library_pattern_brings_skips_the_librarys_names`, `a_nested_pattern_does_not_take_a_name_the_library_gives_a_color`, `a_nested_pattern_leaves_its_name_to_a_library_swatch_that_places_it_otherwise`, `a_pasted_pattern_linked_to_a_copy_of_a_numbered_color_is_found`, `a_new_patterns_swatch_takes_the_library_swatchs_free_name`, `a_numbered_name_is_kept_for_the_library_swatch_it_names`, `a_color_a_pattern_brings_again_does_not_reuse_a_copy_the_library_names`, `a_color_a_pattern_brings_reuses_a_copy_that_is_not_the_librarys_namesake`, `alike_gradients_a_pattern_brings_keep_their_names_when_their_color_is_renamed`, `a_pasted_pattern_is_not_reused_by_giving_a_librarys_name_to_another_color`, `a_pattern_pasted_with_add_and_with_merge_is_found_as_the_copy_with_its_colors`, `a_grouped_pattern_swatch_leaves_a_numbered_name_to_the_librarys_color`, `a_grouped_swatch_of_a_reused_pattern_leaves_a_numbered_name_to_the_librarys_color`, `a_grouped_namesake_of_a_pattern_swatch_leaves_it_the_name`, `a_pasted_pattern_is_not_reused_by_taking_a_librarys_name`, `a_pasted_pattern_is_not_reused_by_bringing_back_a_librarys_name`, `a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings`, `a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). From cfbb1cdf67c30d6d1fb52ea40fac66cbd01d9573 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:40:07 -0800 Subject: [PATCH 48/78] Selection: pie widgets hide while Cmd lends Direct Selection With a shape tool active and Direct Selection chosen last, Cmd held lends Direct Selection, which does not press a live ellipse's pie widgets. The canvas now draws them for a shape tool only while that tool is the one shown, as the bounding box already does. --- crates/ui-egui/src/canvas/overlays.rs | 8 ++++---- crates/ui-egui/src/canvas/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 02318ad688..b79206662d 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -276,10 +276,10 @@ pub(super) fn selection_overlay( p.add(Shape::convex_polygon(diamond, Color32::WHITE, Stroke::new(1.0, color))); } } - // Pie widgets (Selection tool, with View › Show Bounding Box and Show Shape Widgets, on live - // ellipses): each joined by a line to the outline's point at its angle. They stay while one is - // dragged. - if (tool == "selection" || (shape_tool && !drawing)) && app.ui.view.bounding_box && shape_widgets { + // Pie widgets (Selection tool and the shape tools while no other tool is lent, with View › Show + // Bounding Box and Show Shape Widgets, on live ellipses): each joined by a line to the outline's + // point at its angle. They stay while one is dragged. + if (tool == "selection" || (shape_tool && own && !drawing)) && app.ui.view.bounding_box && shape_widgets { for w in vectorcraft_tools::pie::PieWidget::of(&st.doc, &st.selection, xf.zoom) { let (on, c, r, color) = (xf.to_screen(w.on), xf.to_screen(w.at), vectorcraft_tools::pie::RADIUS_PX, c32(st.doc.layer_color(w.id))); p.line_segment([on, c], Stroke::new(1.0, color)); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 21dd33b715..963bbc3289 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -7264,6 +7264,27 @@ fn the_widgets_follow_the_pointer_in_the_frame_it_moves() { assert!(away + 2 <= plain, "away from it, hidden in the same frame: {away} of {plain}"); } +/// With a shape tool, Cmd held lends the selection tool chosen last; when that is Direct +/// Selection, which does not press them, a selected live ellipse's pie widgets hide while the key +/// is down. +#[test] +fn pie_widgets_hide_while_cmd_lends_direct_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 100})).unwrap(); + app.session.execute("object.setLiveShape", &json!({"pieStart": 0, "pieEnd": 90})).unwrap(); + app.select_tool("directSelection"); + app.select_tool("ellipse"); + let ctx = egui::Context::default(); + let r = vectorcraft_tools::pie::RADIUS_PX; + let widgets = |app: &mut VectorcraftApp, modifiers: egui::Modifiers| { + drawn_with(app, &ctx, modifiers, None).iter().filter(|s| matches!(s, Shape::Circle(c) if c.radius == r && c.fill == Color32::WHITE)).count() + }; + assert_eq!(widgets(&mut app, egui::Modifiers::NONE), 2, "the Ellipse tool shows them"); + assert_eq!(widgets(&mut app, egui::Modifiers::COMMAND), 0, "hidden while Cmd lends Direct Selection"); + assert_eq!(widgets(&mut app, egui::Modifiers::NONE), 2, "back when the key is let go"); +} + /// A selected Objects on Path group shows its Rotate All widget with the Selection and Objects on /// Path tools. #[test] From 2592dde6c8076582520249b4f0993f5b3e092e33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:07:03 -0800 Subject: [PATCH 49/78] Selection: a Cmd double-click after a tool switch is the new tool's The double-click or triple-click that follows a lent Cmd-click went to the tool lent to that press even after another tool or document was chosen. The lent tool is now kept with the document and the tool it was lent from, and a follow-up in another document or after a tool switch goes to the active tool. --- crates/engine/src/lib.rs | 6 ++++-- crates/engine/src/tests/draw2.rs | 26 ++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 12 +++++++++--- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index bbcba38fff..244da31e5d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -110,8 +110,10 @@ pub struct Session { /// Selection tool. None until one is chosen. pub(crate) last_part_selection_tool: Option<&'static str>, /// The selection tool Cmd lent the last press, which also takes the double-click or - /// triple-click that follows it. None when the press was not lent. - pub(crate) press_lent: Option<&'static str>, + /// triple-click that follows it, with the uid of the document and the id of the tool it was + /// lent from: a follow-up in another document or after a tool switch is not lent. None when + /// the press was not lent. + pub(crate) press_lent: Option<(Option, &'static str, &'static str)>, /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with /// the document state, active tool and keys it was found for. None when it was last asked diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index c497fed246..740b99f42a 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4775,6 +4775,32 @@ fn a_cmd_double_click_goes_to_the_tool_the_clicks_went_to() { assert!(s.doc().unwrap().isolation.is_some()); } +#[test] +fn a_cmd_double_click_after_a_tool_switch_goes_to_the_new_tool() { + // With the Selection tool, a Cmd-click on type goes to Direct Selection, and so does the + // Cmd double-click after it, which edits the type. Once another tool is chosen, the + // double-click is that tool's: Group Selection's does not edit the type. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let id = NodeId(s.execute("text.create", &json!({"x": 100, "y": 200, "size": 48, "text": "Type"})).unwrap()["id"].as_u64().unwrap()); + let c = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().center(); + let clicks = |s: &mut Session, then: Option<&str>| { + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, c.x, c.y).with_mods(cmd), v).unwrap(); + } + if let Some(tool) = then { + s.select_tool(tool, v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, c.x, c.y).with_mods(cmd), v).unwrap() + }; + assert_eq!(clicks(&mut s, None), [UiRequest::SwitchTool("type".into())], "Direct Selection's double-click edits the type"); + assert_eq!(clicks(&mut s, Some("groupSelection")), [], "Group Selection's double-click does not"); + assert_eq!(s.tool_id(), "groupSelection"); +} + #[test] fn a_cmd_press_on_a_selected_object_keeps_select_behind() { // Over a selected object, a Cmd-click with the Selection tool selects the object behind it; diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 736b99617a..b023ca1f7f 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -406,11 +406,17 @@ impl Session { if (ev.kind != PointerKind::Down && !follow_up) || !ev.mods.cmd || self.lender.is_some() { return Ok((*ev, vec![])); } - // A follow-up goes where the press before it went, whatever that press selected. - let id = if follow_up { self.press_lent } else { self.lent_tool_at(ev.pos, &ev.mods, view) }; + // A follow-up goes where the press before it went, whatever that press selected, while the + // document and the active tool are the ones that press found. + let at = (self.active().map(|d| d.uid), self.tool.id()); + let id = if follow_up { + self.press_lent.filter(|(doc, tool, _)| (*doc, *tool) == at).map(|(.., id)| id) + } else { + self.lent_tool_at(ev.pos, &ev.mods, view) + }; let Some(id) = id else { return Ok((*ev, vec![])) }; if !follow_up { - self.press_lent = Some(id); + self.press_lent = Some((at.0, at.1, id)); } // Typing in progress is kept as its own step first: the lent tool's drag previews from the // document its interaction started from, which would drop the typing (#1881). When it From 185d79b8205757f1492b16c225715e3fb276cb91 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:13:43 -0800 Subject: [PATCH 50/78] Swatch libraries: only a numbered pattern swatch keeps its free library name A library pattern swatch named after its pattern took the library swatch's name whenever the document did not use it, even when its pattern came in under another name. For an unnumbered name this changed the existing result: adding a library "Tiles" to a document that has another pattern "Tiles" without a swatch named the swatch "Tiles" while it paints "Tiles 2". Only a numbered name, which the reservation keeps for the library swatch, is now kept that way; an unnumbered one is named after the pattern that comes in, as before. docs/mcp.md is rewrapped where two lines were broken mid-paragraph, and the progress line puts the Use Library Item sentence before the rules that apply only to Add to Swatches. --- crates/engine/src/cmd/swatchlib.rs | 4 ++-- crates/engine/src/tests/swatchlib.rs | 29 +++++++++++++++++++++++++++- docs/mcp.md | 5 ++--- docs/target-app-parity.md | 2 +- 4 files changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 1176bc586c..7e7ba4b6b6 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -1028,14 +1028,14 @@ fn free_copy_in(taken: &mut HashSet, base: &str, reserved: impl Fn(&str) /// `target`, the import having made swatch `made` for it (removed again). A numbered name skips /// the names of the library's other swatches (`lib_by_name`), as for a color; so does a swatch /// named after its pattern when the pattern's name is one of them. The swatch takes the library -/// swatch's name when it is free and the library has no other swatch of that name, and leaves a +/// swatch's numbered name when it is free and the library has no other swatch of that name, and leaves a /// numbered name the library gives an earlier swatch to that one. fn pattern_swatch_name(w: &Swatch, target: &str, made: Option, taken: &mut HashSet, lib_by_name: &HashMap<&str, &Swatch>) -> String { let reserved = |n: &str| lib_by_name.contains_key(n); let owns = lib_by_name.get(w.name.as_str()).is_some_and(|o| *o == w); let named_after = matches!(&w.paint, Paint::Pattern { pattern, .. } if *pattern == w.name); match made { - _ if named_after && owns && !taken.contains(&w.name) => w.name.clone(), + _ if named_after && owns && numbered_name(&w.name) && !taken.contains(&w.name) => w.name.clone(), _ if !owns && numbered_name(&w.name) && !taken.contains(&w.name) => { let mut held = taken.clone(); held.insert(w.name.clone()); diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 6e9c8ea8a8..38c1f6175b 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -1536,6 +1536,32 @@ fn a_new_patterns_swatch_takes_the_library_swatchs_free_name() { assert_eq!(doc(&s).swatch("Tiles 2").map(|w| w.paint.clone()), paint, "{r} {again}"); } +/// A library pattern swatch "Tiles" named after its pattern, added to a document that has another +/// pattern "Tiles" without a swatch, is named after the pattern that comes in ("Tiles 2"), as +/// before numbered names were reserved: only a numbered name is kept for the library swatch. +#[test] +fn a_new_patterns_swatch_of_an_unnumbered_name_is_named_after_its_pattern() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [own]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let added = r["added"].as_array().and_then(|a| a.first()).and_then(|n| n.as_str()).unwrap_or_default().to_string(); + assert_ne!(added, "Tiles", "{r}"); + let paint = doc(&s).swatch(&added).map(|w| w.paint.clone()); + assert!(matches!(&paint, Some(Paint::Pattern { pattern, .. }) if *pattern == added), "{r} {paint:?}"); + assert!(doc(&s).swatch("Tiles").is_none(), "{r}"); +} + /// A library whose process color "Ink 2" shares its name with a global color in a color group /// that a pattern's art is painted with: the global color comes in numbered, so adding the /// library's "Ink 2" next adds the process color under its own name. @@ -1692,7 +1718,8 @@ fn a_pasted_pattern_is_not_reused_by_giving_a_librarys_name_to_another_color() { run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); - let pattern = match doc(&s).swatch("Tiles").map(|w| w.paint.clone()) { + let added = r["added"].as_array().and_then(|a| a.first()).and_then(|n| n.as_str()).unwrap_or_default().to_string(); + let pattern = match doc(&s).swatch(&added).map(|w| w.paint.clone()) { Some(Paint::Pattern { pattern, .. }) => pattern, p => panic!("{r} {p:?}"), }; diff --git a/docs/mcp.md b/docs/mcp.md index 5fe5561778..9061adf0e0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5839,9 +5839,8 @@ of a numbered library name, such as a color or tint "Ink 2", that the pattern's document does not use it. Of two library swatches with one numbered name, the first one in the library keeps the name when the other is a swatch the pattern's art brings or a pattern swatch. A pattern the art is painted with keeps a numbered name; when the library's swatch of that name places the pattern otherwise, the swatch that comes with the -pattern gets another name. A library color whose name the document gives another -color is the document's numbered copy -of the same color when it has one, so adding the pattern and its color again adds nothing. A pattern the document +pattern gets another name. A library color whose name the document gives another color is the document's numbered +copy of the same color when it has one, so adding the pattern and its color again adds nothing. A pattern the document already holds with its art linked to the document's own color of that name, or to a numbered copy of the color as pasting leaves it, is used as it is, unless using it would give another swatch a name the library uses. A library tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 748b978927..ffe4f33315 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2247,7 +2247,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). - Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name that skips the names of the library's other swatches, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it, or when the document deleted it without unlinking the tint. A swatch of a numbered library name that a pattern's art brings, a tint or gradient included, keeps that name, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `a_library_tint_whose_color_the_document_deleted_brings_the_color_back`, `a_color_a_pattern_brings_skips_the_librarys_numbered_names`, `a_pattern_bringing_a_color_and_its_numbered_namesake_keeps_the_librarys_name`, `a_numbered_tint_or_gradient_a_pattern_brings_keeps_the_librarys_name`, `a_numbered_color_a_pattern_brings_keeps_its_name_beside_a_copy_of_it`, `a_numbered_library_pattern_keeps_its_name`, `a_library_pattern_swatchs_copy_skips_the_librarys_other_names`, `a_pattern_swatch_named_after_its_numbered_pattern_skips_the_librarys_names`, `a_nested_pattern_a_library_pattern_brings_skips_the_librarys_names`, `a_nested_pattern_does_not_take_a_name_the_library_gives_a_color`, `a_nested_pattern_leaves_its_name_to_a_library_swatch_that_places_it_otherwise`, `a_pasted_pattern_linked_to_a_copy_of_a_numbered_color_is_found`, `a_new_patterns_swatch_takes_the_library_swatchs_free_name`, `a_numbered_name_is_kept_for_the_library_swatch_it_names`, `a_color_a_pattern_brings_again_does_not_reuse_a_copy_the_library_names`, `a_color_a_pattern_brings_reuses_a_copy_that_is_not_the_librarys_namesake`, `alike_gradients_a_pattern_brings_keep_their_names_when_their_color_is_renamed`, `a_pasted_pattern_is_not_reused_by_giving_a_librarys_name_to_another_color`, `a_pattern_pasted_with_add_and_with_merge_is_found_as_the_copy_with_its_colors`, `a_grouped_pattern_swatch_leaves_a_numbered_name_to_the_librarys_color`, `a_grouped_swatch_of_a_reused_pattern_leaves_a_numbered_name_to_the_librarys_color`, `a_grouped_namesake_of_a_pattern_swatch_leaves_it_the_name`, `a_pasted_pattern_is_not_reused_by_taking_a_librarys_name`, `a_pasted_pattern_is_not_reused_by_bringing_back_a_librarys_name`, `a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings`, `a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name that skips the names of the library's other swatches, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it, or when the document deleted it without unlinking the tint. Use Library Item adds a library pattern's colors the same way. With Add to Swatches, a swatch of a numbered library name that a pattern's art brings, a tint or gradient included, keeps that name, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `a_library_tint_whose_color_the_document_deleted_brings_the_color_back`, `a_color_a_pattern_brings_skips_the_librarys_numbered_names`, `a_pattern_bringing_a_color_and_its_numbered_namesake_keeps_the_librarys_name`, `a_numbered_tint_or_gradient_a_pattern_brings_keeps_the_librarys_name`, `a_numbered_color_a_pattern_brings_keeps_its_name_beside_a_copy_of_it`, `a_numbered_library_pattern_keeps_its_name`, `a_library_pattern_swatchs_copy_skips_the_librarys_other_names`, `a_pattern_swatch_named_after_its_numbered_pattern_skips_the_librarys_names`, `a_nested_pattern_a_library_pattern_brings_skips_the_librarys_names`, `a_nested_pattern_does_not_take_a_name_the_library_gives_a_color`, `a_nested_pattern_leaves_its_name_to_a_library_swatch_that_places_it_otherwise`, `a_pasted_pattern_linked_to_a_copy_of_a_numbered_color_is_found`, `a_new_patterns_swatch_takes_the_library_swatchs_free_name`, `a_new_patterns_swatch_of_an_unnumbered_name_is_named_after_its_pattern`, `a_numbered_name_is_kept_for_the_library_swatch_it_names`, `a_color_a_pattern_brings_again_does_not_reuse_a_copy_the_library_names`, `a_color_a_pattern_brings_reuses_a_copy_that_is_not_the_librarys_namesake`, `alike_gradients_a_pattern_brings_keep_their_names_when_their_color_is_renamed`, `a_pasted_pattern_is_not_reused_by_giving_a_librarys_name_to_another_color`, `a_pattern_pasted_with_add_and_with_merge_is_found_as_the_copy_with_its_colors`, `a_grouped_pattern_swatch_leaves_a_numbered_name_to_the_librarys_color`, `a_grouped_swatch_of_a_reused_pattern_leaves_a_numbered_name_to_the_librarys_color`, `a_grouped_namesake_of_a_pattern_swatch_leaves_it_the_name`, `a_pasted_pattern_is_not_reused_by_taking_a_librarys_name`, `a_pasted_pattern_is_not_reused_by_bringing_back_a_librarys_name`, `a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings`, `a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). From ece910a3b72fb8477f7c74756459941fa7f9b2d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:45:24 -0800 Subject: [PATCH 51/78] Selection: a Cmd double-click after switching back is the active tool's A switch from the Selection tool to another tool and back kept the record of the selection tool Cmd lent the last press, so the Cmd double-click that followed still went to Direct Selection. The record is now cleared whenever the active tool changes and whenever the tool starts afresh (a switch to another document or another view of it). --- crates/engine/src/lib.rs | 4 ++-- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/draw2.rs | 30 ++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 3 +++ 4 files changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 244da31e5d..b213394c0c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -111,8 +111,8 @@ pub struct Session { pub(crate) last_part_selection_tool: Option<&'static str>, /// The selection tool Cmd lent the last press, which also takes the double-click or /// triple-click that follows it, with the uid of the document and the id of the tool it was - /// lent from: a follow-up in another document or after a tool switch is not lent. None when - /// the press was not lent. + /// lent from: a follow-up in another document, after a tool switch (also one back to the same + /// tool) or after the tool starts afresh is not lent. None when the press was not lent. pub(crate) press_lent: Option<(Option, &'static str, &'static str)>, /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 7930095b6e..e800a9c572 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -209,6 +209,7 @@ impl Session { return; } self.press_type_selection = None; + self.press_lent = None; let view = self.last_view; // The edit the tool computes on another thread and the input held for it belong to the // document being left. The switch goes on whatever they did, as for the deactivation. diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 740b99f42a..34254b3513 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4801,6 +4801,36 @@ fn a_cmd_double_click_after_a_tool_switch_goes_to_the_new_tool() { assert_eq!(s.tool_id(), "groupSelection"); } +#[test] +fn a_cmd_double_click_after_switching_away_and_back_goes_to_the_active_tool() { + // A Cmd-click with the Selection tool goes to Direct Selection. After a switch to another tool + // and back to the Selection tool, or a fresh start of the tool (another view of the document), + // the Cmd double-click is the Selection tool's: it isolates the group. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + for reset in [false, true] { + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap(); + } + if reset { + s.reset_tool(); + } else { + s.select_tool("rectangle", v).unwrap(); + s.select_tool("selection", v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 150.0, 150.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + assert!(s.doc().unwrap().isolation.is_some(), "the Selection tool's double-click isolates the group (reset: {reset})"); + s.execute("object.exitIsolation", &json!({})).unwrap(); + } +} + #[test] fn a_cmd_press_on_a_selected_object_keeps_select_behind() { // Over a selected object, a Cmd-click with the Selection tool selects the object behind it; diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index b023ca1f7f..761c9af469 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -198,6 +198,9 @@ impl Session { if self.tool.id() == id { return Ok(()); } + // A double-click or triple-click after the switch is the new tool's, also when the switch + // comes back to the tool a Cmd press was lent from. + self.press_lent = None; // Sampling type keeps its highlighted characters as the target, and a whole story that // Select All selected. Capture before the Type tool deactivates (which commits typing and // clears its editing state). From dd303e9df7658055b5b880c318472aab14677b1d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:15:16 -0800 Subject: [PATCH 52/78] Overprint: a white spot ink keeps overprinting with Discard White Overprint on Discard White Overprint knocked out every white fill, stroke and character that was set to overprint, including a white linked to a spot swatch such as an opaque white ink. A white linked to a solid spot swatch at a tint above 0% is an ink of its own, so it now keeps overprinting; only paper white knocks out, a 0% tint of a spot swatch included. The rule is in vectorcraft_doc::overprint (DiscardWhite, is_paper_white) and is used by PDF export, Overprint Preview, Separations Preview, printed separations, the fills and strokes of composite print with Overprints set to Simulate, and Print Ink Fixes' Remove White Overprint. Overprint Preview and Separations Preview also draw overprinting paper white characters knocking out while the option is on, as PDF export already wrote them. EPS export keeps every overprint, as before. --- crates/doc/src/overprint.rs | 97 ++++++++++++++++++- crates/engine/src/cmd/addons/color.rs | 2 +- .../src/cmd/addons/color/print_fixes.rs | 29 +++--- .../src/cmd/addons/color/print_fixes/tests.rs | 14 +++ crates/engine/src/cmd/fileio/pdf.rs | 2 +- crates/engine/src/tests/docsetup.rs | 7 ++ crates/pdf/src/export.rs | 3 + crates/pdf/src/export/exporter.rs | 1 + crates/pdf/src/export/nodes.rs | 28 ++++-- crates/pdf/src/print.rs | 6 +- crates/pdf/src/print/plates.rs | 16 +-- crates/pdf/src/tests/layers.rs | 22 +++++ crates/pdf/src/tests/print.rs | 43 +++++++- crates/render/src/proof.rs | 51 ++++++++-- crates/render/src/tests/memory.rs | 85 +++++++++++++++- docs/mcp.md | 13 ++- docs/target-app-parity.md | 3 +- 17 files changed, 369 insertions(+), 53 deletions(-) diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index 58f6b5abc2..c5631a9a44 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -2,6 +2,7 @@ //! over the inks below instead of knocking them out ([`crate::FillLayer::overprint`]). //! Edit → Edit Colors → Overprint Black sets it on black fills and strokes ([`OverprintBlack`]). +use std::collections::HashSet; use std::sync::Arc; use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; @@ -151,14 +152,14 @@ impl Node { /// mode of their own keep it), copying only the nodes on the way to them: on screen and on a /// printed plate this approximates their inks printing over the inks below. Darken keeps the /// stronger ink of each plate (and each additive channel), so a colour overprinting itself stays -/// that colour, where Multiply would darken it. With `discard_white` -/// (Document Setup → Discard White Overprint) white fills and strokes knock out instead. -pub fn darken_overprints(a: &mut Arc, discard_white: bool) { +/// that colour, where Multiply would darken it. Fills and strokes that `discard_white` knocks out +/// (Document Setup → Discard White Overprint) are left as they are. +pub fn darken_overprints(a: &mut Arc, discard_white: &DiscardWhite) { if !a.has_overprint() { return; } let n = Arc::make_mut(a); - let darkens = |overprint: bool, blend: BlendMode, paint: &Paint| overprint && blend == BlendMode::Normal && !(discard_white && is_white(paint)); + let darkens = |overprint: bool, blend: BlendMode, paint: &Paint| overprint && blend == BlendMode::Normal && !discard_white.knocks_out(paint); for it in &mut n.appearance.items { match it { crate::AppearanceItem::Fill(l) if darkens(l.overprint, l.blend, &l.paint) => l.blend = BlendMode::Darken, @@ -182,7 +183,45 @@ pub fn is_white(p: &Paint) -> bool { } } +/// Whether `p` is paper white: white ([`is_white`]) and not a tint above 0% of one of the spot +/// swatches `spots` ([`Document::spot_ink_names`]). The white of a spot swatch (an opaque white +/// ink, for example) is an ink of its own; a 0% tint puts no ink down. +pub fn is_paper_white(p: &Paint, spots: &HashSet) -> bool { + is_white(p) && !matches!(p, Paint::Solid { swatch: Some(name), tint, .. } if *tint > 0.0 && spots.contains(name)) +} + +/// Document Setup → Discard White Overprint as it applies to paints: off, or on with the names of +/// the document's spot swatches. Paper white ([`is_paper_white`]) knocks out where it overprints; +/// a white spot ink keeps overprinting. Clones share the names. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct DiscardWhite(Option>>); + +impl DiscardWhite { + /// The setting of document `doc`. + pub fn of(doc: &Document) -> Self { + Self::printing(doc, |_| true) + } + + /// The setting of document `doc` when only the spot inks for which `spot` is true print as + /// spot inks: a white of another one (converted to process inks) is paper white. + pub fn printing(doc: &Document, spot: impl Fn(&str) -> bool) -> Self { + Self(doc.setup.discard_white_overprint.then(|| Arc::new(doc.spot_ink_names().into_iter().filter(|n| spot(n)).collect()))) + } + + /// Whether `p` knocks out instead of overprinting. + pub fn knocks_out(&self, p: &Paint) -> bool { + self.0.as_ref().is_some_and(|spots| is_paper_white(p, spots)) + } +} + impl Document { + /// The names of the spot swatches that a color linked by name prints as: a name whose first + /// swatch ([`Document::swatch`]) is not a solid spot color is left out. + pub fn spot_ink_names(&self) -> HashSet { + let mut seen = HashSet::new(); + self.swatches_iter().filter(|s| seen.insert(s.name.as_str()) && s.spot && s.paint.color().is_some()).map(|s| s.name.clone()).collect() + } + /// The names of the spot swatches. pub fn spot_names(&self) -> Vec { self.swatches_iter().filter(|s| s.spot).map(|s| s.name.clone()).collect() @@ -331,6 +370,56 @@ mod tests { assert!(OverprintBlack { spot: true, ..Default::default() }.apply(&mut n, &spots), "Include Spot Blacks takes it"); } + #[test] + fn a_white_spot_ink_overprints_under_discard_white() { + let mut d = Document::new(100.0, 100.0); + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + d.swatches.push(vectorcraft_color::Swatch { name: "Opaque White".into(), paint: Paint::solid(white), global: true, spot: true }); + d.swatches.push(vectorcraft_color::Swatch { name: "Process White".into(), paint: Paint::solid(white), global: true, spot: false }); + let spot = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 }; + let process = Paint::Solid { color: white, swatch: Some("Process White".into()), tint: 1.0 }; + let paper = Paint::solid(white); + assert!(d.setup.discard_white_overprint, "on by default"); + d.swatches.push(vectorcraft_color::Swatch { + name: "Red Ink".into(), + paint: Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), + global: true, + spot: true, + }); + // A 0% tint of a spot ink resolves to white and puts no ink down. + let no_red = Paint::Solid { color: white, swatch: Some("Red Ink".into()), tint: 0.0 }; + let no_white = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 0.0 }; + let half_white = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 0.5 }; + let discard = DiscardWhite::of(&d); + assert!(discard.knocks_out(&paper), "paper white knocks out"); + assert!(discard.knocks_out(&process), "so does a global process white"); + assert!(!discard.knocks_out(&spot) && !discard.knocks_out(&half_white), "a white spot ink is an ink"); + assert!(discard.knocks_out(&no_red) && discard.knocks_out(&no_white), "a 0% tint of a spot ink is paper white"); + assert!(!is_paper_white(&spot, &d.spot_ink_names()) && is_paper_white(&paper, &d.spot_ink_names())); + // A spot swatch after a process one of the same name: a link finds the process one. + d.swatches.push(vectorcraft_color::Swatch { name: "Process White".into(), paint: Paint::solid(white), global: true, spot: true }); + assert!(DiscardWhite::of(&d).knocks_out(&process), "the first swatch of the name decides"); + // A spot swatch without a solid color prints a linked solid as its own process color. + d.swatches.push(vectorcraft_color::Swatch { name: "Empty".into(), paint: Paint::None, global: true, spot: true }); + let empty = Paint::Solid { color: white, swatch: Some("Empty".into()), tint: 1.0 }; + assert!(DiscardWhite::of(&d).knocks_out(&empty), "so it is paper white"); + d.setup.discard_white_overprint = false; + assert!(!DiscardWhite::of(&d).knocks_out(&paper), "off: white overprints too"); + + // The previews and plates darken the spot ink and leave paper white knocking out. + let blend = |fill: Paint| { + let mut n = Node::path(NodeId(1), Default::default(), Appearance::basic(fill, Paint::None, 0.0)); + if let Some(f) = n.appearance.fill_mut() { + f.overprint = true; + } + let mut a = Arc::new(n); + darken_overprints(&mut a, &discard); + a.appearance.fill().map(|f| f.blend) + }; + assert_eq!(blend(spot), Some(BlendMode::Darken)); + assert_eq!(blend(paper), Some(BlendMode::Normal)); + } + #[test] fn apply_deep_copies_only_the_nodes_that_change() { let k = cmyk(0.0, 0.0, 0.0, 1.0); diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 703d81ddc3..d80a3c0e5c 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "Print Ink Fixes", ["Object", "Plug-ins", "Color Effects"], None, - "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", + "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting; a white linked to a spot swatch at a tint above 0% is an ink and keeps it), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", has_doc, print_fixes::run ), diff --git a/crates/engine/src/cmd/addons/color/print_fixes.rs b/crates/engine/src/cmd/addons/color/print_fixes.rs index c5f430eb76..5348a621ec 100644 --- a/crates/engine/src/cmd/addons/color/print_fixes.rs +++ b/crates/engine/src/cmd/addons/color/print_fixes.rs @@ -1,14 +1,15 @@ //! Print Ink Fixes (`addon.color.printFixes`, Object › Plug-ins › Color Effects › Print Ink //! Fixes…): a CMYK document's inks made ready for print in one undo step. Colours with more total -//! ink than the limit are scaled down to it, white fills and strokes stop overprinting, and black +//! ink than the limit are scaled down to it, paper white fills and strokes stop overprinting, and black //! ones start to, as Edit › Edit Colors › Overprint Black sets it. +use std::collections::HashSet; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Color; use vectorcraft_color::swatch::REGISTRATION; -use vectorcraft_doc::overprint::{OverprintBlack, is_white}; +use vectorcraft_doc::overprint::{OverprintBlack, is_paper_white}; use vectorcraft_doc::{ColorMode, Node, NodeKind}; use super::super::super::colorcmds::{Recolor, Scope, keeping_series_paint}; @@ -78,8 +79,9 @@ impl Fixes { } /// Remove white overprint from `n`'s own fills and strokes and its characters': true when - /// that changed anything. - fn unset_white(&self, n: &mut Node) -> bool { + /// that changed anything. A white linked to one of the spot inks `inks` is an ink and keeps + /// overprinting ([`is_paper_white`]). + fn unset_white(&self, n: &mut Node, inks: &HashSet) -> bool { let mut changed = false; let mut off = |aimed: bool, white: bool, flag: &mut bool| { if aimed && white && *flag { @@ -89,26 +91,27 @@ impl Fixes { }; for it in &mut n.appearance.items { let aimed = if it.is_fill() { self.fill } else { self.stroke }; - let white = is_white(it.paint()); + let white = is_paper_white(it.paint(), inks); off(aimed, white, it.overprint_mut()); } if let NodeKind::Text(t) = &mut n.kind { for r in &mut t.runs { - off(self.fill, is_white(&r.style.fill), &mut r.style.overprint_fill); - off(self.stroke, is_white(&r.style.stroke), &mut r.style.overprint_stroke); + off(self.fill, is_paper_white(&r.style.fill, inks), &mut r.style.overprint_fill); + off(self.stroke, is_paper_white(&r.style.stroke, inks), &mut r.style.overprint_stroke); } } changed } /// The overprint fixes on `n` and everything inside it: (objects whose white overprint was - /// removed, objects set to overprint black). - fn overprint(&self, n: &mut Node, black: &OverprintBlack, spots: &[String]) -> (usize, usize) { - let white = usize::from(self.remove_white_overprint && self.unset_white(n)); + /// removed, objects set to overprint black). `spots`: the document's spot swatch names; `inks`: + /// those that linked colors print as ([`vectorcraft_doc::Document::spot_ink_names`]). + fn overprint(&self, n: &mut Node, black: &OverprintBlack, spots: &[String], inks: &HashSet) -> (usize, usize) { + let white = usize::from(self.remove_white_overprint && self.unset_white(n, inks)); let blacks = self.overprint_black > 0.0 && (!self.text_only || matches!(n.kind, NodeKind::Text(_))); let mut counts = (white, usize::from(blacks && black.apply(n, spots))); for c in n.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) { - let (w, b) = self.overprint(Arc::make_mut(c), black, spots); + let (w, b) = self.overprint(Arc::make_mut(c), black, spots, inks); counts = (counts.0 + w, counts.1 + b); } counts @@ -154,10 +157,10 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { if !fixes.remove_white_overprint && fixes.overprint_black <= 0.0 { return Ok(ink); } - let spots = d.spot_names(); + let (spots, inks) = (d.spot_names(), d.spot_ink_names()); for id in &ids { if let Some(n) = d.node_mut(*id) { - let (w, b) = fixes.overprint(n, &black, &spots); + let (w, b) = fixes.overprint(n, &black, &spots, &inks); (white, blacks) = (white + w, blacks + b); } } diff --git a/crates/engine/src/cmd/addons/color/print_fixes/tests.rs b/crates/engine/src/cmd/addons/color/print_fixes/tests.rs index e4c1915879..8e28701572 100644 --- a/crates/engine/src/cmd/addons/color/print_fixes/tests.rs +++ b/crates/engine/src/cmd/addons/color/print_fixes/tests.rs @@ -101,6 +101,20 @@ fn white_overprint_goes_and_black_overprint_comes_at_the_threshold() { assert_eq!(s.execute(C, &json!({"overprintBlack": 90, "fill": false})).unwrap()["changed"], 0); } +#[test] +fn a_white_spot_ink_keeps_its_overprint() { + let white = cmyk(0.0, 0.0, 0.0, 0.0); + let (mut s, ids) = doc(&[(white.clone(), true), (white.clone(), true)]); + s.execute("swatch.new", &json!({"name": "Opaque White", "color": white, "spot": true})).unwrap(); + s.execute("select.set", &json!({"ids": [ids[1].0]})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(fill(&s, ids[1]).1, "the swatch keeps the overprint"); + let v = s.execute(C, &json!({"removeWhiteOverprint": true})).unwrap(); + assert_eq!(v["whiteOverprintRemoved"], 1, "{v}"); + assert_eq!([fill(&s, ids[0]).1, fill(&s, ids[1]).1], [false, true], "paper white stops; the spot white is an ink"); +} + #[test] fn bad_requests_and_rgb_documents_are_refused() { let (mut s, ids) = doc(&[(cmyk(100.0, 100.0, 100.0, 100.0), true)]); diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index c0bb942150..7927479f4b 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones not linked to a spot swatch at a tint above 0% knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), diff --git a/crates/engine/src/tests/docsetup.rs b/crates/engine/src/tests/docsetup.rs index 21dd990087..d2b6a1d839 100644 --- a/crates/engine/src/tests/docsetup.rs +++ b/crates/engine/src/tests/docsetup.rs @@ -492,6 +492,13 @@ fn discard_white_overprint_keeps_white_overprints_in_overprint_preview() { s.execute("document.setup", &json!({"discardWhiteOverprint": false})).unwrap(); let [r, g, b, _] = centre(&s); assert!(r > 200 && g < 60 && b < 60, "a white overprint vanishes: {:?}", [r, g, b]); + // A white spot ink is an ink: it overprints with the option on too. + s.execute("document.setup", &json!({"discardWhiteOverprint": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Opaque White", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); + s.execute("select.set", &json!({"ids": [white]})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap(); + let [r, g, b, _] = centre(&s); + assert!(r > 200 && g < 60 && b < 60, "the spot white overprints: {:?}", [r, g, b]); } #[test] diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 094cdeb99d..501eeee2a9 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -114,6 +114,9 @@ pub(crate) struct Exporter<'a> { /// Overprinting characters' fills and strokes are drawn with Darken, as a separation's plate /// draws its overprinting fills and strokes ([`vectorcraft_doc::overprint::darken_overprints`]). pub darken_overprints: bool, + /// Document Setup → Discard White Overprint as it applies to the document's paints, read from + /// the document on first use ([`Self::discards_white`]). + discard_white: Option, /// An overprinting fill or stroke was drawn so. pub overprinted: bool, /// Characters with neither fill nor stroke, or whose fill is drawn as art (outlines filled diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index 498c12ca04..c1fc8defe7 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -64,6 +64,7 @@ impl<'a> Exporter<'a> { mask_art_left_out: false, overprint: false, darken_overprints: false, + discard_white: None, overprinted: false, invisible: false, inline_depth: 0, diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index d84e8f7124..e18b581fa7 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -620,11 +620,10 @@ impl Exporter<'_> { } /// Draw a fill or stroke of `paint` with `draw`: as a form marked to overprint when it - /// `overprints`, paints and overprints are kept (but not a white one with Discard White - /// Overprint). + /// `overprints`, paints and overprints are kept (but not a paper white one with Discard White + /// Overprint, [`Self::discards_white`]). pub(super) fn overprinting(&mut self, s: &mut Surface, overprints: bool, paint: &Paint, draw: impl FnOnce(&mut Self, &mut Surface)) { - let white = || self.doc.setup.discard_white_overprint && vectorcraft_doc::overprint::is_white(paint); - if overprints && self.overprint && !paint.is_none() && !white() { + if overprints && self.overprint && !paint.is_none() && !self.discards_white(paint) { self.overprinted = true; crate::forms::form(s, Mark::Overprint, |s| draw(self, s)); } else { @@ -633,11 +632,10 @@ impl Exporter<'_> { } /// [`Self::overprinting`] for a character fill or stroke, which has no blend mode of its own: - /// with [`Self::darken_overprints`] an overprinting one is drawn with Darken (not a white one - /// with Discard White Overprint). + /// with [`Self::darken_overprints`] an overprinting one is drawn with Darken (not a paper + /// white one with Discard White Overprint). pub(super) fn char_overprinting(&mut self, s: &mut Surface, overprints: bool, paint: &Paint, draw: impl FnOnce(&mut Self, &mut Surface)) { - let white = vectorcraft_doc::overprint::is_white(paint) && self.doc.setup.discard_white_overprint; - if overprints && self.darken_overprints && !paint.is_none() && !white { + if overprints && self.darken_overprints && !paint.is_none() && !self.discards_white(paint) { s.push_blend_mode(krilla::blend::BlendMode::Darken); self.overprinting(s, overprints, paint, draw); s.pop(); @@ -646,6 +644,20 @@ impl Exporter<'_> { } } + /// Whether paint `p` knocks out where it overprints under Document Setup → Discard White + /// Overprint ([`vectorcraft_doc::overprint::DiscardWhite::knocks_out`]). The document's spot + /// ink names are read only for a white linked to a swatch. + fn discards_white(&mut self, p: &Paint) -> bool { + let doc = self.doc; + if !doc.setup.discard_white_overprint || !vectorcraft_doc::overprint::is_white(p) { + return false; + } + if !matches!(p, Paint::Solid { swatch: Some(_), .. }) { + return true; + } + self.discard_white.get_or_insert_with(|| vectorcraft_doc::overprint::DiscardWhite::of(doc)).knocks_out(p) + } + /// Is `p` a paint PDF has no paint for when it paints a fill (`fill`) or a stroke, which /// [`Self::area`] draws as art: a pattern swatch or a gradient drawn as pixels /// ([`vectorcraft_color::GradientPaint::draws_as_pixels`]), but not a Perceptual one of spot diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index 6c619b3165..96ccc2c2f0 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -40,7 +40,7 @@ use kurbo::{Affine, Rect, Vec2}; use serde::Serialize; use vectorcraft_color::cms::{self, ProfileKind}; use vectorcraft_doc::marks::PrinterMarks; -use vectorcraft_doc::overprint::{OverprintBlack, clear_overprints, darken_overprints}; +use vectorcraft_doc::overprint::{DiscardWhite, OverprintBlack, clear_overprints, darken_overprints}; use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; pub use layout::{MAX_COPIES_PER_SHEET, MAX_TILES, TileGrid}; @@ -411,12 +411,12 @@ fn composite_overprints(doc: &mut Document, set: &PrintSettings) { if set.output.mode == OutputMode::Separations || how == PrintOverprints::Preserve { return; } - let discard_white = doc.setup.discard_white_overprint; + let discard_white = DiscardWhite::of(doc); let symbols = doc.symbols.iter_mut().map(|s| &mut s.art); let nodes = doc.layers.iter_mut().chain(symbols).chain(doc.patterns.iter_mut().flat_map(|p| p.art.iter_mut())); for n in nodes { if how == PrintOverprints::Simulate { - darken_overprints(n, discard_white); + darken_overprints(n, &discard_white); } clear_overprints(n); } diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index dada741c9d..92e0a16620 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -9,7 +9,7 @@ use vectorcraft_color::cms::{self, Cms, Model, ProfileKind}; use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{BlendMode, Color, GradientKind, GradientStop, Paint}; use vectorcraft_doc::inks::{Link, StopPlates, inks, plates, spot_color, stop_inks, visit_node_colors}; -use vectorcraft_doc::overprint::{darken_overprints, is_black_ink, is_white}; +use vectorcraft_doc::overprint::{DiscardWhite, darken_overprints, is_black_ink}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, ImageBlob, Node, NodeKind}; use super::{DEFAULT_FREQUENCY, InkSettings, PrintInk, PrintSettings}; @@ -236,15 +236,15 @@ impl<'a> Separator<'a> { /// Overprinting fills and strokes of `a`'s subtree with a Normal blending mode, and /// overprinting character fills and strokes, that put none of ink `plate` down leave its plate - /// as it is: they are drawn as nothing on it (white ones with `discard_white` aside, which - /// knock out). A writer without blending modes (PostScript) then keeps the ink below them, + /// as it is: they are drawn as nothing on it (paper white ones that `discard_white` knocks out + /// aside). A writer without blending modes (PostScript) then keeps the ink below them, /// where it would draw their Darken as a knockout. One that puts any ink down is drawn, and on /// a PostScript plate its ink replaces the ink below, as a nonzero component of an overprinting /// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2). On a /// PostScript plate, the stops and points of such a gradient that put none of the ink down /// become paper white ([`Self::clear_inkless_stops`]), which the writer leaves out there. - fn clear_inkless_overprints(&self, plate: &str, a: &mut Arc, discard_white: bool) { - let inkless = |overprint: bool, p: &Paint| overprint && !p.is_none() && !(discard_white && is_white(p)) && self.no_ink(plate, p); + fn clear_inkless_overprints(&self, plate: &str, a: &mut Arc, discard_white: &DiscardWhite) { + let inkless = |overprint: bool, p: &Paint| overprint && !p.is_none() && !discard_white.knocks_out(p) && self.no_ink(plate, p); let n = Arc::make_mut(a); for it in &mut n.appearance.items { let normal = match it { @@ -281,12 +281,12 @@ impl<'a> Separator<'a> { /// ink the plate below shows through instead of being knocked out. pub fn plate(&self, plate: &str) -> Document { let mut d = self.doc.clone(); - let discard_white = d.setup.discard_white_overprint; + let discard_white = DiscardWhite::printing(&d, |n| !self.converts(n)); let mut colorized = BTreeSet::new(); let nodes = d.layers.iter_mut().chain(d.symbols.iter_mut().map(|s| &mut s.art)).chain(d.patterns.iter_mut().flat_map(|p| p.art.iter_mut())); for n in nodes { - self.clear_inkless_overprints(plate, n, discard_white); - darken_overprints(n, discard_white); + self.clear_inkless_overprints(plate, n, &discard_white); + darken_overprints(n, &discard_white); self.node(plate, Arc::make_mut(n)); keep_colorized_pixels(n, &d.images, &mut colorized); } diff --git a/crates/pdf/src/tests/layers.rs b/crates/pdf/src/tests/layers.rs index b11cbc47d8..d989337cee 100644 --- a/crates/pdf/src/tests/layers.rs +++ b/crates/pdf/src/tests/layers.rs @@ -352,6 +352,28 @@ fn white_overprint_is_discarded_as_the_document_setup_says() { assert_eq!(overprints(&d, json!({})).1, 3); } +#[test] +fn a_white_spot_ink_keeps_overprinting_under_discard_white_overprint() { + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + let mut d = overprinting(white); + d.swatches.push(vectorcraft_color::Swatch { name: "Opaque White".into(), paint: Paint::solid(white), global: true, spot: true }); + let paint = |d: &mut Document, p: &Paint| { + for n in std::sync::Arc::make_mut(&mut d.layers[0]).children_mut().into_iter().flatten() { + let n = std::sync::Arc::make_mut(n); + if let Some(f) = n.appearance.fill_mut().filter(|f| f.overprint) { + f.paint = p.clone(); + } + if let NodeKind::Text(t) = &mut n.kind { + t.runs.iter_mut().for_each(|r| r.style.fill = p.clone()); + } + } + }; + paint(&mut d, &Paint::solid(white)); + assert_eq!(overprints(&d, json!({})).1, 1, "paper white fills and characters knock out"); + paint(&mut d, &Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 }); + assert_eq!(overprints(&d, json!({})).1, 3, "a white spot ink overprints, characters too"); +} + #[test] fn pdf_a_overprint_mode_is_0() { let r = export(&overprinting(RED), json!({"standard": "pdfA2b", "compression": {"compressText": false}})); diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index bee9e61bad..958bef9e03 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use serde_json::json; -use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Paint, Swatch}; +use vectorcraft_color::{BlendMode, Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Paint, Swatch}; use vectorcraft_doc::{Appearance, Artboard, Document, LayerColor, Node, NodeKind}; use vectorcraft_geom::{Rect, shapes}; use vectorcraft_testkit::raster::render_region; @@ -903,6 +903,47 @@ fn overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscri assert_eq!(drawn(true, 3), (3, 1, 1), "PostScript Black plate: every black, not the faint fill"); } +#[test] +fn a_white_spot_ink_keeps_overprinting_on_plates_and_in_simulated_composites() { + // With Discard White Overprint on (the default), a paper white square over cyan knocks the + // cyan out; one in a white spot ink overprints: it puts no cyan down, so the cyan plate draws + // nothing for it, and Simulate composites it with Darken. + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + let square = |paint: Paint| { + let mut n = + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(10.0, 15.0, 30.0, 35.0)), Appearance::basic(paint, Paint::None, 0.0)); + if let Some(f) = n.appearance.fill_mut() { + f.overprint = true; + } + let mut d = over_cyan(vec![n]); + d.swatches.push(Swatch { name: "Opaque White".into(), paint: Paint::solid(white), global: true, spot: true }); + d + }; + let (paper, spot) = (square(Paint::solid(white)), square(Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 })); + assert!(paper.setup.discard_white_overprint); + let cyan_fills = |d: &Document, output: serde_json::Value| { + let opts = PrintOptions { settings: settings(json!({"output": output})), ..Default::default() }; + let p = plan(d, &opts).unwrap(); + let mut count = 0; + p.plates[0].walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none()))); + count + }; + let seps = json!({"mode": "separations"}); + assert_eq!((cyan_fills(&paper, seps.clone()), cyan_fills(&spot, seps)), (2, 1), "paper white knocks out; the spot white leaves the cyan"); + // The white ink printed as process inks is paper white. + let converted = json!({"mode": "separations", "inks": [{"name": "Opaque White", "convertToProcess": true}]}); + assert_eq!(cyan_fills(&spot, converted), 2, "a converted spot white knocks out"); + assert_eq!(cyan_fills(&spot, json!({"mode": "separations", "spotsToProcess": true})), 2, "so does one with every spot converted"); + let blends = |d: &Document| { + let opts = PrintOptions { settings: settings(json!({"advanced": {"overprints": "simulate"}})), ..Default::default() }; + let p = plan(d, &opts).unwrap(); + let mut out = vec![]; + p.doc.walk(|n| out.extend(n.appearance.fill().filter(|f| f.paint.color() == Some(white)).map(|f| f.blend))); + out + }; + assert_eq!((blends(&paper), blends(&spot)), (vec![BlendMode::Normal], vec![BlendMode::Darken])); +} + #[test] fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() { // 0.4% cyan beside 100% K, set to overprint: a PDF plate draws it with Darken, a PostScript diff --git a/crates/render/src/proof.rs b/crates/render/src/proof.rs index dd7d28eb23..09c9e1189d 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -34,8 +34,8 @@ pub use vectorcraft_color::cms::{Intent, ProofSetup, ProofTarget}; use vectorcraft_color::{Color, Paint, Swatch, SwatchGroup}; pub use vectorcraft_doc::inks::{Inks, Link, Plate, inks, map_document_colors, map_node_colors, plates, spot_color}; use vectorcraft_doc::inks::{StopPlates, map_node_inks, stop_inks}; -use vectorcraft_doc::overprint::darken_overprints; -use vectorcraft_doc::{AppearanceItem, Document, ImageBlob, Node, NodeId, Shared}; +use vectorcraft_doc::overprint::{DiscardWhite, darken_overprints}; +use vectorcraft_doc::{AppearanceItem, Document, ImageBlob, Node, NodeId, NodeKind, Shared}; use vello_cpu::Pixmap; use vello_cpu::color::PremulRgba8; @@ -391,6 +391,8 @@ impl Fit { /// one of them while they are kept. pub(crate) struct Prepared { inputs: Inputs, + /// The swatches `inputs.discard_white` was read from, while Discard White Overprint is on. + spots: Option, layers: (Vec>, Vec>), art: (Vec>, Vec>), } @@ -398,10 +400,18 @@ pub(crate) struct Prepared { /// What [`prepare`] reads besides the art. #[derive(PartialEq)] struct Inputs { - discard_white: bool, + discard_white: DiscardWhite, plates: Option, } +/// The document's swatches and swatch groups, which name its spot inks ([`DiscardWhite`]): while +/// they are unchanged, the spot ink names are not read again. +#[derive(PartialEq)] +struct SpotSwatches { + swatches: Shared>, + groups: Shared>, +} + /// What the colors of Separations Preview's plates are made from ([`plate_color`]). struct Plates { /// The proof setup, with the visible plates. @@ -429,7 +439,7 @@ impl PartialEq for Plates { /// print it ([`plate_color`]). struct How<'a> { doc: &'a Document, - discard_white: bool, + discard_white: &'a DiscardWhite, /// Separations Preview: the color settings, the proof setup and the visible plates. plates: Option<(&'a Cms, &'a ProofSetup, &'a [String])>, } @@ -438,12 +448,33 @@ impl How<'_> { /// Whether [`Self::apply`] can change `n`: with Separations Preview any node, else a node with /// an overprinting fill or stroke. fn changes(&self, n: &Node) -> bool { - self.plates.is_some() || n.appearance.items.iter().any(|i| i.overprint()) + self.plates.is_some() || n.appearance.items.iter().any(|i| i.overprint()) || self.white_characters(n) } - /// Change the fills, strokes and other colors of node `a`, which holds no members. + /// Whether type `n` has an overprinting character fill or stroke that Discard White Overprint + /// knocks out ([`DiscardWhite::knocks_out`]). + fn white_characters(&self, n: &Node) -> bool { + let white = |r: &vectorcraft_doc::TextRun| { + (r.style.overprint_fill && self.discard_white.knocks_out(&r.style.fill)) + || (r.style.overprint_stroke && self.discard_white.knocks_out(&r.style.stroke)) + }; + matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(white)) + } + + /// Change the fills, strokes and other colors of node `a`, which holds no members. Character + /// fills and strokes that Discard White Overprint knocks out stop overprinting, judged on + /// their own colors before Separations Preview maps them to the visible plates; the renderer + /// darkens the others. fn apply(&self, a: &mut Arc) { darken_overprints(a, self.discard_white); + if self.white_characters(a) + && let NodeKind::Text(t) = &mut Arc::make_mut(a).kind + { + for r in &mut t.runs { + r.style.overprint_fill &= !self.discard_white.knocks_out(&r.style.fill); + r.style.overprint_stroke &= !self.discard_white.knocks_out(&r.style.stroke); + } + } if let Some((c, proof, visible)) = self.plates { map_node_inks(Arc::make_mut(a), &mut |col, sw, plates| plate_color(self.doc, c, proof, visible, col, sw, plates)); } @@ -461,8 +492,10 @@ pub(crate) fn prepare<'a>(doc: &'a Document, opts: &RenderOptions, kept: &mut Op } let seps = opts.proof.as_ref().and_then(|p| p.separations.as_ref().map(|s| (p, s))); let c = cms::active(); + let spots = doc.setup.discard_white_overprint.then(|| SpotSwatches { swatches: doc.swatches.clone(), groups: doc.swatch_groups.clone() }); + let read = kept.as_ref().filter(|k| k.spots == spots).map(|k| k.inputs.discard_white.clone()); let inputs = Inputs { - discard_white: doc.setup.discard_white_overprint, + discard_white: read.unwrap_or_else(|| DiscardWhite::of(doc)), plates: seps.map(|(proof, _)| Plates { proof: proof.clone(), swatches: doc.swatches.clone(), @@ -473,7 +506,7 @@ pub(crate) fn prepare<'a>(doc: &'a Document, opts: &RenderOptions, kept: &mut Op }), }; let earlier = kept.take().filter(|k| k.inputs == inputs); - let how = How { doc, discard_white: inputs.discard_white, plates: seps.map(|(proof, visible)| (&*c, proof, visible.as_slice())) }; + let how = How { doc, discard_white: &inputs.discard_white, plates: seps.map(|(proof, visible)| (&*c, proof, visible.as_slice())) }; let none = (vec![], vec![]); let (layers, art) = earlier.as_ref().map_or((&none, &none), |k| (&k.layers, &k.art)); let made_layers = prepare_list(&doc.layers, &layers.0, &layers.1, &how); @@ -490,7 +523,7 @@ pub(crate) fn prepare<'a>(doc: &'a Document, opts: &RenderOptions, kept: &mut Op } Cow::Owned(d) }; - *kept = Some(Prepared { inputs, layers: (doc.layers.clone(), made_layers), art: (symbol_art, made_art) }); + *kept = Some(Prepared { inputs, spots, layers: (doc.layers.clone(), made_layers), art: (symbol_art, made_art) }); out } diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index 2cdc41df3c..1b734b4522 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -2205,6 +2205,74 @@ fn rasters_follow_the_view_options() { draws_as_new(&mut d, &isolated, &on_white, unchanged); } +/// Overprinting white characters over red in Overprint Preview: paper white knocks out while +/// Discard White Overprint is on and vanishes into the red when it is turned off; a white spot ink +/// overprints with it on. In Separations Preview paper white characters knock the plate out too. +#[test] +fn overprinting_white_characters_follow_discard_white_overprint() { + let _fonts = fonts_steady(); + use vectorcraft_doc::text::{CharStyle, TextObject}; + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + let typed = || { + let mut d = Document::new(200.0, 100.0); + d.swatches.push(vectorcraft_color::Swatch { name: "Opaque White".into(), paint: Paint::solid(white), global: true, spot: true }); + let red = + filled(&mut d, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), vec![]); + let style = CharStyle { size: 50.0, fill: Paint::solid(white), overprint_fill: true, ..Default::default() }; + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "Hamburg", style)))); + with_art(d, vec![red, text]) + }; + let overprints = RenderOptions { overprint_preview: true, background: Some([255, 255, 255, 255]), ..Default::default() }; + draws_as_new(&mut typed(), &overprints, &overprints, |d| d.setup.discard_white_overprint = false); + draws_as_new(&mut typed(), &overprints, &overprints, |d| { + let text = d.layers[0].children().unwrap()[1].id; + if let Some(NodeKind::Text(t)) = d.node_mut(text).map(|n| &mut n.kind) { + t.runs.iter_mut().for_each(|r| r.style.fill = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 }); + } + }); + // Knocking out shows the white of the characters; overprinting leaves only the red. + let whites = |d: &Document, opts: &RenderOptions| { + Renderer::new().render(d, 200, 100, Affine::IDENTITY, opts).pixels.chunks(4).filter(|p| p[0] > 250 && p[1] > 250 && p[2] > 250).count() + }; + let mut d = typed(); + assert!(whites(&d, &overprints) > 0, "paper white knocks out"); + d.setup.discard_white_overprint = false; + assert_eq!(whites(&d, &overprints), 0, "with the option off it overprints"); + let mut d = typed(); + let text = d.layers[0].children().unwrap()[1].id; + if let Some(NodeKind::Text(t)) = d.node_mut(text).map(|n| &mut n.kind) { + t.runs.iter_mut().for_each(|r| r.style.fill = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 }); + } + assert_eq!(whites(&d, &overprints), 0, "a white spot ink overprints"); + // Separations Preview: paper white characters over cyan knock the Cyan plate out. + let mut d = Document::new(200.0, 100.0); + let cyan = + filled(&mut d, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)), vec![]); + let style = CharStyle { size: 50.0, fill: Paint::solid(white), overprint_fill: true, ..Default::default() }; + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "Hamburg", style)))); + let mut d = with_art(d, vec![cyan, text]); + let seps = RenderOptions { background: Some([255, 255, 255, 255]), ..proof_views(&["Cyan"]).1 }; + assert!(whites(&d, &seps) > 0, "paper white knocks the Cyan plate out"); + d.setup.discard_white_overprint = false; + assert_eq!(whites(&d, &seps), 0, "with the option off the cyan shows through"); + // Magenta characters over cyan, with only the Cyan plate shown: they put none of it down, so + // the cyan shows through them, as if they were not there. + let magenta = |with_text: bool| { + let mut d = Document::new(200.0, 100.0); + let cyan = filled( + &mut d, + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), + Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)), + vec![], + ); + let style = CharStyle { size: 50.0, fill: Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), overprint_fill: true, ..Default::default() }; + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "Hamburg", style)))); + let d = with_art(d, if with_text { vec![cyan, text] } else { vec![cyan] }); + Renderer::new().render(&d, 200, 100, Affine::IDENTITY, &proof_views(&["Cyan"]).1).pixels + }; + assert!(magenta(true) == magenta(false), "the characters leave the cyan plate as it is"); +} + /// A document for the proof previews: a cyan square, a magenta circle over it whose black stroke /// overprints, a white square over the cyan one that overprints, a blurred rectangle in spot color /// `Spot`, and an instance of symbol `S`, a group holding a yellow square. @@ -2273,8 +2341,8 @@ fn proof_previews_keep_their_art_between_frames() { /// With Overprint Preview or Separations Preview on, a renderer draws what a new renderer draws /// after a change to the art or to what the previews read: an object recolored, Discard White -/// Overprint turned off, a symbol's art recolored (its instance shows the plates of the new art), -/// the spot color redefined, a spot color in a color group redefined, the Spot Colors option set +/// Overprint turned off, an overprinting white's swatch made a spot color, a symbol's art +/// recolored (its instance shows the plates of the new art), the spot color redefined, a spot color in a color group redefined, the Spot Colors option set /// to CMYK values, a plate hidden, Simulate Paper Color, another proof profile, and one preview /// after the other. #[test] @@ -2296,6 +2364,19 @@ fn proof_previews_draw_changes_as_a_new_renderer_does() { for opts in [&overprint, &separations] { draws_as_new(&mut proof_doc(), opts, opts, recolor_square); draws_as_new(&mut proof_doc(), opts, opts, |d| d.setup.discard_white_overprint = false); + // The overprinting white square's swatch becomes a spot color, a white ink. + let mut linked = proof_doc(); + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + linked.swatches.push(vectorcraft_color::Swatch { name: "White".into(), paint: Paint::solid(white), global: true, spot: false }); + let square = linked.layers[0].children().unwrap()[2].id; + if let Some(f) = linked.node_mut(square).unwrap().appearance.fill_mut() { + f.paint = Paint::Solid { color: white, swatch: Some("White".into()), tint: 1.0 }; + } + draws_as_new(&mut linked, opts, opts, |d| { + if let Some(s) = d.swatch_mut("White") { + s.spot = true; + } + }); } draws_as_new(&mut proof_doc(), &separations, &separations, recolor_symbol); draws_as_new(&mut proof_doc(), &separations, &separations, |d| { diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..043693126b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5083,7 +5083,16 @@ objects differ). Overprint Preview (`view.overprintPreview`) and Separations Pre it by darkening (the stronger ink of each plate wins, so a colour overprinting itself stays that colour). Older files that listed Overprint Black objects in the document get the flags on load. PDF export writes them with `advanced.overprint: "preserve"` (the default): each overprinting fill and stroke sets a graphics state with `/OP true /op true /OPM 1` (`/OPM 0` in PDF/A). With `discardWhiteOverprint` (`document.setup`, on by -default) white ones knock out instead; `"discard"` writes none. +default) paper white ones knock out instead; `"discard"` writes none. Paper white is solid white that is not a spot +white. Spot white objects keep overprinting +([white overprint](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/white-overprint.html), +[reference, White Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=650)). +These are VectorCraft's own rules: a spot white is a white linked to a solid spot swatch at a tint above 0% (an opaque +white ink, for example), so a 0% tint of a spot swatch is paper white, and so is a spot white that printed separations +convert to process inks. A spot white's fills, strokes and characters keep overprinting in PDF export, Overprint Preview, +Separations Preview and printed separations, its fills and strokes keep overprinting in composite print with Overprints +set to Simulate, and Print Ink Fixes' `removeWhiteOverprint` leaves it overprinting. EPS export does not apply +`discardWhiteOverprint`. ```json {"name":"run_command","arguments":{"command":"object.setOverprint","params":{"ids":[12],"stroke":true}}} @@ -15398,7 +15407,7 @@ document's inks for print, as one undo step: | `scope` | `selection`, `document` (the selection, or the document while nothing is selected) | What it fixes; `ids` stand for the selection | | `inkLimit` | total ink % 1…400, 0 off (off) | CMYK colours (solid, gradient stops, gradient meshes) with more ink than this are scaled down to it; colours of spot swatches and Registration stay | | `excludePureBlack` | bool (true) | Black-only CMYK and grey colours keep their ink | -| `removeWhiteOverprint` | bool (false) | White fills and strokes, and characters', stop overprinting | +| `removeWhiteOverprint` | bool (false) | White fills and strokes, and characters', stop overprinting; a white linked to a spot swatch at a tint above 0% is an ink and keeps overprinting | | `overprintBlack` | black % 1…100, 0 off (off) | Black-only and grey fills and strokes this dark or darker overprint, as `edit.colors.overprintBlack` sets it (not spot-linked or rich blacks) | | `textOnly` | bool (false) | Overprint Black on type only | | `fill`, `stroke` | bool (true) | Which paints the fixes reach | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..13dcea8089 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2388,6 +2388,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Print dialog's Document Ink Options list shows an icon before each spot ink's name, and a click on it prints that one ink as process inks (on the Cyan, Magenta, Yellow and Black plates, with no plate of its own) or as a spot ink again, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for single spot colors. Other spot inks keep their plates, and spot gradient stops and DCS images' spot plates follow each ink's choice (`print.setup {settings: {output: {inks: [{name, convertToProcess: true}]}}}`, kept with the document and in print presets; `print.preview` lists every ink as `documentInks`). These are VectorCraft's own rules: Convert All Spot Colors to Process converts every spot ink and dims the icons while keeping each ink's own choice, a converted ink's Print, Frequency and Angle are dimmed and kept, and process inks and Registration have no icon. Evidence: `print::one_spot_ink_converts_to_process_and_the_others_keep_their_plates`, `print::converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice`, `print::a_spot_gradient_stop_prints_its_process_plates`, `cmykimages::a_dcs_image_converts_only_the_spot_ink_chosen`, `tests::print::a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate`, `dialogs::tests_print::a_spot_inks_icon_converts_it_to_process_and_back`. Print scores and hours are unchanged. - On a PostScript plate, an overprinting gradient that puts the plate's ink down in some places and none in others leaves the ink below where it puts none: the stretches between stops of paper white and the padding past an end that is painted paper white (with the end stop's color at Level 2 and the color of the stretch next to it in a Level 3 smooth shading, which differ when two stops share the end's offset) are clipped out of a linear, radial or diamond gradient, the wedges of paper white out of a conic one, and the cells whose 8-bit samples carry none of the plate's ink out of a freeform one (masked at Level 3, clipped at Level 2). This holds for fills, strokes and characters, and on spot plates. Where the gradient puts ink down, its amount replaces the ink below as before. A stop or point with up to half a percent of another ink in a color that counts as black puts none down, as a solid fill of that color does. PDF plates are unchanged. These are VectorCraft's own rules. Evidence: `print::tests::an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscript_plate`, `print::tests::an_overprinting_gradient_with_a_hard_stop_at_an_end_keeps_the_ink_below_on_a_postscript_plate`, `print::tests::overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below_on_postscript_plates` and `print::tests::an_overprinting_freeform_gradient_leaves_out_the_cells_its_samples_write_without_ink_on_a_postscript_plate` (`vectorcraft-eps`), `tests::print::a_near_black_stop_of_an_overprinting_gradient_puts_no_cyan_on_postscript_plates`. - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. A black linked to a swatch the document lacks separates from its own values, so on PostScript plates it counts as an unlinked black (VectorCraft's own rule). Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates`, `print::overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. + - With Discard White Overprint on, spot white objects keep overprinting and only paper white knocks out ([white overprint](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/white-overprint.html), [reference, White Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=650)). These are VectorCraft's own rules: a spot white is a white linked to a solid spot swatch at a tint above 0% (an opaque white ink, for example), so a 0% tint of a spot swatch is paper white, and so is a spot white that printed separations convert to process inks. A spot white's fills, strokes and characters keep overprinting in PDF export, Overprint Preview, Separations Preview and printed separations, its fills and strokes keep overprinting in composite print with Overprints set to Simulate, and Print Ink Fixes' Remove White Overprint leaves it overprinting. Overprint Preview and Separations Preview now also show overprinting paper white characters knocking out while the option is on, as PDF export writes them. EPS export keeps every overprint, as before. Evidence: `overprint::tests::a_white_spot_ink_overprints_under_discard_white`, `tests::layers::a_white_spot_ink_keeps_overprinting_under_discard_white_overprint` and `tests::print::a_white_spot_ink_keeps_overprinting_on_plates_and_in_simulated_composites` (`vectorcraft-pdf`), `cmd::addons::color::print_fixes::tests::a_white_spot_ink_keeps_its_overprint`, `tests::docsetup::discard_white_overprint_keeps_white_overprints_in_overprint_preview`, `tests::memory::proof_previews_draw_changes_as_a_new_renderer_does`, `tests::memory::overprinting_white_characters_follow_discard_white_overprint`. Print scores and hours are unchanged. - The Print dialog's General section (and the print preset editor) has a link button after Scale W and H, as the Custom scale has one on [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/print-documents-in-illustrator.html), where turning it off scales the width and height apart. While it is on, typing either percentage sets the other, and turning it on sets H to W. It is on for new settings, dimmed with the fields unless Scaling is Custom or a tiling choice, toggled with a click, Space or Enter, and named with its on or off state for screen readers. W and H take 1–1000% in the fields. The link is kept with the document's print settings and in print presets (`print.setup {settings: {scale: {linked}}}`); settings saved without it read it as off, so they print as before. Its default, the tiling choices and the agent rules are VectorCraft's own. Evidence: `print::the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it`, `tests::print::the_scale_link_keeps_width_and_height_equal`, `tests::print::a_scale_saved_without_the_link_keeps_its_width_and_height`, `dialogs::tests_print::the_scale_link_keeps_scale_width_and_height_equal`, `dialogs::tests_print::a_print_preset_keeps_the_scale_link`. Print scores and hours are unchanged. - A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root ``. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626). - PDF export and PDF-compatible `.ai` and `.ait` saves write the document's File Info created date as the file's creation date, or the time of writing when the document has none, and the time of writing as its modification date; the page information mark still prints the time of writing (`crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/marks.rs`). @@ -2501,7 +2502,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The undo histories of all the open documents together keep their steps within a quarter of the installed memory on the same systems (at least 64 MiB, and at most a quarter of the address space in a 32-bit build), within 1 GiB where the installed memory can't be read, and within 256 MiB in the web build; past that budget the oldest steps of any open document are dropped first, but each document keeps its last eight undo steps and its next eight redo steps. Closing a document frees its share for the others. With `--deep`, each memory row of `vectorcraft-cli perf` also gives the peak so far: the peak working set on Windows and the peak resident memory (`VmHWM`) on Linux. A new last row gives the memory after the SVG export and the save → open → save at the end of the run. The renderer composes the two ink planes of a CMYK document that shows transparency into screen colors on up to as many threads as it rasterizes with, instead of on one. At 2880 × 1800 on 8 threads, a page of 300 shapes at 20% to 90% opacity takes 30 ms a frame instead of 55 ms, and 50,000 paths with one at 99% opacity take 258 ms instead of 361 ms (`vectorcraft-cli bench`), with the same pixels. - With Overprint Preview or Separations Preview on, the renderer keeps the art it prepared for the preview from one frame to the next. It prepares again the objects that changed, and all of the art when Discard White Overprint changes or, with Separations Preview, when the plates shown, the proof setup, the swatches, the Spot Colors option or the color settings change or a profile is loaded. It draws the other objects from the art, geometry and stroke outlines it kept for them. + With Overprint Preview or Separations Preview on, the renderer keeps the art it prepared for the preview from one frame to the next. It prepares again the objects that changed, and all of the art when Discard White Overprint changes, when a swatch becomes or stops being a spot color while it is on, or, with Separations Preview, when the plates shown, the proof setup, the swatches, the Spot Colors option or the color settings change or a profile is loaded. It draws the other objects from the art, geometry and stroke outlines it kept for them. Pathfinder › Merge and the `pathfinder.merge` group effect find the faces of every fill in a few contour passes over the arrangement, as Trim and Crop do, instead of one pass for each distinct fill. The output paths and their order are the same. With 8,000 squares that do not touch, each with its own fill, Merge takes 72 to 107 ms instead of 17 to 32 s (release build). The Pathfinder panel, Offset Path, Clean Up, Divide Objects Below, Make and Release Blend, Envelope Distort's Make and Release, Repeat (Radial, Grid, Mirror and Release), Vector Halftone, New and Redefine Symbol, Delete Symbol, erasing with the Symbol Sprayer, Rasterize, Convert to Artboards, Flatten Transparency, Clear Guides, Shape Builder, Live Paint, Release Image Trace, Make and Release Opacity Mask, Delete with direct-selected anchor points, Remove Anchor Points, Cut Path, and the Shaper, Knife, Eraser, Path Eraser, Line Cut, Rectangle Cut, Mirror & Cut and Blob Brush tools add and remove objects in one pass over each layer or group they change, and Outline Stroke and Expand write each new object in the place of the object it replaces (#1429). Cut Path at Selected Anchor Points (`path.cutAtAnchors`) selects the cut ends with one selection call, which skips paths already selected through a hash set, instead of adding each cut path in turn and searching the paths already added. The selection is the same, every field (`selecting_cut_ends_matches_adding_them_one_by_one`). With the 8 middle anchors of each of 5,000 open paths of 10 anchors selected, building the selection of 40,000 cut ends takes 9.7 ms instead of 232 ms of CPU time, and with 2,000 paths 3.2 ms instead of 39 ms; at 500 paths both take 3 ms or less (medians of 7 runs, `cargo run --release -p vectorcraft-engine --example cut_path_select_bench`). Scores and hours unchanged. From e30ce7fcdc3ff127224d3fe54a26f4032e5d416e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 22 Nov 2026 17:01:51 -0800 Subject: [PATCH 53/78] Swatch libraries: a nested pattern's swatch keeps its free library name A pattern that a library pattern's art is painted with, whose numbered name ("Inner 2") the document gives another pattern, came in as "Inner 2 2" with its swatch under that name too, so adding the library's "Inner 2" swatch next found that swatch and left the name unused. The swatch now takes the library swatch's name when no swatch or color group uses it, and still paints the pattern that came in. A color a library pattern's art brings no longer reuses a numbered copy whose name the library gives another swatch when the copy is that swatch, whether or not the art uses that swatch. Before, only a copy of a swatch the same add brought was left out, so adding the library's blue "Ink 2" and then a pattern painted with its blue "Ink" linked the pattern's art to "Ink 2". The params text, docs/mcp.md and the progress line describe both rules, and the progress line says that Use Library Item's numbered names do not skip the library's other names. --- crates/engine/src/cmd/clipboard/resources.rs | 43 ++++++------- crates/engine/src/cmd/swatchlib.rs | 2 +- crates/engine/src/tests/swatchlib.rs | 66 +++++++++++++++++++- docs/mcp.md | 7 ++- docs/target-app-parity.md | 2 +- 5 files changed, 91 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 6303eababe..5935bc4dca 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1445,6 +1445,18 @@ impl Clipboard { w.name = other; } } + // A pattern that comes in under another name than the one reserved for its + // swatch, because a pattern has that name, keeps that name for its swatch + // when no swatch or color group uses it. + let own = name != def.name + && !d.swatch_name_taken(&def.name) + && choices.reserved.get(&def.name).is_some_and(|w| w.paint == pattern_paint(&def.name)); + if own && d.swatches.last().is_some_and(|w| w.name == name) { + if let Some(w) = d.swatches.last_mut() { + w.name = def.name.clone(); + } + out.reserved_named = true; + } Placed::added(&def.name, name) }); added_patterns.extend(p.new_name(&def.name)); @@ -1670,19 +1682,13 @@ impl Clipboard { let conflicts: BTreeSet<String> = if same_doc { BTreeSet::new() } else { self.conflicts(d, used).into_iter().map(|(w, _)| w.name.clone()).collect() }; let bases: Vec<&Swatch> = self.swatches.iter().filter(|w| is_base(w) && used.has(Res::Swatch, &w.name)).collect(); - // The swatches this import brings, for the names reserved for them. - let brought: Vec<&Swatch> = if choices.reserved.is_empty() { - vec![] - } else { - self.swatches.iter().filter(|w| if is_base(w) { used.has(Res::Swatch, &w.name) } else { used.carries(w) }).collect() - }; for w in &bases { let p = if conflicts.contains(&w.name) && choices.of(&w.name) == SwatchChoice::Merge { out.merged += 1; out.merged_swatches.insert(w.name.clone()); Placed::Existing } else { - let (p, reserved_named) = add_swatch(d, w, w, same_doc, &choices.reserved, &brought, &out.relink); + let (p, reserved_named) = add_swatch(d, w, w, same_doc, &choices.reserved, &out.relink); out.reserved_named |= reserved_named; p }; @@ -1699,7 +1705,7 @@ impl Clipboard { for def in self.swatches.iter().filter(|w| !is_base(w) && used.carries(w)) { let mut w = def.clone(); out.relink.paint(&mut w.paint); - let (p, reserved_named) = add_swatch(d, &w, def, same_doc, &choices.reserved, &brought, &out.relink); + let (p, reserved_named) = add_swatch(d, &w, def, same_doc, &choices.reserved, &out.relink); out.reserved_named |= reserved_named; out.placed(Res::Swatch, &def.name, &p); } @@ -1913,17 +1919,9 @@ pub(crate) fn numbered_name(name: &str) -> bool { /// in `reserved`. A numbered name in `reserved` ("Ink 2") that `d` does not use is kept for the /// swatch it is reserved for: that swatch comes in under it, not as a numbered copy of it that `d` /// has, and another swatch of that name gets a number. A numbered copy in `d` whose name is -/// reserved for another swatch that the import brings (`brought`), and that is that swatch with -/// its links as `relink` gives them, is left to it. -fn add_swatch( - d: &mut Document, - w: &Swatch, - source: &Swatch, - same_doc: bool, - reserved: &BTreeMap<String, Swatch>, - brought: &[&Swatch], - relink: &Relink, -) -> (Placed, bool) { +/// reserved for another swatch, and that is that swatch with its links as `relink` gives them, is +/// left to it, whether or not the import brings that swatch. +fn add_swatch(d: &mut Document, w: &Swatch, source: &Swatch, same_doc: bool, reserved: &BTreeMap<String, Swatch>, relink: &Relink) -> (Placed, bool) { let same = |n: &str| d.swatch(n).is_some_and(|t| *t == Swatch { name: n.to_string(), ..w.clone() }); let kept = (!same_doc && numbered_name(&w.name) && !d.swatch_name_taken(&w.name)).then(|| reserved.get(&w.name)).flatten(); let (owns, held) = (kept.is_some_and(|o| o == source), kept.is_some_and(|o| o != source)); @@ -1932,11 +1930,8 @@ fn add_swatch( relink.paint(&mut o.paint); *t == o }; - let theirs = |n: &str| { - n != w.name - && copy_of(&w.name, n) - && reserved.get(n).is_some_and(|o| o != source && brought.contains(&o) && d.swatch(n).is_some_and(|t| is_owner(t, o))) - }; + let theirs = + |n: &str| n != w.name && copy_of(&w.name, n) && reserved.get(n).is_some_and(|o| o != source && d.swatch(n).is_some_and(|t| is_owner(t, o))); let names = || d.swatches_iter().map(|t| t.name.as_str()); let excluded = Cell::new(false); let found = existing( diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 7e7ba4b6b6..1d0f11ae7f 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add to Swatches", ["Window", "Swatch Libraries"], None, - "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it; a swatch of a numbered library name that the art brings, such as a tint \"Ink 2\", keeps that name when the document does not use it, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}", + "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it, not to a numbered copy that is the library's other swatch of that name; a swatch of a numbered library name that the art brings, such as a tint \"Ink 2\" or a pattern's swatch when its pattern comes in under another name, keeps that name when the document does not use it, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}", has_doc, add ), diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 38c1f6175b..f72beb71c2 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -1374,6 +1374,7 @@ fn a_library_pattern_swatchs_copy_skips_the_librarys_other_names() { /// pattern's art painted with both brings both. A library tint of the spot color, picked before /// the pattern, links to the document's copy of the spot color the art takes, not to the global /// color the art brings under a numbered name, whether that color has another paint or the same. +/// The library's own spot "Ink 2" is green, so the document's blue "Ink 2" is not that swatch. #[test] fn a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings() { for global_color in ["#ff0000", "#0000ff"] { @@ -1384,7 +1385,7 @@ fn a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings() fn a_library_tint_skips_a_namesake_the_pattern_brings(global_color: &str) { let mut s = session(); run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true})); - run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "spot": true})); run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); run(&mut s, "swatch.new", json!({"name": "Crimson", "color": global_color, "global": true})); let blue = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 6}))["id"].clone(); @@ -1690,6 +1691,32 @@ fn a_color_a_pattern_brings_reuses_a_copy_that_is_not_the_librarys_namesake() { assert!(is_global(&s, "Ink 2", "#0000ff") && is_global(&s, "Ink 2 2", "#00ff00"), "{r}"); } +/// A library pattern painted with a blue global "Ink", from a library that also has a blue global +/// "Ink 2" the art does not use, added beside the document's red "Ink" after the library's "Ink 2" +/// came in: the art's "Ink" does not reuse the library's "Ink 2" and comes in as "Ink 3". +#[test] +fn a_color_a_pattern_brings_does_not_reuse_another_library_colors_copy() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "{first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 3", "#0000ff"), "{first} {r}"); + let links: Vec<Option<String>> = doc(&s).pattern("Tiles").unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect(); + assert_eq!(links, vec![Some("Ink 3".to_string())], "{first} {r}"); +} + /// A library pattern painted with a blue global "Ink", pasted beside the document's red "Ink" and /// then left without its color "Ink 2" (deleted without unlinking), is not reused by bringing the /// library's "Ink" back as "Ink 2" when the library has its own blue "Ink 2": the pattern links to @@ -1897,6 +1924,43 @@ fn a_nested_pattern_leaves_its_name_to_a_library_swatch_that_places_it_otherwise } } +/// A pattern "Inner 2" that a library pattern's art is painted with, brought under a numbered name +/// because the document has another pattern "Inner 2" without a swatch, comes with a swatch under +/// the library swatch's free name "Inner 2": adding the library's "Inner 2" next finds it. +#[test] +fn a_nested_patterns_swatch_takes_the_library_swatchs_free_name() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [own]})); + run(&mut s, "select.set", json!({"ids": [own]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 14, "height": 14})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Inner 2"]})); + assert!(doc(&s).pattern("Inner 2").is_some(), "the document keeps its pattern"); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]})); + let paint = doc(&s).swatch("Inner 2").map(|w| w.paint.clone()); + assert!( + matches!(&paint, Some(Paint::Pattern { pattern, .. }) if pattern != "Inner 2" && doc(&s).pattern(pattern).is_some()), + "{first} {paint:?}" + ); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]})); + assert_eq!(r["added"], json!([]), "{first} {r}"); + assert_eq!(doc(&s).swatch("Inner 2").map(|w| w.paint.clone()), paint, "{first} {r}"); + assert_eq!(doc(&s).patterns.len(), 3, "{first} {r}"); +} + /// A library with a pattern swatch "Tiles 2" and, in a color group, a swatch of the same name that /// places the same pattern with an offset: adding the group first leaves the name to the /// ungrouped swatch, which comes in under it next. diff --git a/docs/mcp.md b/docs/mcp.md index 9061adf0e0..84695c589e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5839,8 +5839,11 @@ of a numbered library name, such as a color or tint "Ink 2", that the pattern's document does not use it. Of two library swatches with one numbered name, the first one in the library keeps the name when the other is a swatch the pattern's art brings or a pattern swatch. A pattern the art is painted with keeps a numbered name; when the library's swatch of that name places the pattern otherwise, the swatch that comes with the -pattern gets another name. A library color whose name the document gives another color is the document's numbered -copy of the same color when it has one, so adding the pattern and its color again adds nothing. A pattern the document +pattern gets another name. When the document gives that name to another pattern, the pattern comes in under a new +number, and its swatch keeps the library swatch's name when no swatch or color group uses it. A library color whose +name the document gives another color is the document's numbered copy of the same color when it has one, so adding the +pattern and its color again adds nothing; a numbered copy whose name the library gives another swatch, and which is +that swatch, is not a copy of another color, whether or not the pattern's art uses that swatch. A pattern the document already holds with its art linked to the document's own color of that name, or to a numbered copy of the color as pasting leaves it, is used as it is, unless using it would give another swatch a name the library uses. A library tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ffe4f33315..7eab6907b7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2247,7 +2247,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). - Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name that skips the names of the library's other swatches, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it, or when the document deleted it without unlinking the tint. Use Library Item adds a library pattern's colors the same way. With Add to Swatches, a swatch of a numbered library name that a pattern's art brings, a tint or gradient included, keeps that name, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `a_library_tint_whose_color_the_document_deleted_brings_the_color_back`, `a_color_a_pattern_brings_skips_the_librarys_numbered_names`, `a_pattern_bringing_a_color_and_its_numbered_namesake_keeps_the_librarys_name`, `a_numbered_tint_or_gradient_a_pattern_brings_keeps_the_librarys_name`, `a_numbered_color_a_pattern_brings_keeps_its_name_beside_a_copy_of_it`, `a_numbered_library_pattern_keeps_its_name`, `a_library_pattern_swatchs_copy_skips_the_librarys_other_names`, `a_pattern_swatch_named_after_its_numbered_pattern_skips_the_librarys_names`, `a_nested_pattern_a_library_pattern_brings_skips_the_librarys_names`, `a_nested_pattern_does_not_take_a_name_the_library_gives_a_color`, `a_nested_pattern_leaves_its_name_to_a_library_swatch_that_places_it_otherwise`, `a_pasted_pattern_linked_to_a_copy_of_a_numbered_color_is_found`, `a_new_patterns_swatch_takes_the_library_swatchs_free_name`, `a_new_patterns_swatch_of_an_unnumbered_name_is_named_after_its_pattern`, `a_numbered_name_is_kept_for_the_library_swatch_it_names`, `a_color_a_pattern_brings_again_does_not_reuse_a_copy_the_library_names`, `a_color_a_pattern_brings_reuses_a_copy_that_is_not_the_librarys_namesake`, `alike_gradients_a_pattern_brings_keep_their_names_when_their_color_is_renamed`, `a_pasted_pattern_is_not_reused_by_giving_a_librarys_name_to_another_color`, `a_pattern_pasted_with_add_and_with_merge_is_found_as_the_copy_with_its_colors`, `a_grouped_pattern_swatch_leaves_a_numbered_name_to_the_librarys_color`, `a_grouped_swatch_of_a_reused_pattern_leaves_a_numbered_name_to_the_librarys_color`, `a_grouped_namesake_of_a_pattern_swatch_leaves_it_the_name`, `a_pasted_pattern_is_not_reused_by_taking_a_librarys_name`, `a_pasted_pattern_is_not_reused_by_bringing_back_a_librarys_name`, `a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings`, `a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name that skips the names of the library's other swatches, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it, or when the document deleted it without unlinking the tint. Use Library Item also keeps a library pattern's colors when it adds a copy of one, but its numbered names do not skip the names of the library's other swatches. With Add to Swatches, a swatch of a numbered library name that a pattern's art brings, a tint or gradient included, keeps that name when no swatch or color group in the document uses it, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too. A numbered copy whose name the library gives another swatch, and which is that swatch, is not reused for another color (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `a_library_tint_whose_color_the_document_deleted_brings_the_color_back`, `a_color_a_pattern_brings_skips_the_librarys_numbered_names`, `a_pattern_bringing_a_color_and_its_numbered_namesake_keeps_the_librarys_name`, `a_numbered_tint_or_gradient_a_pattern_brings_keeps_the_librarys_name`, `a_numbered_color_a_pattern_brings_keeps_its_name_beside_a_copy_of_it`, `a_numbered_library_pattern_keeps_its_name`, `a_library_pattern_swatchs_copy_skips_the_librarys_other_names`, `a_pattern_swatch_named_after_its_numbered_pattern_skips_the_librarys_names`, `a_nested_pattern_a_library_pattern_brings_skips_the_librarys_names`, `a_nested_pattern_does_not_take_a_name_the_library_gives_a_color`, `a_nested_pattern_leaves_its_name_to_a_library_swatch_that_places_it_otherwise`, `a_nested_patterns_swatch_takes_the_library_swatchs_free_name`, `a_pasted_pattern_linked_to_a_copy_of_a_numbered_color_is_found`, `a_new_patterns_swatch_takes_the_library_swatchs_free_name`, `a_new_patterns_swatch_of_an_unnumbered_name_is_named_after_its_pattern`, `a_numbered_name_is_kept_for_the_library_swatch_it_names`, `a_color_a_pattern_brings_again_does_not_reuse_a_copy_the_library_names`, `a_color_a_pattern_brings_reuses_a_copy_that_is_not_the_librarys_namesake`, `a_color_a_pattern_brings_does_not_reuse_another_library_colors_copy`, `alike_gradients_a_pattern_brings_keep_their_names_when_their_color_is_renamed`, `a_pasted_pattern_is_not_reused_by_giving_a_librarys_name_to_another_color`, `a_pattern_pasted_with_add_and_with_merge_is_found_as_the_copy_with_its_colors`, `a_grouped_pattern_swatch_leaves_a_numbered_name_to_the_librarys_color`, `a_grouped_swatch_of_a_reused_pattern_leaves_a_numbered_name_to_the_librarys_color`, `a_grouped_namesake_of_a_pattern_swatch_leaves_it_the_name`, `a_pasted_pattern_is_not_reused_by_taking_a_librarys_name`, `a_pasted_pattern_is_not_reused_by_bringing_back_a_librarys_name`, `a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings`, `a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). From 653cc07c45a59e4bae886b74681e3bc65b371994 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 22 Nov 2026 21:55:51 -0800 Subject: [PATCH 54/78] Docs: a library swatch named after its pattern takes the pattern's new name A library swatch named after its pattern takes the name the pattern comes in under when that name differs and no library swatch has it, as pattern_swatch_name in crates/engine/src/cmd/swatchlib.rs gives it. --- docs/mcp.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 84695c589e..3246a43feb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5831,7 +5831,9 @@ same extension and bytes as one there, loads as that User Defined library (categ is refused before it is read. From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, tints, gradients and pattern swatches in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and -art, into the document as a pattern swatch under the library swatch's name and in its color group. A global or spot +art, into the document as a pattern swatch under the library swatch's name and in its color group. A library swatch +named after its pattern instead takes the name the pattern comes in under, when the pattern comes in under another name +that no library swatch has and the swatch does not keep a free numbered name as described below. A global or spot color the pattern's art links to keeps the library's color: when the document gives its name another color, it comes in under a numbered name ("Ink 2") and the pattern links to that. That numbered name, and the numbered names of a pattern swatch and of a pattern the art is painted with, skip the names the library gives its other swatches. A swatch From 6af6b2b13e4e95a6590f819e5e46424546ec653a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 23 Nov 2026 12:16:38 -0800 Subject: [PATCH 55/78] Quick Pen: a length drag shows no Smart Guide from the hover before it A press on a length handle kept the Smart Guides of the hover before it, so a guide or label at the handle stayed on screen for the whole drag. The press now clears them, as a press away from a handle does when it places a point. --- crates/engine/src/tests/quickpen.rs | 22 ++++++++++++++++++++++ crates/tools/src/quickpen.rs | 2 ++ 2 files changed, 24 insertions(+) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index dc660e919b..71f908234e 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -1062,6 +1062,28 @@ fn a_length_drag_shows_no_next_piece() { assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(260.0, 100.0)); } +/// A press on a length handle clears the Smart Guides of the hover before it, so none show during +/// the drag. +#[test] +fn a_length_drag_shows_no_smart_guide() { + let mut s = session(); + s.execute("shape.line", &json!({"x1": 220, "y1": 100, "x2": 220, "y2": 300})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let on = ViewInfo { smart_guides: true, ..Default::default() }; + // The end handle stands on the other line's anchor, so the hover there shows its guide. + s.pointer(&PointerEvent::new(PointerKind::Move, 220.0, 100.0), on).unwrap(); + assert!(!only_points(&mut s, on), "the anchor's guide shows"); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), on).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 140.0), on).unwrap(); + assert!(only_points(&mut s, on), "no guide during the drag: {:?}", s.overlays(on)); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 140.0), on).unwrap(); + let drawn = paths(&s).into_iter().find(|(_, p)| p.subpaths[0].anchors.first().is_some_and(|a| a.p == pt(100.0, 100.0))).unwrap(); + assert_eq!(drawn.1.subpaths[0].anchors.last().unwrap().p, pt(260.0, 100.0)); +} + /// A length drag that would take the path past the canvas leaves it where the drag last put it, /// and the drawing goes on from there. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 23d19bc87e..5b78655707 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -682,6 +682,8 @@ impl QuickPenTool { revision: cx.revision, stale: false, }; + // The hover's Smart Guides do not follow a length drag. + self.snap.clear(); self.length = Some(drag); return vec![]; } From f1ff029c18100cbf952cbdd7f6686e9de0da11b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 00:09:43 -0800 Subject: [PATCH 56/78] Docs: say when a library pattern swatch keeps its color group and takes a numbered name A swatch that names picks on its own comes in ungrouped. A swatch named after its pattern reuses a document swatch that paints the pattern the same way, and takes a numbered copy of the pattern's name when a swatch or color group already uses it. --- docs/mcp.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 3246a43feb..9195b3fc44 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5831,9 +5831,15 @@ same extension and bytes as one there, loads as that User Defined library (categ is refused before it is read. From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, tints, gradients and pattern swatches in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and -art, into the document as a pattern swatch under the library swatch's name and in its color group. A library swatch -named after its pattern instead takes the name the pattern comes in under, when the pattern comes in under another name -that no library swatch has and the swatch does not keep a free numbered name as described below. A global or spot +art, into the document as a pattern swatch under the library swatch's name. The swatch goes into its color group when +`names` is left out or when the first entry of `names` that covers the swatch is its group; when that first entry is +the swatch's own name, the swatch comes in ungrouped. A library swatch named after its +pattern instead takes the name the pattern comes in under, when the pattern comes in under another name that no +library swatch has and the swatch does not keep a free numbered name as described below. For such a swatch, when the +document already has a swatch under any name that paints that pattern placed the same way, that swatch is used and +nothing is added. Otherwise, when a +swatch or color group of the document already uses that name, the swatch comes in under a numbered copy of it +("Tiles 2 2"). A global or spot color the pattern's art links to keeps the library's color: when the document gives its name another color, it comes in under a numbered name ("Ink 2") and the pattern links to that. That numbered name, and the numbered names of a pattern swatch and of a pattern the art is painted with, skip the names the library gives its other swatches. A swatch From ee9b2cfd03d328543c04acf12e08169477d5b4fc Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 14:17:19 -0800 Subject: [PATCH 57/78] Dialogs: rows of controls in dialogs and add-ons are framework Rows and Stacks, so a dialog takes the width of its rows A dialog's custom row drawn as a raw egui layout measured as wide as the room it was offered, so DXF Options, New Swatch, PNG and JPEG Options and Radial Blur opened at the window's full width. The rows in the export options, Save Options, Document Setup, Swatch Options, the effect rows, the Clean Up and color add-ons, the edit toolbar, Edit Original and the preferences file buttons now use Row and Stack. A framework container may run its body more than once in a pass. Presses and picks inside a body are kept in locals and applied after it: the HP-GL pen rows apply Add, Remove and the Pen Table switch once, and the legacy board picker toggles a board once. --- crates/ui-egui/src/addons/cleanup.rs | 7 +- crates/ui-egui/src/addons/color.rs | 12 ++- crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/document_setup.rs | 38 ++++---- crates/ui-egui/src/dialogs/dxf_options.rs | 9 +- crates/ui-egui/src/dialogs/effect_rows.rs | 30 +++--- crates/ui-egui/src/dialogs/eps_options.rs | 19 ++-- crates/ui-egui/src/dialogs/hpgl_options.rs | 95 +++++++++++++------ crates/ui-egui/src/dialogs/png_options.rs | 74 ++++++++------- crates/ui-egui/src/dialogs/save_options.rs | 13 ++- crates/ui-egui/src/dialogs/swatch_options.rs | 23 +++-- .../ui-egui/src/dialogs/tests_custom_rows.rs | 73 ++++++++++++++ crates/ui-egui/src/dialogs/tests_hpgl.rs | 18 ++++ crates/ui-egui/src/edit_toolbar.rs | 5 +- crates/ui-egui/src/original_editor.rs | 25 ++--- crates/ui-egui/src/prefs_dialog/model.rs | 8 +- 16 files changed, 308 insertions(+), 143 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/tests_custom_rows.rs diff --git a/crates/ui-egui/src/addons/cleanup.rs b/crates/ui-egui/src/addons/cleanup.rs index fe68a96d79..8ce1aa6812 100644 --- a/crates/ui-egui/src/addons/cleanup.rs +++ b/crates/ui-egui/src/addons/cleanup.rs @@ -10,6 +10,7 @@ use craft::menu::Node; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::display::{Divider, Text}; +use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; use craft::ui::sections::Section; use egui::Ui; @@ -304,8 +305,8 @@ fn text_tools(ui: &mut Ui, selected: bool, editing: bool, action: &mut Option<Ac if let Some(h) = heading { Text::new(tl!(h).to_string()).show(ui); } - ui.horizontal(|ui| { - for (label, tip, id, p) in buttons { + Row::new().show(ui, |ui, _| { + for (label, tip, id, p) in buttons.clone() { button(ui, label, tip, id, p); } }); @@ -330,7 +331,7 @@ fn results(ui: &mut Ui, r: &mut Results, action: &mut Option<Action>) { if !r.status.is_empty() { Text::new(r.status.clone()).show(ui); } - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { let picked = r.picked_kinds(); let show = push(ui, tl!("Show"), picked.len() == 1, None).is_some(); if show && let [kind] = picked.as_slice() { diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index ec86efd95c..aca41a2620 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -14,6 +14,7 @@ use craft::menu::Node; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; use craft::ui::form::{Field, FieldGroup}; +use craft::ui::layout_components::Row; use craft::ui::pickers::Select; use egui::Ui; use serde_json::{Map, Value, json}; @@ -178,18 +179,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } let (id, params) = st.params(); - let mut command = None; - ui.horizontal(|ui| { + let (mut command, mut reset) = (None, false); + Row::new().show(ui, |ui, _| { if Button::new(tl!("Add as Effect").to_string()).show(ui).clicked() { command = Some("effect.apply"); } if Button::new(tl!("Apply as Filter").to_string()).show(ui).clicked() { command = Some("addon.color.filter"); } - if Button::new(tl!("Reset").to_string()).show(ui).clicked() { - st.values.remove(id); - } + reset = Button::new(tl!("Reset").to_string()).show(ui).clicked(); }); + if reset { + st.values.remove(id); + } // Inks: Duotone's and Print Ink Fixes' dialogs, as their menu items open them. let mut ink = None; crate::panels::section(tl!("Inks").to_string()).show(ui, |ui, _| { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1aae334de1..7ce5c83baa 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -213,6 +213,8 @@ mod tests_raster_formats; #[cfg(test)] mod tests_raster_supplied_options; +#[cfg(test)] +mod tests_custom_rows; #[cfg(test)] mod tests_dxf; #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 17c3b500a6..913d04ca3e 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -20,9 +20,10 @@ use craft::color_ui::display::DisplayTransform; use craft::theme::{Rgba, Srgba}; use craft::ui::buttons::Button; use craft::ui::choice::Swatch; -use craft::ui::contract::{Bind, Entry, Show as _, clicked}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _, clicked}; use craft::ui::dialog::dialog_id; use craft::ui::display::Picture; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::ThumbAspect; use craft::ui::patterns::form_dialogs::{ CustomContext, DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesDialog, PropertiesTab, PropertyRow, @@ -382,27 +383,32 @@ fn grid_colors_row(setup: DocSetup) -> Param { let resolved = grid_colors(&json_map(fields), &setup); let menu: Vec<Entry<String>> = GRID_COLOR_PRESETS.iter().map(|(n, _)| *n).chain(["Custom"]).map(|n| Entry::new(n.to_string(), n.to_string())).collect(); - ui.vertical(|ui| { - let picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); - if let Some((_, pair)) = picked.and_then(|n| GRID_COLOR_PRESETS.iter().find(|(p, _)| *p == n)) { - fields.set("gridColors", entries_value(*pair)); - } - ui.horizontal(|ui| { + let mut picked = None; + let (mut wells, mut edits) = ([None; 2], [None; 2]); + let shown = Stack::new().show(ui, |ui, _| { + picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); + Row::new().show(ui, |ui, _| { for (i, color) in resolved.iter().enumerate() { let name = format!("{} {}", tl!("Grid Colors:"), i + 1); let [r, g, b, _] = color.to_rgba8(1.0); let srgb = Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0); - if Swatch::new(name.clone(), srgb).well().show(ui).clicked { - cx.pick_color(GRID_KEYS[i], srgb); - } - let edited = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).value().copied(); - if let Some(Rgba([r, g, b, _])) = edited { - set_grid_entry(fields, &setup, i, &Color::rgb8(r, g, b)); - } + wells[i] = Swatch::new(name.clone(), srgb).well().show(ui).clicked.then_some(srgb); + edits[i] = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).value().copied(); } }); - }) - .response + }); + if let Some((_, pair)) = picked.and_then(|n| GRID_COLOR_PRESETS.iter().find(|(p, _)| *p == n)) { + fields.set("gridColors", entries_value(*pair)); + } + for (i, (well, edit)) in wells.into_iter().zip(edits).enumerate() { + if let Some(srgb) = well { + cx.pick_color(GRID_KEYS[i], srgb); + } + if let Some(Rgba([r, g, b, _])) = edit { + set_grid_entry(fields, &setup, i, &Color::rgb8(r, g, b)); + } + } + shown.output }) } diff --git a/crates/ui-egui/src/dialogs/dxf_options.rs b/crates/ui-egui/src/dialogs/dxf_options.rs index 4f8218172c..d1a66945ff 100644 --- a/crates/ui-egui/src/dialogs/dxf_options.rs +++ b/crates/ui-egui/src/dialogs/dxf_options.rs @@ -8,7 +8,8 @@ //! options of `document.exportDxf`. OK remembers the options for next time and writes the file //! (asking where when there is no path); bad options keep the dialog open. -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::pickers::Select; use craft::ui::text::NumberField; @@ -142,15 +143,15 @@ pub(crate) fn scale_param(disabled_when: Option<(&str, FieldValue)>) -> Param { let mut unit = fields.text("unit").map_or_else(|| Unit::Millimeters.label().to_string(), str::to_string); let mut scale = Some(fields.number("scale").unwrap_or(1.0)); let (lo, hi) = (*vectorcraft_cad::SCALE_RANGE.start(), *vectorcraft_cad::SCALE_RANGE.end()); - let shown = ui - .horizontal(|ui| { + let shown = Row::new() + .show(ui, |ui, _| { ui.label("1"); Select::new(tl!("Unit"), Bind::bound(&mut unit), &units).show(ui); ui.label("="); NumberField::new(tl!("Scale"), Bind::bound(&mut scale)).range(lo..=hi).show(ui); ui.label(tl!("Units")); }) - .response; + .output; let scale = scale.unwrap_or(1.0); if fields.text("unit") != Some(unit.as_str()) { fields.set("unit", unit); diff --git a/crates/ui-egui/src/dialogs/effect_rows.rs b/crates/ui-egui/src/dialogs/effect_rows.rs index f4e27e317b..580036d430 100644 --- a/crates/ui-egui/src/dialogs/effect_rows.rs +++ b/crates/ui-egui/src/dialogs/effect_rows.rs @@ -6,7 +6,8 @@ use std::ops::RangeInclusive; use craft::behavior::Mixed; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind}; use craft::ui::pickers::Select; use craft::ui::primitives::ContentPainterCx; @@ -198,19 +199,20 @@ pub(super) fn textured(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> { let entries: Vec<Entry<String>> = table.iter().map(|(label, value)| Entry::new((*value).to_owned(), data_label(label))).collect(); let current = fields.text("texture").unwrap_or_default(); let current = table.iter().find(|(_, value)| value.eq_ignore_ascii_case(current)).map_or("", |(_, value)| *value).to_owned(); - ui.horizontal(|ui| { - let picked = Select::new(lbl!("Texture"), Bind::given(current), &entries).show(ui); - if let Some(id) = picked.value().cloned() { - fields.set("texture", id); - } - // The pick is an edit of the rows, which the Appearance panel's editor applies. - cx.gesture(&picked.events); + let mut picked = None; + let shown = Row::new().show(ui, |ui, _| { + picked = Some(Select::new(lbl!("Texture"), Bind::given(current.clone()), &entries).show(ui)); if let Some((w, h)) = size { craft::ui::display::Text::new(format!("{w} × {h} px")).show(ui); } - picked.response - }) - .inner + }); + let Some(picked) = picked else { return shown.output }; + if let Some(id) = picked.value().cloned() { + fields.set("texture", id); + } + // The pick is an edit of the rows, which the Appearance panel's editor applies. + cx.gesture(&picked.events); + picked.response }) .companions([TEXTURE_IMAGE]); let own = ["texture", "texturePath", TEXTURE_IMAGE]; @@ -270,7 +272,7 @@ pub(super) fn radial_blur(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> { let zoom = fields.text("method").is_some_and(|m| m.eq_ignore_ascii_case("zoom")); let mut next = c; let unit: RangeInclusive<f64> = 0.0..=1.0; - let row = ui.horizontal(|ui| { + let row = Row::new().show(ui, |ui, _| { let picker = PointPicker::new(Bind::given([Mixed::Same(c[0]), Mixed::Same(c[1])]), unit.clone(), unit.clone()) .label(lbl!("Blur Center")) .id_salt("point") @@ -279,7 +281,7 @@ pub(super) fn radial_blur(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> { if let Some([Mixed::Same(x), Mixed::Same(y)]) = picker.value().cloned() { next = [x, y]; } - ui.vertical(|ui| { + Stack::new().show(ui, |ui, _| { for (axis, label) in [lbl!("Horizontal"), lbl!("Vertical")].into_iter().enumerate() { let shown = NumberField::new(label, Bind::given(Some(c[axis] * 100.0))) .unit("%") @@ -297,7 +299,7 @@ pub(super) fn radial_blur(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> { fields.set("centerX", center_round(next[0].clamp(0.0, 1.0))); fields.set("centerY", center_round(next[1].clamp(0.0, 1.0))); } - row.response + row.output }) .companions(["centerX", "centerY"]); let rows = generic(cx, fields).into_iter().filter(|p| !matches!(p.key.as_str(), "centerX" | "centerY")); diff --git a/crates/ui-egui/src/dialogs/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 5c8a86007d..2a1ee5ec8b 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -15,8 +15,9 @@ use std::sync::Arc; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Show as _, TooltipSpec}; +use craft::ui::contract::{Bind, Show as _, ShowContainer as _, TooltipSpec}; use craft::ui::dialog::DialogId; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use serde_json::{Map, Value, json}; use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset, fileio}; @@ -76,14 +77,16 @@ fn rows(presets: &Arc<[(String, String)]>) -> Vec<Param> { Param::section(tl!("Transparency")), choice_param("overprints", tl!("Overprints:"), Overprint::ALL.iter().map(|o| (o.id(), o.label()))), Param::custom("flattenerPreset", tl!("Preset:"), move |ui, fields, cx| { - ui.horizontal(|ui| { - let custom = fields.contains("flattener"); + let custom = fields.contains("flattener"); + let mut pressed = false; + let shown = Row::new().show(ui, |ui, _| { flatten::preset_picker(ui, fields, "flattenerPreset", &presets, custom); - if Button::new(tl!("Custom…")).show(ui).clicks > 0 { - cx.request_action("custom"); - } - }) - .response + pressed = Button::new(tl!("Custom…")).show(ui).clicks > 0; + }); + if pressed { + cx.request_action("custom"); + } + shown.output }) .resets(["flattener"]), Param::section(tl!("Fonts")), diff --git a/crates/ui-egui/src/dialogs/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs index 3998523a57..3cfe0ecdfc 100644 --- a/crates/ui-egui/src/dialogs/hpgl_options.rs +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -17,7 +17,7 @@ use craft::ui::buttons::{Button, IconButton}; use craft::ui::choice::{Radio, RadioGroup, Swatch}; use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::dialog::DialogId; -use craft::ui::layout_components::Stack; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog}; use craft::ui::runtime::env::Env; use craft::ui::style::rgba_color; @@ -141,52 +141,88 @@ fn pen_key(i: usize) -> String { /// Pens: One Pen per Color (`pens` null) or Pen Table (`pens` the colors, pen 1's first), with a /// row per pen (its number, color and a Remove button) and Add. fn pens_param() -> Param { - Param::custom("pens", tl!("Pens:"), |ui, fields, cx| ui.vertical(|ui| pens_ui(ui, fields, cx)).response) - .companions([SET_ASIDE, PEN_ERROR]) - .full_width() + Param::custom("pens", tl!("Pens:"), |ui, fields, cx| { + take_picked_pens(fields); + // The rows draw from the values as they stand here and the edits apply after them: the stack's body may run + // twice in a pass. + let mut drawn = fields.clone(); + let mut asked = PensAsked::default(); + let shown = Stack::new().show(ui, |ui, _| { + asked = pens_ui(ui, &drawn, cx); + if let Some(p) = &asked.pens { + drawn.set("pens", FieldValue::Json(Value::Array(p.clone()))); + } + }); + // An edit of the rows in any run of the body is in `drawn`; a switch of Pen Table drops it. + let edited = table(&drawn).filter(|p| asked.table.is_none() && table(fields).as_ref() != Some(p)); + match asked.table { + Some(true) => cx.request_action("penTable"), + Some(false) => { + let _ = set_pen_table(fields, false, || Ok(Vec::new())); + fields.remove(PEN_ERROR); + } + None => {} + } + if let Some(pens) = edited { + fields.set("pens", FieldValue::Json(Value::Array(pens))); + } + shown.output + }) + .companions([SET_ASIDE, PEN_ERROR]) + .full_width() +} + +/// What the pens rows asked for in one run. +#[derive(Default)] +struct PensAsked { + /// Pen Table was turned on (`true`) or off. + table: Option<bool>, + /// The pen table after an edit of its rows. + pens: Option<Vec<Value>>, +} + +/// Writes the colors the picker answered into the pen table. +fn take_picked_pens(fields: &mut DialogFields) { + let Some(mut pens) = table(fields).filter(|a| a.len() <= MAX_PENS) else { return }; + let mut changed = false; + for (i, pen) in pens.iter_mut().enumerate() { + if let Some([r, g, b]) = fields.color(&pen_key(i)) { + let byte = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8; + *pen = json!(format!("#{:02x}{:02x}{:02x}", byte(r), byte(g), byte(b))); + fields.remove(&pen_key(i)); + changed = true; + } + } + if changed { + fields.set("pens", FieldValue::Json(Value::Array(pens))); + } } /// The pens row. Switching to Pen Table asks the host (`penTable`): the table starts from the document's pens, which /// this draw cannot reach. -fn pens_ui(ui: &mut egui::Ui, fields: &mut DialogFields, cx: &mut CustomContext) { - let mut list = table(fields); - let mut changed = false; - // Colours the picker answered. - if let Some(pens) = list.as_mut() { - for (i, pen) in pens.iter_mut().enumerate() { - if let Some([r, g, b]) = fields.color(&pen_key(i)) { - let byte = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8; - *pen = json!(format!("#{:02x}{:02x}{:02x}", byte(r), byte(g), byte(b))); - fields.remove(&pen_key(i)); - changed = true; - } - } - } +fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields, cx: &mut CustomContext) -> PensAsked { + let mut asked = PensAsked::default(); + let list = table(fields); let mut on = list.is_some(); RadioGroup::new(tl!("Pens:"), Bind::bound(&mut on)).show(ui, |ui, _| { Radio::new(false).label(tl!("One Pen per Color")).show(ui); Radio::new(true).label(tl!("Pen Table")).show(ui); }); if on != list.is_some() { - if on { - cx.request_action("penTable"); - } else { - let _ = set_pen_table(fields, false, || Ok(Vec::new())); - fields.remove(PEN_ERROR); - list = None; - } + asked.table = Some(on); } - if let Some(e) = fields.text(PEN_ERROR) { + if let Some(e) = fields.text(PEN_ERROR).filter(|_| asked.table != Some(false)) { let error = rgba_color(Env::of(ui).tokens.tokens().color.status.bad.fg); ui.colored_label(error, crate::i18n::message(crate::i18n::current(), e)); } // A table longer than a plot takes (set through `ui.dialog.set`) draws no rows: OK refuses it. - let Some(mut pens) = list.filter(|a| a.len() <= MAX_PENS) else { return }; + let Some(mut pens) = list.filter(|a| asked.table.is_none() && a.len() <= MAX_PENS) else { return asked }; + let mut changed = false; let n = pens.len(); let mut remove = None; Stack::new().scroll(Scroll::vertical()).room_height(180.0).show(ui, |ui, _| { for (i, pen) in pens.iter_mut().enumerate() { - ui.horizontal(|ui| { + Row::new().id_salt(("hpgl-pen-row", i)).show(ui, |ui, _| { ui.label((i + 1).to_string()); let mut color = pen.as_str().and_then(Rgba::from_hex).unwrap_or(Rgba::rgb(0, 0, 0)); if Swatch::new(tl!("Pen color"), Srgba::from(color)).show(ui).clicked { @@ -216,8 +252,9 @@ fn pens_ui(ui: &mut egui::Ui, fields: &mut DialogFields, cx: &mut CustomContext) changed = true; } if changed { - fields.set("pens", FieldValue::Json(Value::Array(pens))); + asked.pens = Some(pens); } + asked } /// Starts Pen Table for dialog `id`: the table the export would give the art, or the reason it cannot. It runs from diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 00151a7f2c..8bf05fe7d8 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -8,9 +8,10 @@ use craft::theme::{Rgba, Srgba}; use craft::ui::choice::Swatch; -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; use craft::ui::display::Text; use craft::ui::form::SliderField; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::pickers::Select; use craft::ui::runtime::env::UnitKind; @@ -216,25 +217,28 @@ fn resolution_row() -> Param { let preset = RESOLUTIONS.iter().position(|p| *p == ppi).filter(|_| fields.bool("__otherPpi") != Some(true)); let other = RESOLUTION_LABELS.len() - 1; let entries: Vec<Entry<usize>> = RESOLUTION_LABELS.iter().enumerate().map(|(i, label)| Entry::new(i, tl!(*label))).collect(); - ui.horizontal(|ui| { - if let Some(i) = Select::new(tl!("Resolution:"), Bind::given(preset.unwrap_or(other)), &entries).show(ui).value().copied() { - if let Some(p) = RESOLUTIONS.get(i) { - fields.set("ppi", *p); - } - fields.set("__otherPpi", i == other); - } + let (mut picked, mut typed) = (None, None); + let shown = Row::new().show(ui, |ui, _| { + picked = Select::new(tl!("Resolution:"), Bind::given(preset.unwrap_or(other)), &entries).show(ui).value().copied(); if preset.is_none() { let field = NumberField::new(tl!("Resolution:"), Bind::given(Some(ppi))) .range(1.0..=4608.0) .step(1.0) .unit_kind(UnitKind::PixelsPerInch) .show(ui); - if let Some(Some(v)) = field.edit.value().copied() { - fields.set("ppi", v); - } + typed = field.edit.value().copied().flatten(); } - }) - .response + }); + if let Some(i) = picked { + if let Some(p) = RESOLUTIONS.get(i) { + fields.set("ppi", *p); + } + fields.set("__otherPpi", i == other); + } + if let Some(v) = typed { + fields.set("ppi", v); + } + shown.output }) .companions(["__otherPpi"]) .opens_with(72.0) @@ -263,18 +267,21 @@ fn color_choice( let at = ids.iter().position(|v| current.eq_ignore_ascii_case(v)).unwrap_or(ids.len()); let start = first(fields); let entries: Vec<Entry<usize>> = labels.iter().enumerate().skip(start).map(|(i, l)| Entry::new(i, tl!(*l))).collect(); - ui.horizontal(|ui| { - if let Some(i) = Select::new(tl!(label), Bind::given(at.max(start)), &entries).show(ui).value().copied() { - fields.set(key, ids.get(i).copied().unwrap_or(OTHER_COLOR)); + let color = (at == ids.len()).then(|| Srgba::from(Rgba::from_hex(¤t).unwrap_or(Rgba::rgb(128, 128, 128)))); + let (mut picked, mut pick_color) = (None, false); + let shown = Row::new().show(ui, |ui, _| { + picked = Select::new(tl!(label), Bind::given(at.max(start)), &entries).show(ui).value().copied(); + if let Some(color) = color { + pick_color = Swatch::new(tl!(label), color).show(ui).clicked; } - if at == ids.len() { - let color = Srgba::from(Rgba::from_hex(¤t).unwrap_or(Rgba::rgb(128, 128, 128))); - if Swatch::new(tl!(label), color).show(ui).clicked { - cx.pick_color(key, color); - } - } - }) - .response + }); + if let Some(i) = picked { + fields.set(key, ids.get(i).copied().unwrap_or(OTHER_COLOR)); + } + if let Some(color) = color.filter(|_| pick_color) { + cx.pick_color(key, color); + } + shown.output }) } @@ -310,18 +317,17 @@ fn jpeg_rows(screens: bool) -> Vec<Param> { fn quality_row() -> Param { Param::custom("quality", tl!("Quality:"), |ui, fields, _| { let q = (fields.number("quality").unwrap_or(90.0) / 10.0).round().clamp(0.0, 10.0); - ui.horizontal(|ui| { + let mut slid = None; + let shown = Row::new().show(ui, |ui, _| { let out = SliderField::new(tl!("Quality:"), Bind::given(q), 0.0..=10.0).step(1.0).show(ui); - let q = match out.edit.value() { - Some(v) => { - fields.set("quality", v.round() * 10.0); - v.round() - } - None => q, - }; + slid = out.edit.value().map(|v| v.round()); + let q = slid.unwrap_or(q); Text::new(tl!(QUALITY_BANDS.get(q as usize).copied().unwrap_or_default())).show(ui); - }) - .response + }); + if let Some(v) = slid { + fields.set("quality", v * 10.0); + } + shown.output }) .opens_with(90.0) } diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index 921dd8d37f..b65a1f40cb 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -35,7 +35,8 @@ use vectorcraft_eps::{Level, Overprint, Preview}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, CollectionEvent, Show as _, ShowCollection as _, TooltipSpec}; +use craft::ui::contract::{Bind, CollectionEvent, Show as _, ShowCollection as _, ShowContainer as _, TooltipSpec}; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{ThumbAspect, ToggleState}; use craft::ui::notices::Notice; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; @@ -399,10 +400,12 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> let mut boards = picked_boards(fields, n); let before = boards.clone(); let files = board_files(menus.doc.as_deref(), fields.text("path").unwrap_or_default(), &boards); - let response = ui - .vertical(|ui| { + let response = Stack::new() + .show(ui, |ui, _| { + // Each run of the body starts from the checks as they stood: a check flips them, and the body may run twice. + boards.clone_from(&before); ui.label(tl!("A legacy .ai file holds one artboard: each artboard you check is saved as a separate file.")); - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { if Button::new(tl!("Select All")).show(ui).clicks > 0 { boards.iter_mut().for_each(|b| *b = true); } @@ -444,7 +447,7 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> } } }) - .response; + .output; if boards != before || boards_in(fields).is_none() { fields.set("boards", FieldValue::Json(json!(boards))); } diff --git a/crates/ui-egui/src/dialogs/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index cb848e5c85..6def4534d4 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -23,6 +23,7 @@ use craft::ui::choice::Swatch; use craft::ui::contract::{Bind, Show as _, ShowContainer as _}; use craft::ui::dialog::DialogId; use craft::ui::form::Field; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; use craft::ui::text::HexField; @@ -207,10 +208,8 @@ pub(super) fn colour_rows(gamut: Gamut<'static>) -> Vec<Param> { // Spot colours are always global. Param::new("global", tl!("Global").to_owned(), ParamKind::bool(false)).enabled_when("type", "process").disabled_value(true), Param::new("mode", field_label(tl!("Color Mode:")), ParamKind::choice(modes, Some("rgb".to_owned()))), - Param::custom("color", tl!("Color").to_owned(), move |ui, fields, context| { - ui.vertical(|ui| edit_colour(ui, fields, &gamut, context)).response - }) - .companions(["hex", "hsb"]), + Param::custom("color", tl!("Color").to_owned(), move |ui, fields, context| edit_colour(ui, fields, &gamut, context)) + .companions(["hex", "hsb"]), ] } @@ -412,7 +411,7 @@ pub(super) fn correct(app: &mut VectorcraftApp, id: DialogId) { /// The colour row: one slider and value field per component of the dialog's mode, the hex field (RGB, HSB and /// Web), a chip of the colour and under it the mode's warnings. The colour follows the mode: a colour in another /// model is converted when the mode changes. -fn edit_colour(ui: &mut egui::Ui, fields: &mut DialogFields, gamut: &Gamut<'static>, context: &mut CustomContext) { +fn edit_colour(ui: &mut egui::Ui, fields: &mut DialogFields, gamut: &Gamut<'static>, context: &mut CustomContext) -> egui::Response { // A hex colour set from outside the row (automation) replaces the colour once. if let Some(hex) = fields.text("hex").map(str::to_owned) { fields.remove("hex"); @@ -439,8 +438,9 @@ fn edit_colour(ui: &mut egui::Ui, fields: &mut DialogFields, gamut: &Gamut<'stat warnings.push((Warning::Web, ColorWarning::web_colors(tl!("Out of Web Color Warning").to_owned(), Srgba::rgb(r, g, b)))); } let mut edit: Option<(Color, Option<ModelValues>)> = None; - ui.horizontal_top(|ui| { - ui.vertical(|ui| { + let mut actions = Vec::new(); + let shown = Row::new().show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { for (i, ch) in model.channels().iter().enumerate() { let mut rule = ChannelRule::of(ch); if web { @@ -478,21 +478,26 @@ fn edit_colour(ui: &mut egui::Ui, fields: &mut DialogFields, gamut: &Gamut<'stat } } }); - ui.vertical(|ui| { + Stack::new().show(ui, |ui, _| { Swatch::new(tl!("Color").to_owned(), near).show(ui); + actions.clear(); for (warning, chip) in &warnings { if ColorWarningChip::new(chip).show(ui).clicked { - context.request_action(warning.action()); + actions.push(warning.action()); } } }); }); + for action in actions { + context.request_action(action); + } if let Some((c, kept)) = edit { set_color(fields, c); if let Some(k) = kept.filter(|k| k.model == HsbModel.id()) { fields.set("hsb", FieldValue::Json(json!([k.values[0], k.values[1], k.values[2]]))); } } + shown.output } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/tests_custom_rows.rs b/crates/ui-egui/src/dialogs/tests_custom_rows.rs new file mode 100644 index 0000000000..a7bae37aea --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_custom_rows.rs @@ -0,0 +1,73 @@ +//! Dialogs whose custom rows lay out several controls side by side or one under another take the width of their rows, +//! read from the access tree of the window. + +use egui::accesskit::Role; +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::fileio::FORMATS; + +use super::tests::{SCREEN, app, frame, settle}; +use crate::VectorcraftApp; + +/// The width of the dialog named `title` once it has settled. +fn dialog_width(app: &mut VectorcraftApp, title: &str) -> f32 { + settle(app); + let out = frame(app, vec![]); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + let dialog = update.nodes.iter().find(|(_, node)| node.role() == Role::Dialog && node.label() == Some(title)); + let bounds = dialog.and_then(|(_, node)| node.bounds()).unwrap_or_else(|| panic!("the {title} dialog is open")); + (bounds.x1 - bounds.x0) as f32 +} + +/// Writes `value` into `key` of the top dialog, as automation does. +fn set(app: &VectorcraftApp, key: &str, value: Value) { + let ctx = app.ui_ctx.clone().expect("a window app"); + let host = app.dialogs().expect("a dialog host"); + host.with(|h| { + let id = h.open_dialogs().last().map(|d| d.id).expect("an open dialog"); + h.set_json_field(&ctx, id, key, value) + }) + .unwrap(); +} + +/// Opens the options of raster format `id` for an export. +fn raster_options(app: &mut VectorcraftApp, id: &str) { + let f = FORMATS.iter().find(|f| f.id == id).expect("a raster format"); + super::png_options::open(app, f, json!({"format": id, "path": format!("/out/a.{id}")})); +} + +/// A custom row drawn as an egui layout measured as wide as the room the dialog offered it, so the dialog took the +/// window's whole width. Each dialog here holds such a row and stays well inside the window. +#[test] +fn dialogs_with_custom_rows_take_the_width_of_their_rows() { + let half = SCREEN.x / 2.0; + + let mut a = app(); + crate::menus::invoke(&mut a, "ui.dxfOptionsDialog", json!({})); + let dxf = dialog_width(&mut a, "DXF Options"); + + let mut a = app(); + crate::menus::invoke(&mut a, "ui.newSwatch", json!({})); + let swatch = dialog_width(&mut a, "New Swatch"); + + let mut a = app(); + raster_options(&mut a, "png"); + settle(&mut a); + set(&a, "ppi", json!(100)); + set(&a, "__otherPpi", json!(true)); + set(&a, "background", json!("#336699")); + let png = dialog_width(&mut a, "PNG Options"); + + let mut a = app(); + raster_options(&mut a, "jpg"); + let jpeg = dialog_width(&mut a, "JPEG Options"); + + let mut a = app(); + a.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 120, "height": 80})).unwrap(); + a.run("select.all", json!({})).unwrap(); + super::effect::open(&mut a, &json!({"effect": "blur.radial"})).unwrap(); + let blur = dialog_width(&mut a, "Radial Blur"); + + for (name, width) in [("DXF Options", dxf), ("New Swatch", swatch), ("PNG Options", png), ("JPEG Options", jpeg), ("Radial Blur", blur)] { + assert!(width < half, "{name} is {width} pt wide in a {} pt window", SCREEN.x); + } +} diff --git a/crates/ui-egui/src/dialogs/tests_hpgl.rs b/crates/ui-egui/src/dialogs/tests_hpgl.rs index 600e1d8fa2..dab1dbe8c6 100644 --- a/crates/ui-egui/src/dialogs/tests_hpgl.rs +++ b/crates/ui-egui/src/dialogs/tests_hpgl.rs @@ -160,6 +160,24 @@ fn pen_table_starts_from_the_art_s_pens_and_comes_back() { assert_eq!(pens(&fields(&app)), json!(automatic)); } +/// A press of Add adds one pen and a press of One Pen per Color sets the table aside, though the rows' body may run +/// twice in the pass that reads the press. +#[test] +fn pen_rows_apply_each_press_once() { + let (mut app, _) = app(1); + app.run("ui.hpglOptionsDialog", json!({})).unwrap(); + set(&mut app, "pens", json!(["#ff0000", "#000000"])); + frame(&mut app); + press_control(&mut app, json!({"name": "Add", "role": "Button"})); + frame(&mut app); + assert_eq!(pens(&fields(&app)), json!(["#ff0000", "#000000", "#000000"])); + press_control(&mut app, json!({"name": "One Pen per Color", "role": "RadioButton"})); + frame(&mut app); + let d = fields(&app); + assert!(pens(&d).is_null()); + assert_eq!(serde_json::to_value(d.get("__pens")).unwrap(), json!(["#ff0000", "#000000", "#000000"])); +} + /// Pen Table with options the export refuses keeps One Pen per Color and says why, rather than /// starting from one black pen that the corrected options would keep. #[test] diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index 3150baae30..c9fbd71eb0 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -22,7 +22,8 @@ use std::sync::OnceLock; use craft::behavior::IconId; use craft::behavior::overlay::Side; use craft::ui::buttons::ToggleButton; -use craft::ui::contract::{Bind, Outcome as _, Show as _}; +use craft::ui::contract::{Bind, Outcome as _, Show as _, ShowContainer as _}; +use craft::ui::layout_components::Row; use craft::ui::menu::PanelRow; use craft::ui::primitives::IconSpec; use craft::ui::rails::{DrawerGroup, DropAt, SlotId, ToolRailOutput, ToolSlot, ToolbarDrawer, ToolbarEdit}; @@ -456,7 +457,7 @@ pub(crate) fn drawer(app: &mut VectorcraftApp, ui: &mut Ui, rail_out: &ToolRailO if target.is_some() { return; } - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { for (name, label, icon) in crate::state::ToolbarShow::CONTROLS { let on = shown.get(name); let button = ToggleButton::new(tl!(label), Bind::given(on)).icon(IconSpec::svg(IconId::new(icon))).icon_only(); diff --git a/crates/ui-egui/src/original_editor.rs b/crates/ui-egui/src/original_editor.rs index 5888f2fa26..9089ede4f2 100644 --- a/crates/ui-egui/src/original_editor.rs +++ b/crates/ui-egui/src/original_editor.rs @@ -5,8 +5,9 @@ use std::path::Path; use craft::host::{Host, PickId, PickRequest}; use craft::ui::buttons::Button; -use craft::ui::contract::{Props as _, Show as _}; +use craft::ui::contract::{Props as _, Show as _, ShowContainer as _}; use craft::ui::display::Text; +use craft::ui::layout_components::Row; use serde::{Deserialize, Serialize}; use crate::VectorcraftApp; @@ -118,19 +119,21 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, enabled: bool) { { app.status(e); } - ui.horizontal_wrapped(|ui| { + let chosen = app.original_editor.choice.path.clone(); + let (mut choose, mut default) = (false, false); + Row::new().wrap(true).show(ui, |ui, _| { Text::new(tl!("Edit Original with:")).show(ui); - let name = app.original_editor.choice.path.as_deref().and_then(|p| Path::new(p).file_name()); + let name = chosen.as_deref().and_then(|p| Path::new(p).file_name()); Text::new(name.map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "PhotoCraft".into())).show(ui); - if Button::new(tl!("Choose…")).enabled(enabled).show(ui).clicked() - && let Err(e) = pick(app) - { - app.status(e); - } - if app.original_editor.choice.path.is_some() && Button::new("PhotoCraft").enabled(enabled).show(ui).clicked() { - reset(app); - } + choose = Button::new(tl!("Choose…")).enabled(enabled).show(ui).clicked(); + default = chosen.is_some() && Button::new("PhotoCraft").enabled(enabled).show(ui).clicked(); }); + if choose && let Err(e) = pick(app) { + app.status(e); + } + if default { + reset(app); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index 72c5ec628c..b4693d5830 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -8,8 +8,9 @@ use std::sync::{Mutex, PoisonError}; use craft::host::{PickKind, PickRequest}; use craft::theme::Rgba; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; use craft::ui::form::{SliderField, SliderFieldLayout}; +use craft::ui::layout_components::Row; use craft::ui::patterns::preferences::{GroupSpec, PageSpec, PathSetting, PrefValue, PreferencesDraft, PreferencesModel, RowKind, RowSpec}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use serde_json::{Map, Value, json}; @@ -350,10 +351,11 @@ impl PreferencesModel for Live<'_> { } "prefsFile" => { let (mut export, mut import, mut reset) = (false, false, false); - ui.horizontal_wrapped(|ui| { + let web = crate::io::is_web(self.app); + Row::new().wrap(true).show(ui, |ui, _| { export = Button::new(tl!("Export Preferences…")).show(ui).clicked(); // Not on the web, whose open dialog answers with the file's contents, not a path to import. - if !crate::io::is_web(self.app) { + if !web { import = Button::new(tl!("Import Preferences…")).show(ui).clicked(); } reset = Button::new(tl!("Reset Preferences")).show(ui).clicked(); From 0ac526a475f1a463f5f8b3487404a6e59b07befe Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 14:45:18 -0800 Subject: [PATCH 58/78] Recolor Artwork: the row arrows draw, and a test checks that icon ids resolve The recolor and exclude toggle on each Recolor Artwork row asked for the icons dc-recolor-arrow and dc-recolor-arrow-off, which no icon set had, so the button drew nothing. The two icons are added: a right arrow for a row that is recolored and a dashed line without a head for a row that is excluded, each with its ASSETS.md row and icon_data.rs entry. A new test, icons::tests::every_icon_id_literal_and_panel_icon_resolves, reads the crate's source and checks that every icon id written as a literal or a const, and every icon panel's and dock tab's icon, resolves in the icon catalog or the app's own set. It fails without the two icons. --- ASSETS.md | 2 + assets/icons/dc-recolor-arrow-off.svg | 1 + assets/icons/dc-recolor-arrow.svg | 1 + crates/ui-egui/src/dialogs/recolor.rs | 2 - crates/ui-egui/src/icon_data.rs | 2 + crates/ui-egui/src/icons.rs | 66 +++++++++++++++++++++++++++ 6 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 assets/icons/dc-recolor-arrow-off.svg create mode 100644 assets/icons/dc-recolor-arrow.svg diff --git a/ASSETS.md b/ASSETS.md index a483174dc1..4adfb581b1 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -248,6 +248,8 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-puppet.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-quick-pen.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a line and a half circle with a dot at each point) | MIT OR Apache-2.0 | | | `assets/icons/dc-rearrange.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-recolor-arrow.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a right arrow, a Recolor Artwork row that is recolored) | MIT OR Apache-2.0 | | +| `assets/icons/dc-recolor-arrow-off.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a dashed line without a head, a Recolor Artwork row that is excluded) | MIT OR Apache-2.0 | | | `assets/icons/dc-rect-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-rect-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-reference-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/assets/icons/dc-recolor-arrow-off.svg b/assets/icons/dc-recolor-arrow-off.svg new file mode 100644 index 0000000000..9a972d3804 --- /dev/null +++ b/assets/icons/dc-recolor-arrow-off.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 12H21" stroke-dasharray="3 3"/></svg> diff --git a/assets/icons/dc-recolor-arrow.svg b/assets/icons/dc-recolor-arrow.svg new file mode 100644 index 0000000000..41dd50e3be --- /dev/null +++ b/assets/icons/dc-recolor-arrow.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 12H20.5"/><path d="M15 6.5L20.5 12L15 17.5"/></svg> diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index fb8aea7c51..c6c9f72d3d 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -212,8 +212,6 @@ const ARROW: ColumnKey = ColumnKey::new("arrow"); const NEW: ColumnKey = ColumnKey::new("new"); const HEX: ColumnKey = ColumnKey::new("hex"); /// The arrow of a row that is recolored, and of one that is excluded (a dashed line without a head). -// PLAN: assumed icons `dc-recolor-arrow` and `dc-recolor-arrow-off` (VectorCraft's own solid and dashed arrows); -// the assets owner draws them and adds them to `assets/icons`, `icon_data.rs` and `ASSETS.md`. const ARROW_ON: &str = "dc-recolor-arrow"; const ARROW_OFF: &str = "dc-recolor-arrow-off"; diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index bf76005b9e..d76e54f3ab 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -160,6 +160,8 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-puppet", include_bytes!("../../../assets/icons/dc-puppet.svg")), ("dc-quick-pen", include_bytes!("../../../assets/icons/dc-quick-pen.svg")), ("dc-rearrange", include_bytes!("../../../assets/icons/dc-rearrange.svg")), + ("dc-recolor-arrow", include_bytes!("../../../assets/icons/dc-recolor-arrow.svg")), + ("dc-recolor-arrow-off", include_bytes!("../../../assets/icons/dc-recolor-arrow-off.svg")), ("dc-rect-cut", include_bytes!("../../../assets/icons/dc-rect-cut.svg")), ("dc-rect-grid", include_bytes!("../../../assets/icons/dc-rect-grid.svg")), ("dc-reference-point", include_bytes!("../../../assets/icons/dc-reference-point.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 85f8a5e701..4fda81a8c7 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -114,6 +114,72 @@ mod tests { has_icon(&IconId::new(name)) } + /// The ways a source line writes an icon id as a literal; a `const` that holds one is read by `const_icon`. + const FORMS: [&str; 3] = ["IconId::new(\"", "icon(\"", "icon = \""]; + + /// The id a `const NAME: &str = "<id>"` line declares, when `NAME` ends in `ICON` or `code` passes it to + /// `IconId::new(NAME)`. + fn const_icon<'a>(line: &'a str, code: &str) -> Option<&'a str> { + let rest = line.trim_start().trim_start_matches("pub ").trim_start_matches("pub(crate) ").strip_prefix("const ")?; + let (name, after) = rest.split_once(':')?; + if name.is_empty() || !name.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') { + return None; + } + if !name.ends_with("ICON") && !code.contains(&format!("IconId::new({name})")) { + return None; + } + after.trim_start().strip_prefix("&str")?.split_once("= \"")?.1.split('"').next() + } + + /// An id that no set has draws nothing and raises no error at build time. Every icon id this crate's code + /// writes as a literal or a `const`, and every icon panel's and dock tab's icon, resolves in the catalog or the + /// app's set. Other ids built in match arms and tuple tables are not scanned. + #[test] + fn every_icon_id_literal_and_panel_icon_resolves() { + register_app_icons(&APP_ICONS); + let resolves = |id: &str| has_icon(&IconId::from(std::borrow::Cow::Owned(id.to_owned()))); + let (mut seen, mut unknown) = (0, Vec::new()); + let mut stack = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")]; + while let Some(dir) = stack.pop() { + let entries = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())); + for entry in entries { + let path = entry.unwrap_or_else(|e| panic!("{}: {e}", dir.display())).path(); + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); + if path.is_dir() { + if name != "tests" { + stack.push(path); + } + continue; + } + if !name.ends_with(".rs") || name.starts_with("tests") { + continue; + } + let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + // Code up to the test module: a test harness's `icon("..")` names a panel, not an icon. + let code = text.find("#[cfg(test)]\nmod ").map_or(text.as_str(), |at| &text[..at]); + for (number, line) in code.lines().enumerate().filter(|(_, l)| !l.trim_start().starts_with("//")) { + let literal = |form: &&str| { + line.match_indices(*form).filter_map(|(at, form)| line[at + form.len()..].split('"').next()).collect::<Vec<_>>() + }; + for id in FORMS.iter().flat_map(literal).chain(const_icon(line, code)) { + seen += 1; + if !resolves(id) { + unknown.push(format!("{}:{}: {id:?}", path.display(), number + 1)); + } + } + } + } + } + assert!(seen > 50, "the source scan found only {seen} icon ids"); + let tabs = crate::state::DockTab::ALL.map(crate::state::DockTab::info); + for (panel, _, icon) in crate::state::ICON_PANELS.iter().chain(tabs.iter()) { + if !resolves(icon) { + unknown.push(format!("panel {panel}: {icon:?}")); + } + } + assert!(unknown.is_empty(), "icon ids that no set has: {unknown:#?}"); + } + /// Appearance (effects) and Pathfinder both lived in the icon column; they used the same /// overlapping-squares motif (storytold/vectorcraft#2681). #[test] From 79f5165ed1289e8154952642dd6957b4648aef43 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 23 Nov 2026 21:55:29 -0800 Subject: [PATCH 59/78] Previews: hand-drawn previews take the theme's sizes, colors and stroke widths - Paintbrush, Blob Brush and Eraser options: the tip dabs draw in a framework picture at the small sample size, in the muted and normal text colors. - Calligraphic Brush options: the nib preview's paper, nib and guide grays draw as data colors, its guides at the thin stroke width. - Graphic Styles: the large tip's texture, and the white tile a thumbnail shows before it loads, draw through the framework painter. - 3D Classic: Map Art's preview takes the plot size and item gap; the track cube and Map Art share one set of documented surface grays. - Transparency: the object thumbnail's fill draws as a data color, and a disabled mask's cross at the thick stroke width. - Swatches: None's slash and a disabled mask's cross share one red, drawn as a data color at the medium and thick stroke widths. - Revolve gizmo: the axis letters, light labels and readouts are text runs in the label type role, and an axis letter's plate grows with the letter. --- crates/ui-egui/src/dialogs/brush_options.rs | 32 +++++++---- crates/ui-egui/src/dialogs/freehand.rs | 48 +++++++++-------- crates/ui-egui/src/dialogs/revolve_gizmo.rs | 53 +++++++++++++------ crates/ui-egui/src/dialogs/three_d_classic.rs | 10 ++-- crates/ui-egui/src/dialogs/track_cube.rs | 13 +++-- crates/ui-egui/src/panels/graphic_styles.rs | 21 +++++--- crates/ui-egui/src/panels/swatches.rs | 18 ++++--- crates/ui-egui/src/panels/transparency.rs | 17 +++--- 8 files changed, 138 insertions(+), 74 deletions(-) diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index 19cf5a251a..4d66df8ecb 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -34,7 +34,7 @@ use craft::ui::layout_components::Row; use craft::ui::list::{ThumbAspect, ThumbSize}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::pickers::Select; -use craft::ui::primitives::ContentPainterCx; +use craft::ui::primitives::{ContentPainterCx, StrokeWidth}; use craft::ui::runtime::env::{Label, UnitKind}; use craft::ui::text::NumberField; use egui::{Color32, Rect, Stroke, pos2, vec2}; @@ -612,14 +612,26 @@ pub(super) fn stroke_preview(cx: &ContentPainterCx, rect: Rect, doc: Option<&Doc crate::panels::brushes::paint_definition(cx, rect, doc, &Value::Object(def)); } +/// The nib preview's paper, white like the brush previews'. +const NIB_PAPER: Color32 = Color32::WHITE; +/// The nib at the brush's values, black on the paper. +const NIB_INK: Color32 = Color32::BLACK; +/// The nib preview's center lines, a light gray on its white paper. +const NIB_GUIDE: Color32 = Color32::from_gray(220); +/// The nib preview's lightest and heaviest nibs, in a gray behind the black nib at the brush's values. +const NIB_RANGE: Color32 = Color32::from_gray(200); +/// The room the nib preview keeps between its largest nib and each edge, in points. +const NIB_MARGIN: f32 = 6.0; + /// The nib of `c` at its values (black), and — for values that vary — at their lightest and /// heaviest (grey), on white like the brush previews, its largest nib filling the box. fn nib_preview(cx: &ContentPainterCx, r: Rect, c: &Calligraphic) { - let p = &cx.painter; - p.rect_filled(r, 0.0, Color32::WHITE); - let guide = Stroke::new(1.0, Color32::from_gray(220)); - p.line_segment([pos2(r.left(), r.center().y), pos2(r.right(), r.center().y)], guide); - p.line_segment([pos2(r.center().x, r.top()), pos2(r.center().x, r.bottom())], guide); + let guide = Stroke::new(cx.stroke_width(StrokeWidth::Thin), NIB_GUIDE); + cx.data_shapes([ + egui::Shape::rect_filled(r, 0.0, NIB_PAPER), + egui::Shape::line_segment([pos2(r.left(), r.center().y), pos2(r.right(), r.center().y)], guide), + egui::Shape::line_segment([pos2(r.center().x, r.top()), pos2(r.center().x, r.bottom())], guide), + ]); let values = [c.angle, c.roundness, c.size]; let at = |sign: f64| -> [f64; 3] { let mut v = values; @@ -633,9 +645,10 @@ fn nib_preview(cx: &ContentPainterCx, r: Rect, c: &Calligraphic) { }; let nibs = [at(-1.0), at(1.0), values]; let largest = nibs.iter().map(|n| n[2]).fold(0.0, f64::max).max(1e-6); - let scale = (r.height().min(r.width()) - 12.0) / largest as f32; + let scale = (r.height().min(r.width()) - 2.0 * NIB_MARGIN) / largest as f32; + let mut shapes = Vec::with_capacity(nibs.len()); for (k, [angle, round, size]) in nibs.into_iter().enumerate() { - let fill = if k < 2 { Color32::from_gray(200) } else { Color32::BLACK }; + let fill = if k < 2 { NIB_RANGE } else { NIB_INK }; let (a, b) = ((size as f32 * scale / 2.0).max(0.5), (size * round.clamp(1.0, 100.0) / 100.0) as f32 * scale / 2.0); let th = (angle as f32).to_radians(); let (u, v) = (vec2(th.cos(), -th.sin()), vec2(th.sin(), th.cos())); @@ -645,8 +658,9 @@ fn nib_preview(cx: &ContentPainterCx, r: Rect, c: &Calligraphic) { r.center() + u * (a * s.cos()) + v * (b.max(0.5) * s.sin()) }) .collect(); - p.add(egui::Shape::convex_polygon(pts, fill, Stroke::NONE)); + shapes.push(egui::Shape::convex_polygon(pts, fill, Stroke::NONE)); } + cx.data_shapes(shapes); } /// OK: edit the brush (and rename it). A name another brush has, or a new bristle brush name that diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 32d780bddb..d4b411dc90 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -21,10 +21,12 @@ // of the draw crate is where `TipEllipse` and `TipAngle` live. use craft::draw::ui::brush_settings::{TipAngle, TipEllipse}; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::display::{Picture, PictureSize}; use craft::ui::layout_components::Row; +use craft::ui::list::{ThumbAspect, ThumbSize}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; -use craft::ui::runtime::env::{Env, UnitKind}; -use craft::ui::style::rgba_color; +use craft::ui::primitives::{ContentPainterCx, PaintShape}; +use craft::ui::runtime::env::UnitKind; use craft::ui::text::NumberField; use craft::ui::value_drag::{Slider, SliderScale}; use egui::{Response, Ui}; @@ -69,9 +71,6 @@ const KEYS: [&str; 18] = [ /// and the field takes up to 100. const FIDELITY_MAX: f64 = 20.0; -/// Half the length of a tip in its dabs, in points. -const DAB_LONG: f32 = 18.0; - /// Fidelity `v` stepped `n` steps by the slider's and the field's keys: an arrow steps hundredths up to 0.1, /// tenths up to 1 and whole units above, in the tool's unit (a step down from 0.1 or 1 takes the finer step below /// it); ten steps at once (Shift with an arrow, Page Up/Down) multiply or divide by ten, so they go @@ -175,27 +174,34 @@ fn tip_row(ui: &mut Ui, fields: &mut DialogFields, least: f64) -> Response { shown.output } -/// Three dabs of `tip`, as a stroke of it lays them down. -// PLAN: a `Picture::painter` replaces the plain allocation once its `ThumbAspect` is known to this set. +/// Three dabs of `tip`, as a stroke of it lays them down: a picture seven tip halves wide and two high, at the +/// small sample size, each dab as long as the picture is high. fn dabs(ui: &mut Ui, tip: TipAngle) { - let tokens = Env::of(ui).tokens.clone(); - let (dim, ink) = (rgba_color(tokens.color.text.muted), rgba_color(tokens.color.text.normal)); - let long = DAB_LONG; - let (response, painter) = ui.allocate_painter(egui::vec2(7.0 * long, 2.0 * long), egui::Sense::hover()); + // Decorative: the Tip control beside it is the row's accessible control. + Picture::painter("", ThumbAspect::new(7, 2), move |cx, rect| paint_dabs(cx, rect, tip)).extent(PictureSize::Sample(ThumbSize::Small)).show(ui); +} + +/// Paints three dabs of `tip` across `rect`, the middle one in the text color and the outer two in the muted one. +fn paint_dabs(cx: &ContentPainterCx<'_>, rect: egui::Rect, tip: TipAngle) { + let style = cx.style_cx(); + let (dim, ink) = (style.color(style.tokens.color.text.muted), style.color(style.tokens.color.text.normal)); + let long = rect.height() / 2.0; let a = tip.degrees.clamp(-180.0, 180.0).to_radians(); let u = egui::vec2(a.cos() as f32, -a.sin() as f32); let v = egui::vec2(-u.y, u.x); let short = long * (tip.roundness.clamp(0.0, 1.0) as f32).max(0.001); - for (i, color) in [dim, ink, dim].into_iter().enumerate() { - let center = egui::pos2(response.rect.min.x + long + i as f32 * 2.5 * long, response.rect.center().y); - let points = (0..32) - .map(|k| { - let s = std::f32::consts::TAU * k as f32 / 32.0; - center + u * (long * s.cos()) + v * (short * s.sin()) - }) - .collect(); - painter.add(egui::Shape::convex_polygon(points, color, egui::Stroke::NONE)); - } + cx.with_draw(|draw| { + for (i, color) in [dim, ink, dim].into_iter().enumerate() { + let center = egui::pos2(rect.min.x + long + i as f32 * 2.5 * long, rect.center().y); + let points = (0..32) + .map(|k| { + let s = std::f32::consts::TAU * k as f32 / 32.0; + center + u * (long * s.cos()) + v * (short * s.sin()) + }) + .collect(); + draw.fill(&PaintShape::Polygon(points), color); + } + }); } /// The rows of tool `tool`'s dialog: those of `present` (the option keys the tool reports), in the order the diff --git a/crates/ui-egui/src/dialogs/revolve_gizmo.rs b/crates/ui-egui/src/dialogs/revolve_gizmo.rs index 3ef06cecef..7afd12ac16 100644 --- a/crates/ui-egui/src/dialogs/revolve_gizmo.rs +++ b/crates/ui-egui/src/dialogs/revolve_gizmo.rs @@ -19,9 +19,10 @@ use craft::ui::contract::{ Remember as _, Role, Show as _, }; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog}; +use craft::ui::primitives::{ContentPainterCx, TextRun}; use craft::ui::runtime::focus::KeyUse; -use craft::ui::style::{ComponentStyle, StyleColor, StyleCx}; -use egui::{Align2, FontId, Painter, Pos2, Rect, Response, Stroke, Ui, Vec2, vec2}; +use craft::ui::style::{ComponentStyle, StyleColor, StyleCx, TypeRole}; +use egui::{Painter, Pos2, Rect, Response, Stroke, Ui, Vec2, vec2}; use serde_json::json; use vectorcraft_effects::{CLASSIC_REVOLVE, REVOLVE}; use vectorcraft_geom::Point; @@ -39,6 +40,8 @@ const RING_REACH: f32 = 9.0; const ORBIT_REACH: f32 = 14.0; /// How far from the light's handle a press takes it, in points. const LIGHT_REACH: f32 = 18.0; +/// The least radius of the plate under an axis letter, in points; a taller letter gets a plate as tall as its line. +const AXIS_PLATE: f32 = 9.0; const RING: PartKey = PartKey::new("ring"); const CENTRE: PartKey = PartKey::new("centre"); @@ -568,6 +571,7 @@ impl Component for RevolveGizmo<'_> { let Some(g) = Geometry::new(&space.view, &self.subject.fields, self.subject.bounds) else { return }; let content = ui.content_painter(cx); let paint = Paint { + content: &content, painter: &content.painter, style: cx.style, view: &space.view, @@ -606,6 +610,8 @@ fn light_position(g: Geometry, options: Revolve) -> Pos2 { /// What a pass draws with. struct Paint<'a> { + /// The content painter, which lays out and paints the labels. + content: &'a ContentPainterCx<'a>, painter: &'a Painter, style: &'a RevolveGizmoStyle, view: &'a CanvasView, @@ -623,7 +629,8 @@ impl Paint<'_> { let (g, s, painter) = (self.g, self.style, self.painter); for (axis, ring) in g.rings.iter().enumerate() { let hot = self.active == Some(axis); - let color = if hot { s.hot.egui() } else { s.axis(axis).egui() }; + let ink = if hot { s.hot } else { s.axis(axis) }; + let color = ink.egui(); for i in 0..SAMPLES { let angle = i as f32 * std::f32::consts::TAU / SAMPLES as f32; let behind = ring.depth[0] * angle.cos() + ring.depth[1] * angle.sin() < -0.05; @@ -641,8 +648,10 @@ impl Paint<'_> { _ => 4.7, }; let p = g.center + ring.point(phase); - painter.circle_filled(p, 9.0, s.plate.egui()); - painter.text(p, Align2::CENTER_CENTER, ["X", "Y", "Z"][axis], FontId::proportional(11.0), color); + self.text(["X", "Y", "Z"][axis], ink, |size| { + painter.circle_filled(p, (size.max_elem() * 0.5).max(AXIS_PLATE), s.plate.egui()); + p - size * 0.5 + }); } painter.circle(g.center, 8.0, s.plate.egui().gamma_multiply(0.8), Stroke::new(1.5, s.muted.egui())); painter.line_segment([g.center - vec2(4.0, 0.0), g.center + vec2(4.0, 0.0)], Stroke::new(1.0, s.muted.egui())); @@ -654,7 +663,7 @@ impl Paint<'_> { if let Some(Mode::Ring { axis, .. }) = self.dragging { let degrees = self.values.rotation.get(axis).copied().unwrap_or(0.0); let text = format!("{} {degrees:.1}°", ["X", "Y", "Z"].get(axis).unwrap_or(&"")); - self.readout(text, g.center + vec2(0.0, g.radius * 1.12 + 18.0), 12.0); + self.readout(&text, g.center + vec2(0.0, g.radius * 1.12 + 18.0)); } } @@ -682,7 +691,7 @@ impl Paint<'_> { let label = labels[axis]; painter.rect_filled(label, 4.0, if self.active == Some(axis) { s.plate_hover.egui() } else { s.plate.egui() }); let text = if axis == 0 { tl!("Rotation") } else { tl!("Height") }; - painter.text(label.center(), Align2::CENTER_CENTER, text, FontId::proportional(11.0), s.hot.egui()); + self.text(text, s.hot, |size| label.center() - size * 0.5); } let p = light_position(g, options); let delta = g.center - p; @@ -710,22 +719,34 @@ impl Paint<'_> { painter.line_segment([p + direction * 13.0, p + direction * 17.0], Stroke::new(1.5, s.hot.egui())); } let name = crate::i18n::tr_ctx(crate::i18n::current(), "lighting", "Light"); - let galley = painter.layout_no_wrap(name.to_string(), FontId::proportional(11.0), s.hot.egui()); - let name_pos = p - vec2(galley.size().x * 0.5, 25.0 + galley.size().y); - painter.rect_filled(Rect::from_min_size(name_pos - vec2(4.0, 2.0), galley.size() + vec2(8.0, 4.0)), 3.0, s.plate.egui()); - painter.galley(name_pos, galley, s.hot.egui()); + self.text(name, s.hot, |size| { + let name_pos = p - vec2(size.x * 0.5, 25.0 + size.y); + painter.rect_filled(Rect::from_min_size(name_pos - vec2(4.0, 2.0), size + vec2(8.0, 4.0)), 3.0, s.plate.egui()); + name_pos + }); if self.dragging.is_some() { let text = format!("{} {:.1}° {} {:.1}°", tl!("Rotation"), self.values.light_rotation, tl!("Height"), self.values.light_height); - self.readout(text, g.center + vec2(0.0, radius + 56.0), 11.5); + self.readout(&text, g.center + vec2(0.0, radius + 56.0)); } } /// `text` on a plate centred at `at`. - fn readout(&self, text: String, at: Pos2, size: f32) { + fn readout(&self, text: &str, at: Pos2) { let (s, painter) = (self.style, self.painter); - let galley = painter.layout_no_wrap(text, FontId::proportional(size), s.ink.egui()); - painter.rect_filled(Rect::from_center_size(at, galley.size() + vec2(14.0, 8.0)), 4.0, s.plate.egui()); - painter.galley(at - galley.size() * 0.5, galley, s.ink.egui()); + self.text(text, s.ink, |size| { + painter.rect_filled(Rect::from_center_size(at, size + vec2(14.0, 8.0)), 4.0, s.plate.egui()); + at - size * 0.5 + }); + } + + /// Paints `text` in the label type role and `color` at the top left `place` gives for its size; `place` may paint + /// what goes under the text. + fn text(&self, text: &str, color: StyleColor, place: impl FnOnce(Vec2) -> Pos2) { + self.content.with_draw(|draw| { + let layout = draw.layout(&TextRun::new(text).role(TypeRole::Label).color(color), f32::INFINITY); + let at = place(layout.size()); + draw.galley(at, &layout); + }); } } diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 390c536503..1e520556fb 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -18,7 +18,7 @@ use craft::ui::list::ThumbAspect; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind}; use craft::ui::pickers::Select; use craft::ui::primitives::ContentPainterCx; -use craft::ui::runtime::env::UnitKind; +use craft::ui::runtime::env::{Env, UnitKind}; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::style::DataColor; use craft::ui::text::NumberField; @@ -32,6 +32,7 @@ use vectorcraft_effects::{ use super::revolve::{Place, bevel_row, c3, light_editor}; use super::three_d::{Data, with_fields}; +use super::track_cube::{SHADE_DARK, SHADE_LIGHT}; use crate::VectorcraftApp; /// The field that holds the number of the surface Map Art shows. @@ -379,10 +380,11 @@ pub(crate) fn map_done(dialog: &mut HostedParamDialog, effect: &str) { fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response { let surface = surface_number(fields); let map = maps_of(fields).into_iter().find(|m| m.surface == surface); - let size = vec2(ui.available_width().max(ui.spacing().slider_width), ui.spacing().slider_width); // PLAN: tokens.size.plot + let tokens = Env::of(ui).tokens.clone(); + let size = vec2(ui.available_width().max(tokens.size.plot.width), tokens.size.plot.height); let (room, response) = ui.allocate_exact_size(size, Sense::hover()); let (width, height) = (flat.width.max(1e-6), flat.height.max(1e-6)); - let margin = f64::from(ui.spacing().item_spacing.x) * 2.0; + let margin = f64::from(tokens.space.gap.item) * 2.0; let zoom = ((f64::from(room.width()) - margin) / width).min((f64::from(room.height()) - margin) / height).max(1e-6); let view = CanvasView::new(room, Point::ZERO, zoom); let rect = flat.art.map(art_rect); @@ -390,7 +392,7 @@ fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response { Canvas::new(tl!("Surface")).view(view).show_at(ui, room, |ui, body| { let corner = |x: f64, y: f64| view.to_screen(Point::new(x, y)); let page = egui::Rect::from_two_pos(corner(-width / 2.0, -height / 2.0), corner(width / 2.0, height / 2.0)); - let fill = if flat.visible { Color32::from_gray(205) } else { Color32::from_gray(90) }; + let fill = if flat.visible { SHADE_LIGHT } else { SHADE_DARK }; if let Some(space) = canvas_space(&body.env) { space.paint_picture(ui.ctx(), vec![egui::Shape::rect_filled(page, 0.0, fill)]); } diff --git a/crates/ui-egui/src/dialogs/track_cube.rs b/crates/ui-egui/src/dialogs/track_cube.rs index 80d3a2746f..c920e48708 100644 --- a/crates/ui-egui/src/dialogs/track_cube.rs +++ b/crates/ui-egui/src/dialogs/track_cube.rs @@ -22,6 +22,12 @@ const CUBE_BOX: f32 = 124.0; const CUBE_HALF: f32 = 25.0; const RING_IN: f32 = 47.0; const RING_OUT: f32 = 60.0; +/// The grays the 3D dialogs shade a surface with, the same in every theme: light for the cube's top and bottom faces +/// and a Map Art surface the viewer sees, mid for the cube's left and right faces, and dark for its back face and a +/// hidden Map Art surface. +pub(super) const SHADE_LIGHT: Color32 = Color32::from_gray(205); +pub(super) const SHADE_MID: Color32 = Color32::from_gray(155); +pub(super) const SHADE_DARK: Color32 = Color32::from_gray(90); /// How far an edge reaches for the pointer (points). const EDGE_REACH: f32 = 5.0; /// Degrees one point of pointer movement turns the cube. @@ -425,12 +431,11 @@ fn paint_cube(painter: &egui::Painter, s: &RowStyle, rect: Rect, m: M3, active: if !face_visible(m, axis, side) { continue; } - // PLAN: the gray steps are literals; the data tokens of area plan §2 w3 were not visible to this writer. let fill = match (axis, side) { (2, true) => colors[2], - (2, false) => Color32::from_gray(90), - (1, _) => Color32::from_gray(205), - _ => Color32::from_gray(155), + (2, false) => SHADE_DARK, + (1, _) => SHADE_LIGHT, + _ => SHADE_MID, }; let points: Vec<Pos2> = face_corners(axis, side).iter().map(|&i| corner(m, center, i)).collect(); painter.add(egui::Shape::convex_polygon(points, fill, Stroke::NONE)); diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 0ffa35a7b4..9d1a522a80 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -20,16 +20,18 @@ use craft::behavior::{EditEvent, GesturePhase, IconId, Selection}; use craft::ui::contract::{ Bind, DropAt, DropPayload, DropPlace, Entry, ListDrag, MemoProps, PopupKind, ReorderMove, SelectMode, Show as _, ShowContainer as _, Trigger, }; -use craft::ui::display::Divider; +use craft::ui::display::{Divider, Picture}; +use craft::ui::list::ThumbAspect; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::patterns::presets::{ PickerField, PresetBrowser, PresetDrop, PresetEvent, PresetFns, PresetPicker, PresetReorder, PresetRow, PresetSource, PresetState, PresetView, }; use craft::ui::primitives::{ - ContentPainterCx, IconSpec, Priority, Revision, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, + ContentPainterCx, IconSpec, PaintShape, Priority, Revision, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, }; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; use craft::ui::sections::{FooterAction, FooterBar, FooterOutput, Panel}; +use craft::ui::style::DataColor; use egui::{Color32, Rect, Sense, TextureHandle, Ui, pos2, vec2}; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, Paint}; @@ -337,7 +339,7 @@ fn paint_thumb(cx: &ContentPainterCx<'_>, rect: Rect, thumbs: &Thumbnails<StyleK let request = ThumbRequest::for_cell(rect.width().max(rect.height()), ctx.pixels_per_point()); let state = thumbs.state(&ctx, source, key, &request, Priority::VISIBLE); if !thumbs.paint(cx, rect, &state, &ThumbPaint::default().checker(false)) { - cx.painter.rect_filled(rect, 0.0, Color32::WHITE); + cx.with_draw(|draw| draw.data_fill(&PaintShape::Rect(rect, egui::CornerRadius::ZERO), DataColor::new(Color32::WHITE))); } } @@ -389,10 +391,15 @@ fn large_tip(app: &VectorcraftApp, thumbs: &StyleThumbs, ui: &mut Ui, key: &Styl let look = thumbs.looks.get(i).copied().unwrap_or_default(); let tex = object_preview(app, ui.ctx(), &thumbs.d.graphic_styles[i], look, thumbs.look.preview, px); let (r, _) = ui.allocate_exact_size(vec2(LARGE, LARGE), Sense::hover()); - match &tex { - Some(tex) => ui.painter().image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE), - None => ui.painter().rect_filled(r, 0.0, Color32::WHITE), - }; + let texture = tex.as_ref().map(TextureHandle::id); + // Decorative: the style's name below it says what it shows. + Picture::painter("", ThumbAspect::SQUARE, move |cx, rect| { + cx.with_draw(|draw| match texture { + Some(id) => draw.texture(rect, id, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0))), + None => draw.data_fill(&PaintShape::Rect(rect, egui::CornerRadius::ZERO), DataColor::new(Color32::WHITE)), + }) + }) + .show_at(ui, r); ui.label(key); } diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 9bc58b6f6f..851717edf8 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -18,10 +18,10 @@ use craft::ui::contract::{Bind, DropAt, DropPlace, ListDrag, MemoProps, SelectMo use craft::ui::contract::{Entry, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem}; use craft::ui::patterns::presets::{PresetEvent, PresetView, ThumbInfo}; -use craft::ui::primitives::{ContentPainterCx, Glyph, IconSpec, StrokeWidth}; +use craft::ui::primitives::{ContentPainterCx, Glyph, IconSpec, PaintShape, StrokeWidth}; use craft::ui::runtime::env::Label; use craft::ui::sections::{FooterAction, FooterBar}; -use craft::ui::style::UiTokens; +use craft::ui::style::{DataColor, UiTokens}; use egui::{Color32, Painter, Rect, Response, Shape, Stroke, StrokeKind, Ui, pos2, vec2}; use serde_json::{Value, json}; use vectorcraft_color::swatch::REGISTRATION; @@ -543,10 +543,7 @@ pub(super) fn paint_swatch(cx: &ContentPainterCx<'_>, rect: Rect, paint: &Paint, match paint { _ if paint.is_registration() => registration_mark(cx, inner), Paint::Solid { .. } => {} - Paint::None => { - let slash = Stroke::new(cx.stroke_width(StrokeWidth::Medium), Color32::from_rgb(0xe0, 0x20, 0x20)); - cx.data_shapes([Shape::line_segment([inner.left_bottom(), inner.right_top()], slash)]); - } + Paint::None => none_slash(cx, inner), Paint::Pattern { .. } if pattern.is_some_and(|doc| pattern_thumb_in(doc, cx, inner, paint)) => {} _ => crate::paint_preview::paint_rect(cx, inner, paint), } @@ -593,6 +590,15 @@ fn pattern_thumb_in(doc: &Document, cx: &ContentPainterCx<'_>, r: Rect, paint: & true } +/// The red of None's slash on a swatch tile and of a disabled opacity mask's cross, drawn on the document's white or +/// black paper. It is the same in every theme. +pub(super) const OFF_MARK: Color32 = Color32::from_rgb(0xe0, 0x20, 0x20); + +/// None's slash across `r`, from its lower left to its upper right, in [`OFF_MARK`] at the medium stroke width. +fn none_slash(cx: &ContentPainterCx<'_>, r: Rect) { + cx.with_draw(|draw| draw.stroke(&PaintShape::Path(vec![r.left_bottom(), r.right_top()]), StrokeWidth::Medium, DataColor::new(OFF_MARK))); +} + /// Registration's mark: a black target on white. fn registration_mark(cx: &ContentPainterCx<'_>, r: Rect) { let c = r.center(); diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index ee674781ae..a3f37bf4a1 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -19,13 +19,14 @@ use craft::ui::list::{List, ListRow, RowEvent, ThumbSize, ThumbTarget}; use craft::ui::menu::PanelRow; use craft::ui::pickers::Select; use craft::ui::primitives::{ - ContentPainterCx, IconSpec, LoadFailure, LoadedPicture, Priority, ThumbJob, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, + ContentPainterCx, IconSpec, LoadFailure, LoadedPicture, PaintShape, Priority, StrokeWidth, ThumbJob, ThumbRender, ThumbRequest, ThumbSource, + ThumbnailOptions, Thumbnails, }; use craft::ui::primitives::{Revision, ThumbPaint}; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; use craft::ui::runtime::env::UnitKind; use craft::ui::text::NumberField; -use egui::{Color32, Stroke, Ui}; +use egui::{Color32, Ui}; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Knockout, Node, NodeId, OpacityMask}; use vectorcraft_engine::cmd::TransparencyInfo; @@ -183,8 +184,7 @@ fn mask_row( if !object_state.as_ref().is_some_and(|s| store.paint(cx, rect, s, plain)) && let Some(c) = fill { - // PLAN: a colour from data should go through the content painter's data path, not the raw painter. - cx.painter.rect_filled(rect.shrink(rect.width() * 0.2), 0.0, c); + cx.data_shapes([egui::Shape::rect_filled(rect.shrink(rect.width() * 0.2), 0.0, c)]); } }; let paint_mask = move |cx: &ContentPainterCx, rect: egui::Rect| { @@ -193,9 +193,12 @@ fn mask_row( store.paint(cx, rect, s, paper); } if disabled { - let red = Stroke::new(2.0, Color32::from_rgb(220, 40, 40)); - cx.painter.line_segment([rect.left_top(), rect.right_bottom()], red); - cx.painter.line_segment([rect.right_top(), rect.left_bottom()], red); + let red = craft::ui::style::DataColor::new(super::swatches::OFF_MARK); + cx.with_draw(|draw| { + for line in [[rect.left_top(), rect.right_bottom()], [rect.right_top(), rect.left_bottom()]] { + draw.stroke(&PaintShape::Path(line.to_vec()), StrokeWidth::Thick, red); + } + }); } } else { cx.icon(rect, &IconSpec::svg(IconId::new("dc-mask-none"))); From 99fccade635c89b7d6617eefbddf6c9ba138de2d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 15:20:13 -0800 Subject: [PATCH 60/78] Control bar: with type selected, Opacity and Recolor Artwork stay while the type groups leave The Character and Paragraph groups were drawn without a rank, and a member without a rank never leaves the bar. When type's controls did not fit, every ranked member ahead of them left instead: Snapping, the width profile, Recolor Artwork and then Opacity. - A new `rank::TYPE`, below the other ranks, ranks the Character group, the Paragraph group and area type's vertical alignment buttons, so they leave before the members ahead of them. - With type groups shown, the Align buttons after them take the same rank and, coming last, leave first. - `text_style` is looked up only when the Character or Paragraph group is on. The new test narrows the bar step by step with a text object selected and checks that Opacity, Recolor Artwork and the Style picker show at every width that shows the Character group. --- crates/ui-egui/src/chrome/control_bar.rs | 33 +++++++++++++++++------- crates/ui-egui/src/chrome/tests.rs | 23 +++++++++++++++++ 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 2088bfa1b4..7cecd2414d 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -23,14 +23,18 @@ pub(crate) mod rank { pub const SELECT_SIMILAR: u8 = 1; /// The inline X/Y/W/H fields and the Snapping menu. pub const FIELDS: u8 = 2; + /// The type groups (Character, Paragraph and area type's vertical alignment) and the Align buttons after them: + /// they leave before the members ahead of them, so Opacity, the Style picker and Recolor Artwork show while type + /// is selected. + pub const TYPE: u8 = 3; /// The parts of a group that its other members work without: the width profile, Recolor Artwork, Global Edit /// Options, Document Setup, an image's Edit Original. - pub const DETAIL: u8 = 3; + pub const DETAIL: u8 = 4; /// The Opacity link and field: they leave before the groups, so the narrower Style link and picker after them /// can show without them. - pub const OPACITY: u8 = 4; + pub const OPACITY: u8 = 5; /// Every other member of the bar. - pub const GROUP: u8 = 5; + pub const GROUP: u8 = 6; } /// An anchor button: icon, tooltip, command and the convert command's `to`. @@ -597,14 +601,21 @@ fn members(app: &mut VectorcraftApp, ui: &mut Ui) { if group_on(app, "graphicStyle") && count > 0 { style_group(app, ui); } - if group_on(app, "character") { - crate::panels::character::control_bar(app, ui); + let (character, paragraph) = (group_on(app, "character"), group_on(app, "paragraph")); + let typed = (character || paragraph) && crate::panels::character::text_style(app).is_some(); + if typed && character { + ranked(ui, rank::TYPE, |ui| { + crate::panels::character::control_bar(app, ui); + }); } - if group_on(app, "paragraph") { - crate::panels::paragraph::control_bar(app, ui); + if typed && paragraph { + ranked(ui, rank::TYPE, |ui| { + crate::panels::paragraph::control_bar(app, ui); + }); } - if group_on(app, "verticalAlignment") && crate::panels::properties::vertical_align::shown(app).is_some() { - group(ui, rank::GROUP, |ui| { + let vertical = group_on(app, "verticalAlignment") && crate::panels::properties::vertical_align::shown(app).is_some(); + if vertical { + group(ui, rank::TYPE, |ui| { crate::panels::properties::vertical_align::buttons(app, ui); }); } @@ -615,7 +626,9 @@ fn members(app: &mut VectorcraftApp, ui: &mut Ui) { return; } if group_on(app, "alignDistribute") { - group(ui, rank::GROUP, |ui| crate::panels::align::control_bar_strip(app, ui)); + // After the type groups, the Align buttons take their rank and, coming last, leave first. + let rank = if typed || vertical { rank::TYPE } else { rank::GROUP }; + group(ui, rank, |ui| crate::panels::align::control_bar_strip(app, ui)); } if transform { // The Transform link opens the whole Transform panel in a popover; X/Y/W/H follow inline while the diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index acc0ecf522..75dbc0754d 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -2431,6 +2431,29 @@ fn the_control_bar_leaves_members_out_in_its_priority_order() { assert!(seen.iter().any(|s| s[0] && !s[1]), "some width shows the Align buttons without the fields"); } +/// With type selected, the Character and Paragraph groups leave the Control bar before the members ahead of them: at +/// every width that shows the Character group, Opacity, Recolor Artwork and the Style picker show too, the Paragraph +/// group leaves before the Character group, the Align buttons leave before the Paragraph group, and some width shows +/// Opacity without them. +#[test] +fn the_type_groups_leave_the_control_bar_before_opacity_and_style() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let text = app.run("text.create", json!({"x": 10, "y": 100, "text": "Hi"})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [text] })).unwrap(); + let mut bar = control_shown(app); + let names = ["Character:", "Paragraph:", "Opacity:", "Recolor Artwork", "Style:", "Horizontal Align Left"]; + let seen = control_bar_widths(&mut bar, &names); + assert!(seen.iter().any(|s| s.iter().all(|shown| *shown)), "a wide bar shows {names:?}"); + for s in &seen { + assert!(!s[0] || s[2..5].iter().all(|shown| *shown), "the Character group shows only with {:?}: {s:?}", &names[2..5]); + assert!(!s[1] || s[0], "the Paragraph group shows only with the Character group: {s:?}"); + assert!(!s[5] || s[1], "the Align buttons show only with the Paragraph group: {s:?}"); + } + assert!(seen.iter().any(|s| s[2] && !s[0]), "some width shows Opacity without the Character group"); +} + /// The names of the bar's X, Y, W and H fields, in their order. const BAR_FIELDS: [&str; 4] = ["X position", "Y position", "Width", "Height"]; From 85399ece43f7fb63a5611ac959f60b298752355e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 15:24:50 -0800 Subject: [PATCH 61/78] Tool icons: the Slice Tool shows its new icon dc-slice.svg was registered, but tool_icon still mapped tool-slice to slice_knife, so the Slice Tool showed the old icon. --- crates/ui-egui/src/icons.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index e0f347d9cc..c0ca9fdf0c 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -107,7 +107,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-graph-pie" => "dc-graph-pie", "tool-graph-radar" => "dc-graph-radar", "tool-artboard" => "artboard", - "tool-slice" => "slice_knife", + "tool-slice" => "dc-slice", "tool-slice-select" => "dc-slice-select", "tool-hand" => "hand", "tool-rotate-view" => "dc-rotate-view", From c3f5eac706dc812f712b438d1c026ae4ca3832b6 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 12:40:40 -0800 Subject: [PATCH 62/78] =?UTF-8?q?Menus:=20Open=20With,=20Object=20?= =?UTF-8?q?=E2=80=BA=20Plug-ins=20and=20File=20=E2=80=BA=20Scripts=20show?= =?UTF-8?q?=20their=20notes=20as=20disabled=20rows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With no importer plug-in installed, File › Open With held only the heading "No importer plug-ins installed". The menu layout drops a heading with no item after it and then drops the submenu it leaves empty, so Open With disappeared from the File menu. Object › Plug-ins lost its "No filter plug-ins installed" heading the same way, since a separator follows it, and so did File › Scripts' notes ("Some scripts were not listed", "The Scripts folder cannot be read" and the loading notes). These rows are now a disabled placeholder item, the form the menu layout keeps for an empty list. The item runs no command and shows its text in the UI language. The menu listing, the macOS menu bar and the translation tests treat it as they treat a Coming Soon row: disabled, with no command. --- crates/ui-egui/src/dialogs/plugin.rs | 10 ++--- crates/ui-egui/src/i18n/tests.rs | 10 ++--- crates/ui-egui/src/menus.rs | 15 +++++++ crates/ui-egui/src/menus/entries.rs | 4 +- crates/ui-egui/src/menus/labels.rs | 4 +- crates/ui-egui/src/menus/model.rs | 12 +++++- crates/ui-egui/src/menus/native.rs | 4 +- crates/ui-egui/src/menus/tests.rs | 54 +++++++++++++++++++++++- crates/ui-egui/src/scripts_menu.rs | 2 +- crates/ui-egui/src/tests/scripts_menu.rs | 5 +++ 10 files changed, 100 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 6b6952a6ca..9eb768dbc2 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -45,14 +45,14 @@ use vectorcraft_plugins::{Budget, Kind, Manifest, Plugin, permissions, registry} use super::form; use super::preview::LivePreview; use crate::VectorcraftApp; -use crate::menus::{Sep, c, cp, heading, sub}; +use crate::menus::{Sep, c, cp, placeholder, sub}; /// The key of the hosted dialog of plug-in filters. pub const KIND: &str = "plugin"; const CMD: &str = "plugin.run"; -/// Object › Plug-ins' header while no filter plug-in is installed. +/// Object › Plug-ins' disabled row while no filter plug-in is installed. pub const NO_FILTERS: &str = "No filter plug-ins installed"; /// A menu label for plug-in `name`: with an ellipsis when it opens a dialog. @@ -87,13 +87,13 @@ pub fn object_menu() -> Vec<Node> { .map(|p| with_commands(p, cp(label(&p.manifest().name, !p.manifest().params.is_empty()), "plugin.dialog", json!({ "id": p.id() })))) .collect(); if items.is_empty() { - items.push(heading(NO_FILTERS)); + items.push(placeholder(NO_FILTERS)); } items.extend([Sep, c("Install Plug-in…", "ui.installPlugin"), c("Reload Plug-ins", "plugin.reload")]); items } -/// File › Open With's header while no importer plug-in is installed. +/// File › Open With's disabled row while no importer plug-in is installed. pub const NO_IMPORTERS: &str = "No importer plug-ins installed"; /// File › Open With: the installed importers (`file.openWith {importer}`), each by its name. @@ -102,7 +102,7 @@ pub fn open_with_menu() -> Vec<Node> { .iter() .map(|p| cp(label(&p.manifest().name, true), "file.openWith", json!({ "importer": vectorcraft_plugins::export::format_id(p.id()) }))) .collect(); - if items.is_empty() { vec![heading(NO_IMPORTERS)] } else { items } + if items.is_empty() { vec![placeholder(NO_IMPORTERS)] } else { items } } /// Effect › Plug-ins: the live-effect plug-ins, each with its commands if it has any (`None` diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 24c452f944..1641f3db2c 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -747,7 +747,7 @@ fn menu_labels() -> Vec<(String, String, serde_json::Value)> { fn walk(items: &[Node], out: &mut Vec<(String, String, serde_json::Value)>) { for i in items { match i { - Node::Item(it) if it.command.id == crate::menus::TODO => out.push((it.label.clone(), String::new(), serde_json::Value::Null)), + Node::Item(it) if crate::menus::unbound(&it.command.id) => out.push((it.label.clone(), String::new(), serde_json::Value::Null)), Node::Item(it) => out.push((it.label.clone(), it.command.id.clone(), it.command.params.clone())), Node::Heading(l) => out.push((l.clone(), String::new(), serde_json::Value::Null)), Node::Submenu { label, children, .. } => { @@ -773,11 +773,11 @@ fn menu_item_effect<'a>(id: &str, p: &'a serde_json::Value) -> Option<&'a str> { /// The label a menu item shows in `lang`, as the menus resolve it: an Effect menu item by its /// effect's `@id` row when the catalog has one, any other command by its id's row or its English -/// label, and a submenu or an unbuilt item by its English label. +/// label, and a submenu, an unbuilt item or a placeholder by its English label. fn shown_menu_label(lang: Lang, item: &crate::menus::Node) -> Option<&str> { use crate::menus::Node; match item { - Node::Item(it) if it.command.id == crate::menus::TODO => Some(tr(lang, &it.label)), + Node::Item(it) if crate::menus::unbound(&it.command.id) => Some(tr(lang, &it.label)), Node::Item(it) => { let (id, p) = (it.command.id.as_str(), &it.command.params); let by_effect = menu_item_effect(id, p).map(|e| tr_id(lang, e, "")).filter(|s| !s.is_empty()); @@ -799,7 +799,7 @@ fn menu_items_side_by_side_have_different_labels() { for item in items { let Some(shown) = shown_menu_label(lang, item) else { continue }; let (english, what) = match item { - Node::Item(it) if it.command.id == crate::menus::TODO => (it.label.as_str(), "submenu or unbuilt item"), + Node::Item(it) if crate::menus::unbound(&it.command.id) => (it.label.as_str(), "submenu, unbuilt item or placeholder"), Node::Item(it) => (it.label.as_str(), menu_item_effect(&it.command.id, &it.command.params).unwrap_or(it.command.id.as_str())), Node::Submenu { label, .. } => (label.as_str(), "submenu or unbuilt item"), _ => continue, @@ -854,7 +854,7 @@ fn menu_items_never_show_an_id() { fn walk(lang: Lang, items: &[crate::menus::Node], out: &mut Vec<String>) { for item in items { match item { - crate::menus::Node::Item(it) if it.command.id != crate::menus::TODO => { + crate::menus::Node::Item(it) if !crate::menus::unbound(&it.command.id) => { let (l, id) = (&it.label, it.command.id.as_str()); let key = menu_item_effect(id, &it.command.params).unwrap_or(id); let shown = shown_menu_label(lang, item).unwrap_or_default(); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 7d003be560..0b6bf5e767 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -23,6 +23,16 @@ pub(crate) use craft::menu::Node::Separator as Sep; /// The command id of an item that is not built yet; its state is always disabled. pub(crate) const TODO: &str = "todo"; +/// The command id of a placeholder row that stands for an empty list (File › Open With's "No +/// importer plug-ins installed"); it runs nothing and its state is always disabled. +pub(crate) const PLACEHOLDER: &str = "placeholder"; + +/// Whether a row bound to command `id` runs nothing: a Coming Soon row ([`TODO`]) or a placeholder +/// ([`PLACEHOLDER`]). +pub(crate) fn unbound(id: &str) -> bool { + id == TODO || id == PLACEHOLDER +} + /// An item that runs command `id` with `params`, labelled `label` (the English source label for /// tree rows, the shown name for rows that list names). pub(crate) fn named(label: impl Into<String>, id: &str, params: Value) -> Node { @@ -38,6 +48,11 @@ pub(crate) fn cp(label: &'static str, id: &'static str, params: Value) -> Node { pub(crate) fn todo(label: &'static str) -> Node { named(label, TODO, json!({ "label": label })) } +/// A disabled row that stands for an empty list, so its submenu stays in the menu: the layout +/// drops a heading with no item after it, and with it a submenu left empty. +pub(crate) fn placeholder(label: &'static str) -> Node { + named(label, PLACEHOLDER, json!({ "label": label })) +} pub(crate) fn sub(label: &'static str, children: Vec<Node>) -> Node { Node::submenu(label, children) } diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 6524edfd21..09513fb538 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -3,7 +3,7 @@ use super::labels::{display_label, dynamic_label, effect_item_label, item_shortc use super::slots::{recent_readable, recent_slot}; use super::state::{shortcut_of, shown_state}; use super::tree::{Listed, menu_tree_named}; -use super::{Node, Serialize, TODO, Value, VectorcraftApp}; +use super::{Node, Serialize, Value, VectorcraftApp, unbound}; /// The label of the menu item that runs `id` with `p` and reads `label` in English, as the menus /// draw it in the UI language: an effect's own name (Pathfinder › Add), an object's name, a @@ -169,7 +169,7 @@ pub fn insertable_items(english_names: bool, listed: &Listed) -> Vec<InsertableI pub(super) fn flatten(app: &VectorcraftApp, path: Vec<String>, shown: Vec<String>, nodes: &[Node], out: &mut Vec<MenuEntry>) { for node in nodes { match node { - Node::Item(it) if it.command.id == TODO => out.push(MenuEntry { + Node::Item(it) if unbound(&it.command.id) => out.push(MenuEntry { path: path.clone(), label: it.label.clone(), command: None, diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 030eb40b98..a1247789a0 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -2,7 +2,7 @@ use super::slots::{perspective_grid, recent_slot, saved_selection_name, saved_se use super::state::{hidden_when_disabled, shortcut_of}; use super::tree::menu_tree; use super::ui_commands::UI_COMMANDS; -use super::{Node, TODO, Value, VectorcraftApp}; +use super::{Node, Value, VectorcraftApp, unbound}; use craft::keymap::Chord; /// Label for toggles whose text flips (Outline/Preview, Hide/Show …). @@ -366,7 +366,7 @@ pub fn menu_strings() -> std::collections::BTreeSet<String> { fn walk(nodes: &[Node], under: &str, out: &mut BTreeSet<String>) { for node in nodes { match node { - Node::Item(it) if it.command.id == TODO => { + Node::Item(it) if unbound(&it.command.id) => { out.insert(it.label.clone()); } Node::Item(it) => { diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 9fdbeb7d84..1ff1ce27e0 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -18,7 +18,7 @@ use craft::ui::runtime::windows::WindowHost; use serde_json::{Value, json}; use super::labels::holds_plugin_commands; -use super::{Listed, TODO, display_label, menu_tree_named, plugin_revision, shown_label, shown_state, why_off}; +use super::{Listed, PLACEHOLDER, TODO, display_label, menu_tree_named, plugin_revision, shown_label, shown_state, why_off}; use crate::i18n::LangExt as _; use crate::{UiState, VectorcraftApp}; @@ -432,6 +432,16 @@ impl Build<'_> { let tip = crate::i18n::tr(self.lang, TODO_TOOLTIP).to_string(); return Some(item.tooltip(tip)); } + // A placeholder shows its text in the UI language, as a heading does, and runs nothing. + if command.id == PLACEHOLDER { + self.states.set(command, CommandState::new().enabled(false)); + let mut item = item.enabled(false); + let shown = self.title(&item.label, true); + if shown != item.label { + item.english = Some(std::mem::replace(&mut item.label, shown)); + } + return Some(item); + } let (id, params) = (command.id.as_str(), &command.params); let (enabled, checked) = shown_state(self.app, id, params)?; let mut state = CommandState::new().enabled(enabled).title(self.item_title(id, params, &item.label)); diff --git a/crates/ui-egui/src/menus/native.rs b/crates/ui-egui/src/menus/native.rs index 9a15431858..62fbc97da3 100644 --- a/crates/ui-egui/src/menus/native.rs +++ b/crates/ui-egui/src/menus/native.rs @@ -5,8 +5,8 @@ use craft::menu::{Gate, ItemKind, LayoutOptions, MenuBar, NativeMenu, Node, mac, use craft::ui::runtime::commands::{FirePhase, FireSource, Fired, holder}; use crate::VectorcraftApp; -use crate::menus::TODO; use crate::menus::model::{APP_NAME, item_title, pressed_pass, recording_shortcut, refresh, state_key, translate_label}; +use crate::menus::unbound; /// The layout options every Mac layout of VectorCraft's menus uses: the app's name and its /// translation of the labels the layout writes itself. @@ -63,7 +63,7 @@ fn stated(app: &VectorcraftApp) -> MenuBar { fn walk(app: &VectorcraftApp, lang: crate::i18n::Lang, nodes: &mut [Node]) { for node in nodes { match node { - Node::Item(it) if it.command.id == TODO => it.enabled = false, + Node::Item(it) if unbound(&it.command.id) => it.enabled = false, Node::Item(it) => { let (id, params) = (it.command.id.as_str(), &it.command.params); if let Some((enabled, checked)) = crate::menus::shown_state(app, id, params) { diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 7d1dd037e5..2433cc0e25 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -1237,8 +1237,8 @@ fn every_bound_menu_command_exists() { match n { Node::Item(it) => { let id = it.command.id.as_str(); - // A Coming Soon row (`TODO`) is bound to no command. - if id != TODO + // A Coming Soon row (`TODO`) or a placeholder is bound to no command. + if !unbound(id) && vectorcraft_engine::find_command(id).is_none() && !UI_COMMANDS.iter().any(|c| c.0 == id) && !id.starts_with("object.path.") @@ -1258,6 +1258,56 @@ fn every_bound_menu_command_exists() { assert!(bad.is_empty(), "menu items bound to unknown commands: {bad:?}"); } +/// File › Open With and Object › Plug-ins stay in the laid-out bar with nothing of their kind installed, showing a +/// disabled row that says so. Plug-ins are process-wide and other tests install some, so each list is checked only +/// while it holds none of its own rows. +#[test] +fn plugin_lists_show_a_disabled_row_when_nothing_is_installed() { + fn submenu<'a>(nodes: &'a [Node], english: &str) -> Option<&'a [Node]> { + nodes.iter().find_map(|n| match n { + Node::Submenu { label, english: e, children, .. } if e.as_deref().unwrap_or(label) == english => Some(children.as_slice()), + _ => None, + }) + } + fn placeholder_off(nodes: &[Node], text: &str) -> bool { + nodes.iter().any(|n| matches!(n, Node::Item(it) if it.command.id == PLACEHOLDER && it.command.params["label"] == text && !it.enabled)) + } + fn lists(nodes: &[Node], id: &str) -> bool { + nodes.iter().any(|n| match n { + Node::Item(it) => it.command.id == id, + Node::Submenu { children, .. } => lists(children, id), + _ => false, + }) + } + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let ctx = crate::testing::ui_context(); + crate::menus::model::refresh(&mut app, &ctx); + let menu = |english: &str| { + app.menus.laid.menus.iter().find(|m| m.english.as_deref().unwrap_or(&m.title) == english).map(|m| m.children.as_slice()).unwrap_or_default() + }; + + let open_with = submenu(menu("File"), "Open With").expect("File › Open With is in the bar"); + if !lists(open_with, "file.openWith") { + assert!(placeholder_off(open_with, crate::dialogs::plugin::NO_IMPORTERS), "{open_with:?}"); + } + let plugins = submenu(menu("Object"), "Plug-ins").expect("Object › Plug-ins is in the bar"); + if !lists(plugins, "plugin.dialog") { + assert!(placeholder_off(plugins, crate::dialogs::plugin::NO_FILTERS), "{plugins:?}"); + } + + // Whatever is installed: the layout keeps an empty list's row, and the submenu that holds only that row. + let row = |nodes: &[Node], text: &str| nodes.iter().any(|n| matches!(n, Node::Item(it) if it.command.id == PLACEHOLDER && it.label == text)); + let mut empty = vec![ + sub("Open With", vec![placeholder(crate::dialogs::plugin::NO_IMPORTERS)]), + placeholder(crate::dialogs::plugin::NO_FILTERS), + Sep, + c("Reload Plug-ins", "plugin.reload"), + ]; + craft::menu::tidy(&mut empty); + assert!(submenu(&empty, "Open With").is_some_and(|o| row(o, crate::dialogs::plugin::NO_IMPORTERS)), "{empty:?}"); + assert!(row(&empty, crate::dialogs::plugin::NO_FILTERS), "{empty:?}"); +} + /// #543: Object › Image Trace › Make and Make and Expand trace with the Default preset at once, /// with no form asking for a preset's name. #[test] diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index 7d45e37953..a715f982af 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -241,7 +241,7 @@ pub(crate) fn items_at(now: f64) -> Vec<Node> { }; let mut nodes = level(&listing.entries); let notes = [listing.truncated.then_some(TRUNCATED), listing.unreadable.then_some(UNREADABLE), note]; - nodes.extend(notes.into_iter().flatten().map(Node::heading)); + nodes.extend(notes.into_iter().flatten().map(crate::menus::placeholder)); if !nodes.is_empty() { nodes.push(Node::Separator); } diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 2b03214f3a..33674ec957 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -88,6 +88,7 @@ fn label(node: &Node) -> Option<String> { /// for a separator. fn shape(nodes: &[Node]) -> String { let one = |node: &Node| match node { + Node::Item(item) if item.command.id == menus::PLACEHOLDER => format!("({})", item.label), Node::Item(item) => item.label.clone(), Node::Submenu { label, children, .. } => format!("{label}/[{}]", shape(children)), Node::Heading(text) => format!("({text})"), @@ -297,6 +298,10 @@ fn the_menu_notes_a_listing_that_stopped_and_a_folder_it_cannot_read() { std::fs::write(dir.join("Scripts"), "").unwrap(); read(&app); assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); + // The menu layout keeps the note. + let mut laid = scripts(); + craft::menu::tidy(&mut laid); + assert_eq!(shape(&laid), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); let _ = std::fs::remove_dir_all(dir); } From 9fe7bd19c5679dce2d03a6736c6d1fa6af0f8b65 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 16:00:20 -0800 Subject: [PATCH 63/78] Panels: rows of side-by-side controls are Row and Stack, and stay inside the panel The rows of controls that sat in raw horizontal layouts inside framework containers are the framework's Row, Stack and Grid. - Stroke: the Arrowheads row fills the field. The two heads share the width Swap leaves, and Swap moves to a new line when all three do not fit. Before, the row ran past the panel's right edge. The Profile row is a Row. - Color Themes: the Create tab's hex row is a Row, so its two buttons stay inside a panel at its least width. - Color Wheel: the rows are a Stack, and the top row is a Grid with the proxy at its content width and the wheel or the box beside it. When the box and its strip do not fit beside the proxy, they go under it. Before, the strip ran past the panel and was as tall as the room. - Align panel, Properties panel's Align row, Control bar's Align strip and paragraph row, Paragraph panel's lists row, and the gradient stop editor's two rows are a Row. They lay out as before. --- crates/ui-egui/src/dialogs/gradient_stop.rs | 6 +-- crates/ui-egui/src/panels.rs | 2 + crates/ui-egui/src/panels/align.rs | 13 +++--- crates/ui-egui/src/panels/color_themes.rs | 5 ++- crates/ui-egui/src/panels/color_wheel.rs | 44 +++++++++++-------- crates/ui-egui/src/panels/paragraph.rs | 7 +-- crates/ui-egui/src/panels/stroke.rs | 10 +++-- crates/ui-egui/src/panels/tests_panel_rows.rs | 38 ++++++++++++++++ 8 files changed, 90 insertions(+), 35 deletions(-) create mode 100644 crates/ui-egui/src/panels/tests_panel_rows.rs diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 1cab75f7bd..d38eae5bb0 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -21,7 +21,7 @@ use craft::ui::choice::Segmented; use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; use craft::ui::form::Field; -use craft::ui::layout_components::Stack; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::notices::Notice; use craft::ui::popover::Popover; use craft::ui::runtime::env::{Label, UnitKind}; @@ -264,7 +264,7 @@ impl StackDialog for GradientStopPopover { /// point: spread). What the user edits is filed in `filed`. fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) { Stack::new().show(ui, |ui, _| { - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { let tabs = [ Entry::new(Tab::Color, tl!("Color").to_owned()).icon(IconId::new("palette")), Entry::new(Tab::Swatches, tl!("Swatches").to_owned()).icon(IconId::new("swatch-book")), @@ -288,7 +288,7 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi } Tab::Swatches => swatches(ui, feed, filed), } - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { filed.fields.opacity = percent_field(ui, tl!("Opacity").to_owned(), feed.opacity).or(filed.fields.opacity); let (label, amount) = if feed.point { (tl!("Spread"), &mut filed.fields.spread) } else { (tl!("Location"), &mut filed.fields.location) }; *amount = percent_field(ui, label.to_owned(), feed.amount).or(*amount); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 489eee6f61..8ee0a7c13f 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1003,6 +1003,8 @@ mod tests_links; #[cfg(test)] mod tests_maskview; #[cfg(test)] +mod tests_panel_rows; +#[cfg(test)] mod tests_script_console; #[cfg(test)] mod tests_stroke; diff --git a/crates/ui-egui/src/panels/align.rs b/crates/ui-egui/src/panels/align.rs index 5cff5f4aed..9b8d94a31b 100644 --- a/crates/ui-egui/src/panels/align.rs +++ b/crates/ui-egui/src/panels/align.rs @@ -9,6 +9,7 @@ use craft::ui::bars::{BarItem, BarItems}; use craft::ui::buttons::{IconButton, PopupMark, ToggleButton}; use craft::ui::contract::{Bind, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::display::Divider; +use craft::ui::layout_components::Row; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::text::NumberField; @@ -305,7 +306,7 @@ fn bar_items(buttons: impl Iterator<Item = Button>) -> BarItems { /// Align panel's Align To says (the key object while there is one), as its own buttons do (#789), /// and the selected artboards with the Artboard tool chosen. pub(crate) fn align_buttons(_app: &mut VectorcraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { for (icon, b) in align_icons() { command_button(ui, bar_glyph(b).unwrap_or(icon), b); } @@ -333,7 +334,7 @@ pub(crate) fn button_enabled(app: &VectorcraftApp, b: &Button) -> bool { pub(crate) fn control_bar_strip(app: &mut VectorcraftApp, ui: &mut Ui) { let (icon, name) = align_to_icon_name(shown_align_to(app), key_is_anchor(app)); let distributes = if on_artboards(app) { artboards_distribute(app) } else { objects_aligned(app) > 1 }; - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { bar_items(align_icons().map(|(_, b)| b)).show(ui); let button = IconButton::new(IconId::new(icon)) .label(tl!("Align To:")) @@ -498,14 +499,14 @@ pub(crate) fn run_align_to(app: &mut VectorcraftApp, v: AlignTo) -> Result<Value /// from the command layer ([`button_enabled`], [`run_button`]). pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { crate::panels::subheading(tl!("Align Objects:")).show(ui, |ui, _| { - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { for (icon, b) in align_icons() { command_button(ui, icon, b); } }); }); crate::panels::subheading(tl!("Distribute Objects:")).show(ui, |ui, _| { - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { for (icon, b) in distribute_icons() { command_button(ui, icon, b); } @@ -524,7 +525,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let min_spacing = spacing_min(app); let mut edited = None; crate::panels::subheading(tl!("Distribute Spacing:")).show(ui, |ui, _| { - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { command_button(ui, "dc-dist-vspace", Button::Spacing("vertical")); command_button(ui, "dc-dist-hspace", Button::Spacing("horizontal")); // The value is UI state, not a document edit: a landed value is assigned. @@ -541,7 +542,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { crate::panels::subheading(tl!("Align To:")).show(ui, |ui, _| { // With one object selected the buttons align it to the artboard, and Align To shows Artboard. let anchor = key_is_anchor(app); - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { for (id, v) in ALIGN_TO_COMMANDS { let (icon, _) = align_to_icon_name(v, anchor); ToggleButton::command(CommandRef::new(id)).icon(IconId::new(icon)).icon_only().show(ui); diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index d4d09ec6c4..067f820a5a 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -16,7 +16,8 @@ use craft::theme::variant::Tone; use craft::theme::{ModelValues, Rgba, Srgba}; use craft::ui::buttons::IconButton; use craft::ui::choice::{SwatchSpacing, SwatchTable}; -use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, ShowCollection as _}; +use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow, ThumbSize}; use craft::ui::menu::PanelRow; use craft::ui::notices::Notice; @@ -518,7 +519,7 @@ fn create(app: &mut VectorcraftApp, ui: &mut Ui) { d.sel = i; } sliders(ui, &mut d, &mut mode, &mut held); - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { let hex = d.colors.get(d.sel).map(hex_rgba).unwrap_or(Rgba::rgb(0, 0, 0)); let mut edited = hex; HexField::hex(tl!("Color"), Bind::bound(&mut edited)).show(ui); diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 7d10ca7d0b..8aeca36e07 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -48,6 +48,7 @@ use std::sync::Arc; // PLAN: assumed `craft-color-ui`, `craft-theme`, `craft-behavior` and `craft-keymap` are dependencies of // vectorcraft-ui-egui (Cargo.toml is not in this set's table); `craft_ui` does not re-export them at the base. +use craft::behavior::ColumnWidth; use craft::behavior::Mixed; use craft::behavior::Selection; use craft::color_ui::AreaMode; @@ -57,7 +58,8 @@ use craft::theme::{ColorModel, HsbModel, ModelValues, RgbModel, Srgba}; use craft::ui::choice::{SwatchSpacing, SwatchTable}; use craft::ui::contract::{ActivateOn, Bind, EditResponse, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::{Shade, Text}; -use craft::ui::layout_components::Stack; +use craft::ui::layout::CellAlign; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::menu::PanelRow; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::runtime::env::Label; @@ -78,6 +80,10 @@ use crate::edits::{EditPath, apply_edits}; pub const ID: &str = "colorWheel"; +/// The columns of the panel's top row: the proxy as wide as its content, and the wheel or the box beside it in the +/// rest of the width. +const BESIDE: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)]; + /// What the panel shows right of the proxy: the wheel, or the box (a color field and a channel /// strip). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] @@ -1107,29 +1113,32 @@ fn show_with(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui) { let cx = Pick { tgt: &tgt, color, cms: &cms, behind, cmyk_doc, shown: hsb }; let set = app.ui.color_wheel.clone(); let now = ui.input(|i| i.time); - ui.horizontal_top(|ui| { - ui.vertical(|ui| super::proxy(app, ui)); + // The stack's gap separates the rows. + Stack::new().show(ui, |ui, _| show_rows(app, panel, ui, &cx, &set, now)); +} + +/// The panel's rows: the Fill/Stroke proxy beside the box or the wheel, level with its top, then the slider rows, +/// the color vision row and the document colors row that `set` turns on. +fn show_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pick, set: &Settings, now: f64) { + Grid::new(&BESIDE).cells(CellAlign::Top).show(ui, |ui, _| { + super::proxy(app, ui); match set.view { - View::Box => show_box(app, panel, ui, &cx, &set), - View::Wheel => show_wheel(app, panel, ui, &cx, &set), + View::Box => { + Row::new().fill_width().show(ui, |ui, _| show_box(app, panel, ui, cx, set)); + } + View::Wheel => show_wheel(app, panel, ui, cx, set), } }); match set.sliders { Sliders::None => {} - Sliders::Oklch => { - ui.add_space(4.0); - oklch_rows(app, panel, ui, &cx); - } - Sliders::Hsl => { - ui.add_space(4.0); - hsl_rows(app, panel, ui, &cx); - } + Sliders::Oklch => oklch_rows(app, panel, ui, cx), + Sliders::Hsl => hsl_rows(app, panel, ui, cx), } // A row drag whose rows were hidden or replaced (`ui.colorWheel {sliders}`), or turned gray // (OKLCH rows after the working RGB space stops being sRGB), reports no release: its preview is // kept as one undo step and the interaction ends. let sliders = app.ui.color_wheel.sliders; - if panel.rows_live.is_some_and(|rows| rows != sliders || (rows == Sliders::Oklch && !cms.rgb_is_srgb())) { + if panel.rows_live.is_some_and(|rows| rows != sliders || (rows == Sliders::Oklch && !cx.cms.rgb_is_srgb())) { if app.session.in_interaction() && let Err(e) = app.session.commit_interaction() { @@ -1139,12 +1148,11 @@ fn show_with(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui) { panel.rows_live = None; } if set.vision { - ui.add_space(4.0); - vision_row(ui, &cms, color.as_ref()); + vision_row(ui, cx.cms, cx.color.as_ref()); } if set.document_colors - && let Some(u) = document_colors_row(app, panel, ui, &cms, now) + && let Some(u) = document_colors_row(app, panel, ui, cx.cms, now) { - apply_used(app, &tgt, &u, behind); + apply_used(app, cx.tgt, &u, cx.behind); } } diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index b7d5fdc67d..2dd7f1f39f 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -14,6 +14,7 @@ use craft::ui::buttons::{IconButton, PopupMark, ToggleButton}; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Entry, MemoProps, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::form::Field; +use craft::ui::layout_components::Row; use craft::ui::menu::{Menu, PanelRow}; use craft::ui::pickers::Select; use craft::ui::popover::Popover; @@ -438,8 +439,8 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { if text_style(app).is_none() { return true; } - // PLAN: the members' `Row::fit_rank` (ch.K30: toggles out before the link) belongs to chrome-w16's row; `horizontal` stands in until it lands. - ui.horizontal(|ui| { + // PLAN: the members' `Row::fit_rank` (ch.K30: toggles out before the link) belongs to chrome-w16's row. + Row::new().show(ui, |ui, _| { let link = crate::panels::option_link(tl!("Paragraph:")).tooltip(tl!("Paragraph options")).show(ui); Popover::new(tl!("Paragraph"), Bind::kept()) .overlay(|overlay| overlay.opened_by(&link.response, Trigger::Click)) @@ -660,7 +661,7 @@ fn list_control(ui: &mut Ui, kind: ListKind, pressed: bool, entries: &[Entry<u32 /// turns the list off, and the one every paragraph has is checked. More Options after them opens /// Bullets and Numbering on the kind's tab. fn lists_row(app: &mut VectorcraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { let shown = bullets_shown(app); match list_control(ui, ListKind::Bullets, matches!(shown, Some(Some(_))), &bullet_entries(shown)) { Some(ListEvent::Toggle) => toggle_list(app, ListKind::Bullets), diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index c339c73b6e..c4a5b91318 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -10,8 +10,9 @@ use craft::draw::ui::stroke::{self as draw, StrokeEditor, StrokeField, StrokeSec use craft::keymap::CommandRef; use craft::ui::buttons::IconButton; use craft::ui::choice::Segmented; -use craft::ui::contract::{Bind, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel, TooltipSpec}; +use craft::ui::contract::{Bind, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, TooltipSpec}; use craft::ui::form::Field; +use craft::ui::layout_components::Row; use craft::ui::menu::PanelRow; use craft::ui::pickers::Select; use craft::ui::popover::Popover; @@ -390,7 +391,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { arrow_rows(app, ui, st.as_ref()); ui.separator(); Field::new(tl!("Profile")).show(ui, |ui, _| { - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { profile_select(app, ui); flip_buttons(app, ui, st.as_ref()); }); @@ -410,11 +411,14 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) { (st.and_then(|s| s.end_arrow.clone()), false, tl!("End arrowhead"), "endArrow"), ]; Field::new(tl!("Arrowheads")).show(ui, |ui, _| { - ui.horizontal(|ui| { + // The two heads share the width the Swap button leaves; a field too narrow for all three puts Swap on a + // new line. + Row::new().fill_width().wrap(true).show(ui, |ui, _| { for (head, start, label, key) in &heads { let (start, key) = (*start, *key); let out = Select::new(*label, Bind::given(head.clone()), &entries) .picture(move |a, cx, rect| arrow_thumb(cx, rect, a.as_ref(), start)) + .sizing(Sizing::FillWidth) .show(ui); // A custom head goes with its art, as document.inspect reports it. if let Some(a) = out.events.landed() { diff --git a/crates/ui-egui/src/panels/tests_panel_rows.rs b/crates/ui-egui/src/panels/tests_panel_rows.rs new file mode 100644 index 0000000000..51a22a4d2b --- /dev/null +++ b/crates/ui-egui/src/panels/tests_panel_rows.rs @@ -0,0 +1,38 @@ +//! Headless frames of panel rows that the framework lays out: controls side by side stay inside the panel's width. + +use super::tests_appearance::app_with_rect; +use super::*; +use crate::panel_docking::PANEL_MIN_WIDTH; +use crate::tests::panel_harness::{Panel, ROOM}; + +#[test] +fn the_arrowhead_row_stays_inside_the_stroke_panel() { + let panel = Panel::new(app_with_rect(), stroke::show); + // The Arrowheads field spans the panel's width. + let row = panel.rect("Arrowheads"); + for name in ["Start arrowhead", "End arrowhead", "Swap start and end arrowheads"] { + assert!(row.contains_rect(panel.rect(name)), "{name} at {:?} is outside the row {row:?}", panel.rect(name)); + } +} + +#[test] +fn the_color_themes_hex_row_stays_inside_a_narrow_panel() { + let mut panel = Panel::new(app_with_rect(), color_themes::show); + panel.room(egui::vec2(PANEL_MIN_WIDTH, ROOM.y)).frame(); + // The tab strip spans the panel's width. + let width = panel.rect("Color Themes"); + for name in ["Color", "Set the current fill or stroke to the selected color", "Set the selected color to the current color"] { + let at = panel.rect(name); + assert!(at.left() >= width.left() && at.right() <= width.right(), "{name} at {at:?} is outside the panel {width:?}"); + } +} + +#[test] +fn the_color_wheel_box_and_its_strip_stay_inside_the_panel() { + let mut app = app_with_rect(); + app.ui.color_wheel.view = color_wheel::View::Box; + let panel = Panel::new(app, color_wheel::show); + let (field, strip) = (panel.rect("Color box"), panel.rect("Hue")); + assert!(strip.height() <= field.height(), "the strip {strip:?} is taller than the box {field:?}"); + assert!(field.right() <= ROOM.x && strip.right() <= ROOM.x, "the box {field:?} or its strip {strip:?} runs past the panel"); +} From bf4b1fb01f9164fe031c7d8c3333c717c6314621 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 14:05:50 -0800 Subject: [PATCH 64/78] =?UTF-8?q?Print:=20the=20printer=20row=20shows=20Se?= =?UTF-8?q?tup=E2=80=A6=20for=20the=20printer=20chosen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Print dialog never set the framework dialog's driver controls, so the printer row had no Setup… button and print.printerSetup could not be reached from the dialog. - The row shows Setup… when the print service can open printer settings and the destination is a printer. For PDF File, and when the service cannot open printer settings, the row has no Setup…. Before the port the dialog showed the button disabled in those cases, with a tooltip; the framework's printer row can only show or hide it, so it is now hidden and has no tooltip. - The pump sets the controls after the frame has drawn the row, so a change of printer shows on the next frame. The pump asks for that frame when the controls change, and the row updates without waiting for input. - A Setup… press while no printer settings are available is ignored. --- crates/ui-egui/src/dialogs/print.rs | 66 +++++++++++++++++------ crates/ui-egui/src/dialogs/tests_print.rs | 53 ++++++++++++++++++ 2 files changed, 104 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index e988d10099..255495d286 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -19,7 +19,9 @@ use std::sync::{Arc, LazyLock, mpsc}; use craft::behavior::{ColumnWidth, EditEvent, EditEvents, IconId, Mixed}; -use craft::print::ui::{Destination, HostedPrint, PrintAnswer, PrintFinish, PrintLayout, PrintMode, PrintSection, PrintSheet, Printer, State}; +use craft::print::ui::{ + Destination, DriverControls, HostedPrint, PrintAnswer, PrintFinish, PrintLayout, PrintMode, PrintSection, PrintSheet, Printer, State, +}; use craft::ui::buttons::ToggleButton; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; @@ -106,6 +108,8 @@ struct Open { art: Option<(ArtKey, egui::TextureHandle)>, /// `print.preview` of the settings and document it was run for. preview: Option<(Stamp, Arc<Result<Value, String>>)>, + /// The printer row's driver controls, as the dialog was last given them. + driver: DriverControls, } /// The document (uid, revision) and the settings a cached preview belongs to. @@ -116,6 +120,8 @@ type ArtKey = (u64, u64, PrintLayers, [u64; 4], u32); /// What the pump took from the dialog this pass. struct Drained { + /// The printer row's driver controls for the printer chosen. + driver: DriverControls, refresh: bool, /// The preset editor's name. name: String, @@ -197,9 +203,11 @@ fn start( }; let taken: Vec<String> = taken_names(app); let named = editing.clone(); + let driver = driver(has_setup(app), &state.settings.destination); let mut hosted = HostedPrint::new(state, fields, sections(&Lists::of(app))) .mode(mode) .layout(PrintLayout::Sections) + .driver(driver) .header(header) .json_form(|fields, out| out.extend(nested(form::json_of(&KEYS, fields)))) .check_name(move |name: &str| refusal(&taken, &named, name).map(|_| PresetError::NameTaken)) @@ -209,7 +217,7 @@ fn start( hosted.set_json_field(&ctx, "name", json!(name))?; } let id = dialogs.with(|h| h.open(hosted)); - app.print_dialog.open = Some(Open { id, mode, preset, editing, art: None, preview: None }); + app.print_dialog.open = Some(Open { id, mode, preset, editing, art: None, preview: None, driver }); Ok(Value::Null) } @@ -280,6 +288,18 @@ fn destinations(app: &mut VectorcraftApp) -> (Vec<Printer>, bool) { (list, service) } +/// Whether the print service can open a printer's settings (`print.printerSetup`). +fn has_setup(app: &VectorcraftApp) -> bool { + app.services.print.as_ref().is_some_and(|s| s.has_setup()) +} + +/// The printer row's Setup…: shown when the print service can open printer settings (`setup`) and `destination` +/// is a printer. +fn driver(setup: bool, destination: &Destination) -> DriverControls { + let printer = matches!(destination, Destination::Printer(name) if name != PDF_FILE); + if setup && printer { DriverControls::Page } else { DriverControls::None } +} + /// The names a new preset may not take: [Default] and the saved presets. fn taken_names(app: &VectorcraftApp) -> Vec<String> { std::iter::once(DEFAULT_PRESET.to_string()).chain(app.session.prefs.print_presets.iter().map(|p| p.name.clone())).collect() @@ -302,13 +322,13 @@ pub(super) fn settings(fields: &DialogFields) -> Value { /// The work of the open dialog, once per frame: the printer list, Setup…, the preview, the placement the preview was /// dragged to, the presets and OK. -pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { +pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(mut open) = app.print_dialog.open.take() else { return }; let Some(dialogs) = app.dialogs() else { app.print_dialog.open = Some(open); return; }; - if serve(app, &dialogs, &mut open) { + if serve(app, ctx, &dialogs, &mut open) { app.print_dialog.open = Some(open); } } @@ -319,22 +339,38 @@ fn on<R>(dialogs: &WindowDialogs, f: impl FnOnce(&mut HostedPrint) -> R) -> Opti } /// One pass of the pump over the open dialog; false once it has closed. -fn serve(app: &mut VectorcraftApp, dialogs: &WindowDialogs, open: &mut Open) -> bool { - let Some(mut d) = on(dialogs, |p| Drained { - refresh: p.take_refresh(), - name: p.preset_name().to_string(), - // Print Settings… opens the driver's dialog of the printer chosen. - setup: if p.take_setup() { p.json_fields().and_then(|f| f["printer"].as_str().map(str::to_string)) } else { None }, - moves: p.take_moves(), - events: p.take_preset_events(), - ok: p.take_ok(), - settings: settings(p.fields_mut()), - sheet: p.sheet_index(), +fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, open: &mut Open) -> bool { + let setup = has_setup(app); + let Some(mut d) = on(dialogs, |p| { + // The printer row shows Setup… for the printer chosen, and none for PDF File. + let driver = driver(setup, &p.state().settings.destination); + p.set_driver(driver); + Drained { + driver, + refresh: p.take_refresh(), + name: p.preset_name().to_string(), + // Setup… opens the settings of the printer chosen. + setup: if p.take_setup() && driver != DriverControls::None { + p.json_fields().and_then(|f| f["printer"].as_str().map(str::to_string)) + } else { + None + }, + moves: p.take_moves(), + events: p.take_preset_events(), + ok: p.take_ok(), + settings: settings(p.fields_mut()), + sheet: p.sheet_index(), + } }) else { // Closed: its answer was acted on when the OK was held. let _ = dialogs.with(|h| h.take_by_id::<HostedPrint>(open.id)); return false; }; + // The row was drawn this frame with the controls of the printer before: the next frame shows the new ones. + if d.driver != open.driver { + open.driver = d.driver; + ctx.request_repaint(); + } if d.refresh { let (list, _) = destinations(app); let (tx, rx) = mpsc::channel(); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 67d45de47e..3429cf323e 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -223,6 +223,59 @@ impl PrintService for UprightQueue { } } +/// The printers whose settings the setup service was asked to open. +type Setups = Rc<RefCell<Vec<Option<String>>>>; + +/// A print service that opens printer settings, recording each printer it was asked for. +struct SetupPrint(Jobs, Setups); + +impl PrintService for SetupPrint { + fn printers(&mut self) -> Vec<Printer> { + MockPrint(self.0.clone()).printers() + } + + fn print(&mut self, job: &PrintJob) -> Result<String, String> { + MockPrint(self.0.clone()).print(job) + } + + fn has_setup(&self) -> bool { + true + } + + fn setup(&mut self, printer: Option<&str>) -> Result<(), String> { + self.1.borrow_mut().push(printer.map(str::to_string)); + Ok(()) + } +} + +#[test] +fn setup_opens_the_settings_of_the_printer_chosen() { + let setups = Setups::default(); + let services = Services { print: Some(Box::new(SetupPrint(Jobs::default(), setups.clone()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + press(&mut app, "Setup…"); + set(&mut app, "printer", json!("Office")); + press(&mut app, "Setup…"); + assert_eq!(*setups.borrow(), [Some("Proofer".to_string()), Some("Office".to_string())], "the default printer, then the one chosen"); + // PDF File has no printer settings. + set(&mut app, "printer", json!("PDF File")); + // The frame after the change draws the row with PDF File's controls. + pump(&mut app); + pump(&mut app); + let r = call_raw(&mut app, "ui.click", json!({"control": {"name": "Setup…"}})); + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(setups.borrow().len(), 2); + // A service without printer settings shows no Setup…. + let (mut app, _) = self::app(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + let r = call_raw(&mut app, "ui.click", json!({"control": {"name": "Setup…"}})); + assert_eq!(r["ok"], false, "{r}"); +} + #[test] fn a_landscape_job_goes_upright_to_a_queue_that_does_not_turn_it() { let sizes = |pdf: &[u8]| vectorcraft_pdf::info(pdf, None).unwrap().pages.iter().map(|p| (p.width, p.height)).collect::<Vec<_>>(); From 99ffa0ebd81f8d766e8d49e169e9aa4fbbd40a2e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 16:59:34 -0800 Subject: [PATCH 65/78] Plug-ins: a command's menu.after is checked before its spaces are trimmed A menu.after value with a control character at either end, or longer than 64 characters before its spaces are trimmed, is refused with the same error as other wrongly shaped values. --- crates/plugins/src/manifest.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 80906ceac6..b9e36cfd24 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -90,11 +90,11 @@ impl MenuPlace { let after = match o.get("after") { None => None, Some(Value::String(s)) => { - let s = s.trim(); - if s.is_empty() || s.chars().count() > 64 || s.chars().any(char::is_control) { + let trimmed = s.trim(); + if trimmed.is_empty() || s.chars().count() > 64 || s.chars().any(char::is_control) { return Err(format!("`{key}` must be 1-64 printable characters")); } - Some(s.to_string()) + Some(trimmed.to_string()) } Some(_) => return Err(format!("`{key}` must be a string")), }; @@ -1442,6 +1442,7 @@ mod tests { } let long = format!(r#"{{"path":["Select"],"after":"{}"}}"#, "x".repeat(65)); + let padded = format!(r#"{{"path":["Select"],"after":" {} "}}"#, "x".repeat(64)); for (menu, says) in [ (r#"{"path":["File"]}"#, "`menu.path` must be one of"), (r#"{"path":["Help"]}"#, "`menu.path` must be one of"), @@ -1461,7 +1462,9 @@ mod tests { (r#"{"path":["Select"],"after":null}"#, "`menu.after` must be a string"), (r#"{"path":["Select"],"after":" "}"#, "`menu.after` must be 1-64 printable characters"), (r#"{"path":["Select"],"after":"In\u0007verse"}"#, "`menu.after` must be 1-64 printable characters"), + (r#"{"path":["Select"],"after":"\nInverse\n"}"#, "`menu.after` must be 1-64 printable characters"), (long.as_str(), "`menu.after` must be 1-64 printable characters"), + (padded.as_str(), "`menu.after` must be 1-64 printable characters"), (r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#, "duplicate field `menu`"), ] { let e = Manifest::parse(with(2, menu).as_bytes()).unwrap_err().to_string(); From 466c4e98c7524c3401ddbbf2b9a347b247280702 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 17:02:26 -0800 Subject: [PATCH 66/78] Graphic Styles: the large tip is a card thumbnail (size.thumb.card) wide and its square picture fills it, in place of a fixed 132 pt square --- crates/ui-egui/src/panels/graphic_styles.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 9d1a522a80..0633f3fbcd 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -20,7 +20,7 @@ use craft::behavior::{EditEvent, GesturePhase, IconId, Selection}; use craft::ui::contract::{ Bind, DropAt, DropPayload, DropPlace, Entry, ListDrag, MemoProps, PopupKind, ReorderMove, SelectMode, Show as _, ShowContainer as _, Trigger, }; -use craft::ui::display::{Divider, Picture}; +use craft::ui::display::{Divider, Picture, PictureSize}; use craft::ui::list::ThumbAspect; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::patterns::presets::{ @@ -30,9 +30,10 @@ use craft::ui::primitives::{ ContentPainterCx, IconSpec, PaintShape, Priority, Revision, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, }; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; +use craft::ui::runtime::env::Env; use craft::ui::sections::{FooterAction, FooterBar, FooterOutput, Panel}; use craft::ui::style::DataColor; -use egui::{Color32, Rect, Sense, TextureHandle, Ui, pos2, vec2}; +use egui::{Color32, Rect, TextureHandle, Ui, pos2}; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::style_libs::STYLE_LIBRARIES; @@ -132,9 +133,6 @@ fn thumbnails(ctx: &egui::Context, salt: &'static str) -> Thumbnails<StyleKey> { Thumbnails::in_context(ctx, salt, ThumbnailOptions::new()) } -/// Side of the large preview shown while the pointer rests on a style. -const LARGE: f32 = 132.0; - thread_local! { // PLAN: the sheet drops RENDERER, but `render` and `render_object` need one renderer that outlives a call. static RENDERER: RefCell<vectorcraft_render::Renderer> = RefCell::new(vectorcraft_render::Renderer::new()); @@ -387,10 +385,13 @@ fn render_object(app: &VectorcraftApp, doc: &Document, n: &Node, g: &GraphicStyl /// The tip over a style: it large, on the selected object when there is one, with its name. fn large_tip(app: &VectorcraftApp, thumbs: &StyleThumbs, ui: &mut Ui, key: &StyleKey) { let Some(i) = thumbs.d.graphic_style_index(key) else { return }; - let px = (LARGE * ui.ctx().pixels_per_point()).round() as u32; + // The preview is a card thumbnail (`size.thumb.card`) wide, and as tall: the tip is that wide, and the square + // picture fills it. + let side = Env::of(ui).tokens.size.thumb.card; + let px = (side * ui.ctx().pixels_per_point()).round() as u32; let look = thumbs.looks.get(i).copied().unwrap_or_default(); let tex = object_preview(app, ui.ctx(), &thumbs.d.graphic_styles[i], look, thumbs.look.preview, px); - let (r, _) = ui.allocate_exact_size(vec2(LARGE, LARGE), Sense::hover()); + ui.set_max_width(side); let texture = tex.as_ref().map(TextureHandle::id); // Decorative: the style's name below it says what it shows. Picture::painter("", ThumbAspect::SQUARE, move |cx, rect| { @@ -399,7 +400,8 @@ fn large_tip(app: &VectorcraftApp, thumbs: &StyleThumbs, ui: &mut Ui, key: &Styl None => draw.data_fill(&PaintShape::Rect(rect, egui::CornerRadius::ZERO), DataColor::new(Color32::WHITE)), }) }) - .show_at(ui, r); + .extent(PictureSize::Fill) + .show(ui); ui.label(key); } From 95c0d489ad4c2c0f9a44278423704e787f2d3a12 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 17:02:26 -0800 Subject: [PATCH 67/78] Tests: the Map Art surface preview of the classic 3D dialog is as tall as the theme's plot size and at least as wide, read from the canvas named Surface in the accessibility tree --- crates/ui-egui/src/dialogs/revolve/tests.rs | 29 +++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index f11bc461bf..53f7a888fe 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -158,6 +158,35 @@ fn map_art_maps_a_symbol_onto_a_surface_of_extrude_and_bevel_classic() { assert!(params.get("__mapArt").is_none() && params.get("__mapSurface").is_none(), "the dialog's own state stays out of the effect"); } +/// The theme's plot size, as a pass of the app's interface resolves it. +fn plot_size() -> egui::Vec2 { + let mut plot = None; + crate::testing::ui_context() + .run_ui(Default::default(), |ui| { + let size = craft::ui::runtime::env::Env::of(ui).tokens.size.plot; + plot = Some(vec2(size.width, size.height)); + }) + .textures_delta + .clear(); + plot.expect("the pass ran") +} + +#[test] +fn map_art_surface_preview_takes_the_themes_plot_size() { + let mut h = opened(with_symbol("M50 50L150 50L150 150L50 150Z"), json!({"effect":CLASSIC_EXTRUDE,"item":null})); + h.set("__page", json!("mapArt")); + let plot = plot_size(); + let tree = h.fixture.tree(); + let surface = h + .fixture + .by_role(craft::ui::contract::Role::CANVAS) + .into_iter() + .find(|t| tree.name_of(t.node) == Some("Surface")) + .expect("Map Art shows the surface canvas"); + assert_eq!(surface.rect.height(), plot.y, "the preview is as tall as the theme's plot: {:?}", surface.rect); + assert!(surface.rect.width() >= plot.x, "the preview is at least as wide as the theme's plot: {:?}", surface.rect); +} + #[test] fn map_art_maps_no_more_surfaces_than_an_object_takes() { let max = vectorcraft_effects::MAX_MAPS; From 854feab9830c45b8079222edd6d7cb6e506e8550 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 17:02:27 -0800 Subject: [PATCH 68/78] Revolve gizmo: the rings, plates and readouts draw through the content painter's own painter, and the Transparency panel imports DataColor with the other style types --- crates/ui-egui/src/dialogs/revolve_gizmo.rs | 12 +++++------- crates/ui-egui/src/panels/transparency.rs | 3 ++- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/revolve_gizmo.rs b/crates/ui-egui/src/dialogs/revolve_gizmo.rs index 7afd12ac16..985b13174a 100644 --- a/crates/ui-egui/src/dialogs/revolve_gizmo.rs +++ b/crates/ui-egui/src/dialogs/revolve_gizmo.rs @@ -22,7 +22,7 @@ use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDia use craft::ui::primitives::{ContentPainterCx, TextRun}; use craft::ui::runtime::focus::KeyUse; use craft::ui::style::{ComponentStyle, StyleColor, StyleCx, TypeRole}; -use egui::{Painter, Pos2, Rect, Response, Stroke, Ui, Vec2, vec2}; +use egui::{Pos2, Rect, Response, Stroke, Ui, Vec2, vec2}; use serde_json::json; use vectorcraft_effects::{CLASSIC_REVOLVE, REVOLVE}; use vectorcraft_geom::Point; @@ -572,7 +572,6 @@ impl Component for RevolveGizmo<'_> { let content = ui.content_painter(cx); let paint = Paint { content: &content, - painter: &content.painter, style: cx.style, view: &space.view, subject: self.subject, @@ -610,9 +609,8 @@ fn light_position(g: Geometry, options: Revolve) -> Pos2 { /// What a pass draws with. struct Paint<'a> { - /// The content painter, which lays out and paints the labels. + /// The content painter: its `painter` draws the rings and plates, and its `Draw` lays out and paints the labels. content: &'a ContentPainterCx<'a>, - painter: &'a Painter, style: &'a RevolveGizmoStyle, view: &'a CanvasView, subject: &'a Subject, @@ -626,7 +624,7 @@ struct Paint<'a> { impl Paint<'_> { fn rotation(&self) { - let (g, s, painter) = (self.g, self.style, self.painter); + let (g, s, painter) = (self.g, self.style, &self.content.painter); for (axis, ring) in g.rings.iter().enumerate() { let hot = self.active == Some(axis); let ink = if hot { s.hot } else { s.axis(axis) }; @@ -668,7 +666,7 @@ impl Paint<'_> { } fn light(&self) { - let (g, s, painter) = (self.g, self.style, self.painter); + let (g, s, painter) = (self.g, self.style, &self.content.painter); let options = light_options(&self.subject.fields); let radius = g.radius * 1.4; painter.circle_stroke(g.center, radius, Stroke::new(1.0, s.muted.egui().gamma_multiply(0.3))); @@ -732,7 +730,7 @@ impl Paint<'_> { /// `text` on a plate centred at `at`. fn readout(&self, text: &str, at: Pos2) { - let (s, painter) = (self.style, self.painter); + let (s, painter) = (self.style, &self.content.painter); self.text(text, s.ink, |size| { painter.rect_filled(Rect::from_center_size(at, size + vec2(14.0, 8.0)), 4.0, s.plate.egui()); at - size * 0.5 diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index a3f37bf4a1..1fafa33563 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -25,6 +25,7 @@ use craft::ui::primitives::{ use craft::ui::primitives::{Revision, ThumbPaint}; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; use craft::ui::runtime::env::UnitKind; +use craft::ui::style::DataColor; use craft::ui::text::NumberField; use egui::{Color32, Ui}; use serde_json::{Value, json}; @@ -193,7 +194,7 @@ fn mask_row( store.paint(cx, rect, s, paper); } if disabled { - let red = craft::ui::style::DataColor::new(super::swatches::OFF_MARK); + let red = DataColor::new(super::swatches::OFF_MARK); cx.with_draw(|draw| { for line in [[rect.left_top(), rect.right_bottom()], [rect.right_top(), rect.left_bottom()]] { draw.stroke(&PaintShape::Path(line.to_vec()), StrokeWidth::Thick, red); From 4c3b4b54649002318b3334a2c693effa307d73f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 17:03:09 -0800 Subject: [PATCH 69/78] Color panel: the Fill and Stroke wells show a gradient, None and a pattern through PairWell::paint and well_paint, as the Tools panel's proxy does, instead of black, as production's Color panel did --- crates/ui-egui/src/panels/color.rs | 7 ++++--- crates/ui-egui/src/panels/color/tests.rs | 23 +++++++++++++++++++++++ crates/ui-egui/src/tests/panel_harness.rs | 6 ++++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 0db7310e92..80f1be75a8 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -32,6 +32,7 @@ use vectorcraft_color::{Color, GradientKind, Paint}; use super::{Live, active_paint, color_json, live_run, proxy_events}; use crate::VectorcraftApp; use crate::edits::{EditPath, apply_event}; +use crate::paint_preview::well_paint; /// The layout the app's panel and its menu use. const LAYOUT: ColorPanelLayout = ColorPanelLayout::FillStroke; @@ -532,11 +533,11 @@ fn switch_rgb_units(app: &mut VectorcraftApp) -> bool { app.ui.color_panel.rgb_percent } -/// The proxy's paint as one well: the colour of a solid paint or a gradient's first stop. +/// The proxy's paint as one well, drawn as the Tools panel's proxy draws it (a gradient, None or a +/// pattern as itself), and the color the panel is given for it: a solid paint's color, black for any other paint. fn well(label: &'static str, paint: &Paint, mixed: bool) -> (PairWell, Srgba) { let color = srgba(&paint.color().unwrap_or(Color::BLACK)); - // PLAN: PairWell::paint (wg.W48) would also show gradients and None as they are. - (PairWell::new(label, if mixed { Mixed::Mixed } else { Mixed::Same(color) }), color) + (PairWell::paint(label, if mixed { Mixed::Mixed } else { Mixed::Same(well_paint(paint, &|_| None)) }), color) } /// Draw numeric paint controls and run what they report. diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index 102bf09995..e63fc09e7a 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -381,3 +381,26 @@ fn picked_mesh_points_are_the_color_the_panel_shows_and_edits() { assert_eq!(picked(&app), vec![0, middle], "the Shift-click adds the top middle point"); assert_eq!(crate::panels::mixed_paints(&app, &ctx), (true, false), "picking recomputes it"); } + +/// The panel's Fill and Stroke wells show a gradient and None as the Tools panel's proxy does, +/// not as black. +#[test] +fn the_wells_show_a_gradient_and_none_as_the_tools_proxy_does() { + use crate::tests::panel_harness::Panel; + let painted = || { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops}})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + app + }; + let color = Panel::new(painted(), show); + let tools = Panel::new(painted(), crate::panels::proxy); + // The wells are unnamed parts of the pair, so they are found by the value each one reads as. + let wells = tools.values(); + assert_eq!(wells.len(), 2, "the Tools proxy's two wells read as {wells:?}"); + assert_ne!(wells[0], wells[1], "a gradient and None read differently"); + for well in &wells { + assert!(color.shows_value(well), "the Color panel shows a well that reads as {well:?}"); + } +} diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 0949ef8c80..574da463f5 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -306,6 +306,12 @@ impl Panel { self.fixture.tree().description_of(self.look(name).node).map(str::to_owned) } + /// The value texts of the latest frame's controls, in tree order. + pub(crate) fn values(&self) -> Vec<String> { + let tree = self.fixture.tree(); + tree.keys().into_iter().filter_map(|key| tree.value_of(key)).map(str::to_owned).collect() + } + /// Whether a control in the latest frame holds the value text `value`. pub(crate) fn shows_value(&self, value: &str) -> bool { self.shows_value_with(|shown| shown == value) From 1ac56ef3ba54503aa1a25ab4d0b6cfb1352a6314 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 17:54:20 -0800 Subject: [PATCH 70/78] Scripts: script.grants reports a grants file that is a link to a missing file A link in the grants file's place whose target is missing is there but cannot be read, so script.grants fails on it and script.grants.revoke leaves it as it is, instead of treating it as a missing grants file. --- crates/engine/src/script/files.rs | 3 ++- crates/engine/src/tests/script_io.rs | 12 +++++++++++- docs/mcp.md | 2 +- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 1ef963d992..476fbde5ad 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -947,7 +947,8 @@ fn try_read_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> { fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Value>> { let bytes = match read_head(store, MAX_STORE_BYTES) { Ok(bytes) => bytes, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + // A link whose target is missing is there but cannot be read. + Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::fs::symlink_metadata(store).is_err() => return Ok(Vec::new()), Err(e) => return Err(e), }; if bytes.len() > MAX_STORE_BYTES { diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 50191fafb4..e5d854850d 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1321,7 +1321,8 @@ fn script_file_grants_file_that_cannot_be_read_is_left_as_it_is() { } /// `script.grants` fails on a grants file that is there but cannot be read (another version, not -/// JSON, no list of grants, over the size limit or not a file), lists none when it is missing, and +/// JSON, no list of grants, over the size limit, not a file, or on Unix a link to a missing file), +/// lists none when it is missing, and /// lists the well-formed grants of one that holds a grant that is not. #[test] fn script_grants_fails_on_a_grants_file_that_cannot_be_read() { @@ -1346,6 +1347,15 @@ fn script_grants_fails_on_a_grants_file_that_cannot_be_read() { let mut s = with_data(&base); assert!(s.execute("script.grants", &json!({})).is_err(), "a folder in the grants file's place"); let _ = std::fs::remove_dir_all(base); + #[cfg(unix)] + { + let base = folder("list-dangling"); + std::fs::create_dir_all(base.join("settings")).unwrap(); + std::os::unix::fs::symlink(base.join("gone.json"), base.join("settings/Script Grants.json")).unwrap(); + let mut s = with_data(&base); + assert!(s.execute("script.grants", &json!({})).is_err(), "a link to a missing file in the grants file's place"); + let _ = std::fs::remove_dir_all(base); + } let base = folder("list-missing"); let mut s = with_data(&base); assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([]), "a missing grants file lists none"); diff --git a/docs/mcp.md b/docs/mcp.md index 32bd63b4ef..e51290531e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3117,7 +3117,7 @@ is given as its file name alone. `script.grants.revoke {script?, path?, all?}` r a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but -cannot be read is left as it is: `script.grants` and `script.grants.revoke` fail, and a grant picked with Always is +cannot be read, a link to a missing file included, is left as it is: `script.grants` and `script.grants.revoke` fail, and a grant picked with Always is not kept. A missing grants file lists no grants, and `script.grants` leaves out a grant in the file that is not well formed. A script cannot run either command. From 51cad798675808d4f16725e4b26488544600a4a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 18:06:52 -0800 Subject: [PATCH 71/78] Control bar: test area type's vertical alignment rank with type selected - New test: with area type selected, the vertical alignment buttons leave the bar before Opacity, Recolor Artwork and the Style picker, and the Align buttons after them leave first. It runs with the Character and Paragraph groups shown and with both turned off, so it covers the vertical alignment group's rank and the Align strip's rank when only vertical alignment shows. - The `rank::TYPE` doc comment now says where the rank sits: type groups leave after Select Similar, Snapping and the X/Y/W/H fields, and before every other member. --- crates/ui-egui/src/chrome/control_bar.rs | 4 +-- crates/ui-egui/src/chrome/tests.rs | 31 +++++++++++++++++++++++- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 7cecd2414d..ab90d71dc2 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -24,8 +24,8 @@ pub(crate) mod rank { /// The inline X/Y/W/H fields and the Snapping menu. pub const FIELDS: u8 = 2; /// The type groups (Character, Paragraph and area type's vertical alignment) and the Align buttons after them: - /// they leave before the members ahead of them, so Opacity, the Style picker and Recolor Artwork show while type - /// is selected. + /// they leave after Select Similar, Snapping and the X/Y/W/H fields and before every other member, so Opacity, + /// the Style picker and Recolor Artwork show while type is selected. pub const TYPE: u8 = 3; /// The parts of a group that its other members work without: the width profile, Recolor Artwork, Global Edit /// Options, Document Setup, an image's Edit Original. diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 75dbc0754d..5b91533f58 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -2431,7 +2431,7 @@ fn the_control_bar_leaves_members_out_in_its_priority_order() { assert!(seen.iter().any(|s| s[0] && !s[1]), "some width shows the Align buttons without the fields"); } -/// With type selected, the Character and Paragraph groups leave the Control bar before the members ahead of them: at +/// With type selected, the Character and Paragraph groups leave the Control bar before Opacity and the Style group: at /// every width that shows the Character group, Opacity, Recolor Artwork and the Style picker show too, the Paragraph /// group leaves before the Character group, the Align buttons leave before the Paragraph group, and some width shows /// Opacity without them. @@ -2454,6 +2454,35 @@ fn the_type_groups_leave_the_control_bar_before_opacity_and_style() { assert!(seen.iter().any(|s| s[2] && !s[0]), "some width shows Opacity without the Character group"); } +/// With area type selected, its vertical alignment buttons leave the Control bar before Opacity and the Style group, +/// and after the Align buttons that follow them, with the Character and Paragraph groups shown and with both off. +#[test] +fn the_vertical_alignment_buttons_leave_the_control_bar_before_opacity_and_style() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let area = json!({"x": 10, "y": 10, "text": "Hi", "area": {"width": 100, "height": 120}}); + let text = app.run("text.create", area).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [text] })).unwrap(); + let mut bar = control_shown(app); + let names = ["Align Top", "Opacity:", "Recolor Artwork", "Style:", "Horizontal Align Left", "Paragraph:"]; + for type_groups in [true, false] { + for group in ["character", "paragraph"] { + bar.app().run("window.control.options", json!({ "group": group, "visible": type_groups })).unwrap(); + } + let case = if type_groups { "with the type groups" } else { "without the type groups" }; + let seen = control_bar_widths(&mut bar, &names); + assert!(seen.iter().any(|s| s[..5].iter().all(|shown| *shown)), "{case}: a wide bar shows {:?}", &names[..5]); + for s in &seen { + assert!(!s[0] || s[1..4].iter().all(|shown| *shown), "{case}: Align Top shows only with {:?}: {s:?}", &names[1..4]); + assert!(!s[4] || s[0], "{case}: the Align buttons show only with Align Top: {s:?}"); + assert!(type_groups || !s[5], "{case}: the Paragraph group is off: {s:?}"); + assert!(!type_groups || !s[0] || s[5], "{case}: Align Top shows only with the Paragraph group: {s:?}"); + } + assert!(seen.iter().any(|s| s[1] && !s[0]), "{case}: some width shows Opacity without Align Top"); + } +} + /// The names of the bar's X, Y, W and H fields, in their order. const BAR_FIELDS: [&str; 4] = ["X position", "Y position", "Width", "Height"]; From a6783443d38222d836510547cc574384ce568785 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 18:21:18 -0800 Subject: [PATCH 72/78] Document Info: an image with no pixels across or down gives no resolution A linked image whose width or height is 0 has no area, so its row reads `resolution unavailable` and `effectivePpi` is null, whatever its transform. --- crates/engine/src/cmd/docinfo.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index f58eb97e41..f20a413473 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -209,10 +209,11 @@ impl ImageRow { // A distorted image is measured at its middle, as `image.info` measures it. let xf = vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf); let ppi = super::place::effective_ppi(xf); - // A transform that lays both pixel axes on one line leaves the image no area. The - // determinant is compared with the product of the two axes' lengths, at any scale. + // An image with no pixels across or down has no area, and so does one whose transform lays + // both pixel axes on one line. The determinant is compared with the product of the two + // axes' lengths, at any scale. let [xx, xy, yx, yy, ..] = xf.as_coeffs(); - let has_area = xf.determinant().abs() > 1e-9 * xx.hypot(xy) * yx.hypot(yy); + let has_area = im.width > 0 && im.height > 0 && xf.determinant().abs() > 1e-9 * xx.hypot(xy) * yx.hypot(yy); let embedded = im.link.is_none(); let memory = || u64::from(im.width).checked_mul(u64::from(im.height))?.checked_mul(4); Self { @@ -2482,6 +2483,21 @@ mod tests { assert!(ppi.len() == 2 && ppi.iter().all(|v| (v / 7.2e8 - 1.0).abs() < 1e-9), "{}", i["imageObjects"][0]); } + /// An image with no pixels across or down has no area, so its row gives no resolution whatever + /// its transform. + #[test] + fn a_zero_pixel_image_has_no_resolution() { + let mut s = Session::new(); + let half = Affine::scale(0.5); + images_in(&mut s, &[("a", "image/png", Some("/art/none.png"), 0, 800, half), ("a", "image/png", Some("/art/flat.png"), 1200, 0, half)]); + let i = s.execute("document.info", &json!({})).unwrap(); + let objects = i["imageObjects"].as_array().cloned().unwrap_or_default(); + assert_eq!(objects.iter().map(|o| o["effectivePpi"].clone()).collect::<Vec<_>>(), [Value::Null, Value::Null], "{objects:?}"); + let text = s.execute("document.info", &json!({"format": "text"})).unwrap()["text"].as_str().unwrap_or_default().to_string(); + assert!(text.contains("none.png: PNG; 0 × 800 px; resolution unavailable — /art/none.png\n"), "{text}"); + assert!(text.contains("flat.png: PNG; 1200 × 0 px; resolution unavailable — /art/flat.png\n"), "{text}"); + } + /// A number of bytes reads in B below 1 KiB, else in KiB, MiB or GiB to a tenth, and a /// resolution to a tenth without a trailing `.0`. #[test] From 567dfccdfb1404173219cc2662ec276376854877 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 18:36:15 -0800 Subject: [PATCH 73/78] Export for Screens: an artboard's picture keeps its proportions in its square tile or row thumbnail (fit_rect), as production's did --- .../ui-egui/src/dialogs/export_for_screens.rs | 7 ++-- crates/ui-egui/src/dialogs/tests_screens.rs | 36 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index cd54515553..5e765e306c 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -43,7 +43,7 @@ use craft::ui::display::{Shade, Text}; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize, ToggleCell, ToggleState}; use craft::ui::patterns::form_dialogs::{FormDialog, PathRow}; -use craft::ui::primitives::ContentPainterCx; +use craft::ui::primitives::{ContentPainterCx, fit_rect}; use craft::ui::runtime::env::Label; use craft::ui::tabs::{Tab, TabKind, TabStrip}; use craft::ui::text::TextField; @@ -601,8 +601,11 @@ impl ExportForScreensDialog { let items = Items(doc.artboards.iter().map(|a| (u64::from(a.id), a.name.clone())).collect()); let caption = |at: usize| format!("{} {}", at + 1, items.0.get(at).map_or("", |(_, name)| name.as_str())); let thumbs = &self.thumbs; + // The artboard keeps its proportions, centered in the tile or the row's thumbnail. let paint = |at: usize, cx: &ContentPainterCx, rect: egui::Rect| match thumbs.get(at).cloned().flatten() { - Some(tex) => cx.picture(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), 0.0), + Some(tex) => { + cx.picture(tex.id(), fit_rect(rect, tex.size_vec2()), egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), 0.0) + } None => { cx.painter.rect_filled(rect, 0.0, egui::Color32::WHITE); } diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 622fce6a5e..544985b8d2 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -162,6 +162,42 @@ fn checked_artboards_read_as_a_range() { } } +/// The rect the frame `shapes` paint `texture` over; `None` when none paints it. +fn painted(shapes: &[egui::epaint::ClippedShape], texture: egui::TextureId) -> Option<egui::Rect> { + fn walk(shape: &egui::Shape, texture: egui::TextureId, out: &mut Option<egui::Rect>) { + match shape { + egui::Shape::Vec(all) => all.iter().for_each(|s| walk(s, texture, out)), + egui::Shape::Mesh(mesh) if mesh.texture_id == texture => { + let at = mesh.calc_bounds(); + *out = Some(out.map_or(at, |r| r.union(at))); + } + _ => {} + } + } + let mut out = None; + shapes.iter().for_each(|clipped| walk(&clipped.shape, texture, &mut out)); + out +} + +/// The grid's tiles and the list's thumbnails are square; an artboard of another shape keeps its +/// proportions in them. +#[test] +fn an_artboards_picture_keeps_its_proportions() { + let (mut app, _) = app(1, false); + open(&mut app); + for view in ["grid", "list"] { + set(&mut app, "view", json!(view)); + frame(&mut app); + let ctx = app.ui_ctx.clone().expect("a test app has a window"); + let out = crate::testing::part_frame(&mut app, &ctx, Default::default(), |app, ui| app.ui(ui)); + let tex = app.canvas.artboard_thumbs.as_ref().and_then(|(_, thumbs)| thumbs.first().cloned().flatten()).expect("the artboard has a picture"); + let drawn = painted(&out.shapes, tex.id()).expect("the artboard's picture is drawn"); + let (picture, shown) = (tex.size_vec2(), drawn.size()); + assert!(picture.x > picture.y, "the 60×40 pt artboard is wider than high"); + assert!((shown.x / shown.y - picture.x / picture.y).abs() < 0.02, "{view}: a {picture:?} picture is drawn {shown:?}"); + } +} + #[test] fn opens_with_the_artboards_the_artboard_tool_selected_and_exports_only_them() { let (mut app, log) = app(4, true); From ceb49e78965ff38da092f707e080e138d94085b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 18:38:30 -0800 Subject: [PATCH 74/78] New Document: Orientation shows a page icon for Portrait and for Landscape, named for screen readers, as production's buttons did --- crates/ui-egui/src/dialogs/new_document.rs | 51 +++++++++++++++++++++- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 025a5336af..e60e9e0b3a 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -20,7 +20,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::{Background, ColorMode, Unit}; use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, RASTER_PPI}; -use craft::behavior::Mixed; +use craft::behavior::{IconId, Mixed}; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Segmented}; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, clicked}; @@ -299,7 +299,10 @@ impl DocumentSettings for VcNewDocument { Row::new().show(ui, |ui, _| { Field::new(height.clone()).show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths)); Field::new(orientation.clone()).show(ui, |ui, _| { - let entries = [Entry::new(Orientation::Portrait, portrait.clone()), Entry::new(Orientation::Landscape, landscape.clone())]; + let entries = [ + Entry::new(Orientation::Portrait, portrait.clone()).icon(IconId::new("orientation_portrait")), + Entry::new(Orientation::Landscape, landscape.clone()).icon(IconId::new("orientation_landscape")), + ]; picked = Segmented::new(orientation.clone(), Bind::given(current), &entries).show(ui).value().cloned(); }); Field::new(artboards.clone()).show(ui, |ui, _| { @@ -760,6 +763,50 @@ mod tests { app.run("prefs.set", json!({"key": "unitsGeneral", "value": units, "documentUnits": false})).unwrap(); } + /// The window's frames with the dialog open, laid out; the last frame's output. + fn laid_out(app: &mut VectorcraftApp) -> egui::FullOutput { + let ctx = ctx(app); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let mut frame = |i: u32| { + let input = egui::RawInput { time: Some(0.1 * f64::from(i)), screen_rect: Some(screen), ..Default::default() }; + crate::testing::part_frame(app, &ctx, input, |app, ui| app.ui(ui)) + }; + (0..3).for_each(|i| drop(frame(i))); + frame(3) + } + + /// Orientation shows a page icon for Portrait and for Landscape, named for screen readers, as production's buttons + /// did; before, it showed the words, and Landscape, cut short, ran into Artboards. + #[test] + fn orientation_shows_two_page_icons_beside_artboards() { + fn texts(s: &egui::Shape, out: &mut Vec<(String, egui::Pos2)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect().center())), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let mut app = app(); + open(&mut app); + let out = laid_out(&mut app); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let bounds = |label: &str, role: egui::accesskit::Role| { + let (_, n) = nodes.iter().find(|(_, n)| n.label() == Some(label) && n.role() == role).unwrap_or_else(|| panic!("no {role:?} {label}")); + n.bounds().expect("bounds") + }; + let landscape = bounds("Landscape", egui::accesskit::Role::RadioButton); + let artboards = bounds("Artboards", egui::accesskit::Role::SpinButton); + assert!(landscape.x1 <= artboards.x0, "Landscape {landscape:?} stays left of Artboards {artboards:?}"); + let group = bounds("Orientation", egui::accesskit::Role::RadioGroup); + let mut drawn = Vec::new(); + out.shapes.iter().for_each(|s| texts(&s.shape, &mut drawn)); + let inside: Vec<_> = drawn + .iter() + .filter(|(_, at)| (group.x0..=group.x1).contains(&f64::from(at.x)) && (group.y0..=group.y1).contains(&f64::from(at.y))) + .collect(); + assert!(inside.is_empty(), "the segments draw icons, not words: {inside:?}"); + } + /// Recent shows each entry as it was made: a portrait and a landscape A3 are two documents, and /// the built-in cards turn to the picked orientation (#2860). #[test] From bd6d7c9117cd0f17d613cb40a31e027b6d93f08b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 16:58:01 -0800 Subject: [PATCH 75/78] Dialogs: rows of controls in the 3D, Character Style, Adjust Colors and Color Guide dialogs are framework Rows and Stacks, and presses inside a row apply after it A framework container may run its body more than once in a pass. The HP-GL pen rows now draw from the dialog's values on every run and report a typed color, Remove, Add and a swatch press, which apply once after the rows; the picker opens after them. A picked pen color is no longer left unread when the table is longer than a plot takes. The classic 3D surface navigator and Map Art buttons, Bevel Shape, the light's Add and Delete buttons and its color row, Stylistic Sets, the Adjust Colors channels and the Color Guide Options sliders use Row and Stack the same way. A Stack's measuring run no longer writes the values the Adjust Colors and Color Guide Options rows edit. --- .../ui-egui/src/dialogs/char_style_options.rs | 9 +- crates/ui-egui/src/dialogs/color_balance.rs | 3 +- .../src/dialogs/color_guide_options.rs | 3 +- crates/ui-egui/src/dialogs/form.rs | 23 ++++- crates/ui-egui/src/dialogs/hpgl_options.rs | 49 +++++----- crates/ui-egui/src/dialogs/revolve.rs | 96 ++++++++++--------- crates/ui-egui/src/dialogs/tests_hpgl.rs | 20 +++- crates/ui-egui/src/dialogs/three_d_classic.rs | 41 ++++---- 8 files changed, 150 insertions(+), 94 deletions(-) diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 9fcb532c33..25c7891020 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -8,8 +8,9 @@ use std::sync::Arc; use craft::behavior::Mixed; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _}; +use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogResult, FieldRefusal}; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{ DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesDialog, PropertiesTab, PropertyRow, TabLayout, }; @@ -843,7 +844,9 @@ fn sets_row() -> Param { .and_then(|v| v.as_array().map(|tags| tags.iter().filter_map(Value::as_str).map(str::to_string).collect())) .unwrap_or_default(); let mut clicked = None; - let line = ui.horizontal_wrapped(|ui| { + let line = Row::new().wrap(true).show(ui, |ui, _| { + // The row's body may run more than once in a pass: the last run's click applies. + clicked = None; for set in &vectorcraft_text::EXTRA_FEATURES[..20] { let current = listed.iter().find(|t| bare(t) == *set).map(|t| !t.starts_with('-')); if let (_, Some(next)) = tri_box(ui, current, Some(Label::from(set.to_string())), set) { @@ -864,7 +867,7 @@ fn sets_row() -> Param { fields.set("ot_sets", FieldValue::Json(json!(listed))); } } - line.response + line.output }) } diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 5dfeb4e018..c82918426b 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -199,12 +199,11 @@ fn track(key: &str, x: f32) -> Srgba { /// The channel rows of the current mode. fn channels(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut CustomContext) -> egui::Response { - ui.vertical(|ui| { + super::form::stacked(ui, fields, |ui, fields| { for (key, label) in mode(fields).channels { percent_row(ui, fields, key, label, |x| track(key, x)); } }) - .response } fn rows() -> Vec<Param> { diff --git a/crates/ui-egui/src/dialogs/color_guide_options.rs b/crates/ui-egui/src/dialogs/color_guide_options.rs index 37836565e4..721064005b 100644 --- a/crates/ui-egui/src/dialogs/color_guide_options.rs +++ b/crates/ui-egui/src/dialogs/color_guide_options.rs @@ -32,12 +32,11 @@ pub fn open(app: &mut VectorcraftApp) { fields.set("steps", f64::from(current.steps)); fields.set("amount", f64::from(current.amount)); let steps = Param::custom("steps", field_label(tl!("Steps:")), |ui, fields, _| { - ui.vertical(|ui| { + super::form::stacked(ui, fields, |ui, fields| { slider(ui, fields, "steps", tl!("Steps:"), 1.0..=f64::from(GuideOptions::MAX_STEPS), None); let ends = [(0.0, tl!("Less").to_owned()), (100.0, tl!("More").to_owned())]; slider(ui, fields, "amount", tl!("Variation:"), 0.0..=100.0, Some(ends)); }) - .response }) .companions(["amount"]); let variations = Param::custom("variations", field_label(tl!("Variations:")), move |ui, fields, _| { diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 538141fc11..6d81d18214 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -4,9 +4,11 @@ use std::collections::HashMap; -use craft::ui::contract::{Bind, Show as _}; +use craft::ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft::ui::layout_components::Stack; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind, encode}; use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; +use craft::ui::runtime::measure; use craft::ui::text::TextField; use craft::ui::value_drag::SliderScale; use serde_json::{Map, Value, json}; @@ -200,6 +202,25 @@ pub(crate) fn fields_of(params: &[Param], json: &Map<String, Value>) -> DialogFi fields } +/// Shows `body` in a `Stack` as rows of a custom dialog row that edit `fields`. The stack may run its body more than +/// once in a pass: every run edits a copy of the values as they stand here, and the copy of the run that is not a +/// measuring run replaces them after the stack. +pub(super) fn stacked(ui: &mut egui::Ui, fields: &mut DialogFields, mut body: impl FnMut(&mut egui::Ui, &mut DialogFields)) -> egui::Response { + let before = fields.clone(); + let mut edited = None; + let shown = Stack::new().show(ui, |ui, _| { + let mut run = before.clone(); + body(ui, &mut run); + if measure::effect(ui.ctx(), "dialog rows edit their values") { + edited = Some(run); + } + }); + if let Some(edited) = edited { + *fields = edited; + } + shown.output +} + /// The command or effect parameters of the dialog values `fields`: the UI-only keys (`__*`, `preview`) are dropped. pub(crate) fn json_of(params: &[Param], fields: &DialogFields) -> Map<String, Value> { fields diff --git a/crates/ui-egui/src/dialogs/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs index 3cfe0ecdfc..50eab143f5 100644 --- a/crates/ui-egui/src/dialogs/hpgl_options.rs +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -18,7 +18,7 @@ use craft::ui::choice::{Radio, RadioGroup, Swatch}; use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::dialog::DialogId; use craft::ui::layout_components::{Row, Stack}; -use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog}; use craft::ui::runtime::env::Env; use craft::ui::style::rgba_color; use craft::ui::text::TextField; @@ -143,18 +143,13 @@ fn pen_key(i: usize) -> String { fn pens_param() -> Param { Param::custom("pens", tl!("Pens:"), |ui, fields, cx| { take_picked_pens(fields); - // The rows draw from the values as they stand here and the edits apply after them: the stack's body may run - // twice in a pass. - let mut drawn = fields.clone(); + // The stack's body may run more than once in a pass: every run draws from the values as they stand here, and + // what the last run asked for applies after the stack. let mut asked = PensAsked::default(); - let shown = Stack::new().show(ui, |ui, _| { - asked = pens_ui(ui, &drawn, cx); - if let Some(p) = &asked.pens { - drawn.set("pens", FieldValue::Json(Value::Array(p.clone()))); - } - }); - // An edit of the rows in any run of the body is in `drawn`; a switch of Pen Table drops it. - let edited = table(&drawn).filter(|p| asked.table.is_none() && table(fields).as_ref() != Some(p)); + let shown = Stack::new().show(ui, |ui, _| asked = pens_ui(ui, fields)); + if let Some((i, color)) = asked.pick { + cx.pick_color(&pen_key(i), color); + } match asked.table { Some(true) => cx.request_action("penTable"), Some(false) => { @@ -163,7 +158,7 @@ fn pens_param() -> Param { } None => {} } - if let Some(pens) = edited { + if let Some(pens) = asked.pens { fields.set("pens", FieldValue::Json(Value::Array(pens))); } shown.output @@ -179,11 +174,13 @@ struct PensAsked { table: Option<bool>, /// The pen table after an edit of its rows. pens: Option<Vec<Value>>, + /// The pen whose swatch was pressed, with its color: the picker opens on it. + pick: Option<(usize, Srgba)>, } /// Writes the colors the picker answered into the pen table. fn take_picked_pens(fields: &mut DialogFields) { - let Some(mut pens) = table(fields).filter(|a| a.len() <= MAX_PENS) else { return }; + let Some(mut pens) = table(fields) else { return }; let mut changed = false; for (i, pen) in pens.iter_mut().enumerate() { if let Some([r, g, b]) = fields.color(&pen_key(i)) { @@ -200,7 +197,7 @@ fn take_picked_pens(fields: &mut DialogFields) { /// The pens row. Switching to Pen Table asks the host (`penTable`): the table starts from the document's pens, which /// this draw cannot reach. -fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields, cx: &mut CustomContext) -> PensAsked { +fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields) -> PensAsked { let mut asked = PensAsked::default(); let list = table(fields); let mut on = list.is_some(); @@ -219,29 +216,35 @@ fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields, cx: &mut CustomContext) -> let Some(mut pens) = list.filter(|a| asked.table.is_none() && a.len() <= MAX_PENS) else { return asked }; let mut changed = false; let n = pens.len(); + // What the rows asked for: a typed color per pen, the pen whose swatch or Remove was pressed. Each run of the + // stack's body starts them afresh from the same pens. + let mut typed: Vec<Option<String>> = vec![None; n]; let mut remove = None; Stack::new().scroll(Scroll::vertical()).room_height(180.0).show(ui, |ui, _| { - for (i, pen) in pens.iter_mut().enumerate() { + typed.iter_mut().for_each(|t| *t = None); + (remove, asked.pick) = (None, None); + for (i, pen) in pens.iter().enumerate() { Row::new().id_salt(("hpgl-pen-row", i)).show(ui, |ui, _| { ui.label((i + 1).to_string()); let mut color = pen.as_str().and_then(Rgba::from_hex).unwrap_or(Rgba::rgb(0, 0, 0)); if Swatch::new(tl!("Pen color"), Srgba::from(color)).show(ui).clicked { - cx.pick_color(&pen_key(i), Srgba::from(color)); + asked.pick = Some((i, Srgba::from(color))); } let before = color; TextField::hex(tl!("Pen color"), Bind::bound(&mut color)).id_salt(("hpgl-pen", i)).show(ui); - if color != before - && let Some(typed) = pen_color(&color.to_hex()) - { - *pen = json!(typed); - changed = true; - } + typed[i] = (color != before).then(|| pen_color(&color.to_hex())).flatten(); if IconButton::new(IconId::new("trash")).label(tl!("Remove")).enabled(n > 1).show(ui).clicks > 0 { remove = Some(i); } }); } }); + for (pen, typed) in pens.iter_mut().zip(typed) { + if let Some(typed) = typed { + *pen = json!(typed); + changed = true; + } + } if Button::new(tl!("Add")).enabled(n < MAX_PENS).show(ui).clicks > 0 { // A new pen starts as the last one's color, ready to be changed. pens.push(pens.last().cloned().unwrap_or_else(|| json!("#000000"))); diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 3804c4ea3a..a61190970e 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -9,7 +9,8 @@ use craft::behavior::{DisplayOrder, ItemSource, SelectionChange}; use craft::theme::Srgba; use craft::ui::buttons::Button; use craft::ui::contract::Entry; -use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, clicked}; +use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked}; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamKind, ParamRows}; use craft::ui::pickers::Select; use craft::ui::runtime::env::LengthUnits; @@ -369,19 +370,23 @@ pub(crate) fn bevel_row(data: &Data, effect: &str, place: Place) -> Param { }; let default_at = options[..builtin].iter().position(|(_, v, _)| *v == default); let titles: Vec<String> = options.iter().map(|(l, _, _)| l.clone()).collect(); - ui.horizontal(|ui| { - if let Some((_, v, c)) = pick(ui, c3("Bevel Shape"), &titles, current, default_at).and_then(|i| options.get(i)) { - set_value(fields, "bevel", v); - if let Some((n, p)) = c { - set_value(fields, BEVEL_NAME, &json!(n)); - set_value(fields, BEVEL_PROFILE, p); - } + // The row's body may run more than once in a pass: it reports the pick and the press, which apply after it. + let (mut picked, mut edit) = (None, false); + let row = Row::new().show(ui, |ui, _| { + picked = pick(ui, c3("Bevel Shape"), &titles, current, default_at); + edit = place == Place::Panel && pressed(ui, tl!("Edit Bevels…"), file, None); + }); + if let Some((_, v, c)) = picked.and_then(|i| options.get(i)) { + set_value(fields, "bevel", v); + if let Some((n, p)) = c { + set_value(fields, BEVEL_NAME, &json!(n)); + set_value(fields, BEVEL_PROFILE, p); } - if place == Place::Panel && pressed(ui, tl!("Edit Bevels…"), file, None) { - fields.set("__editBevels", true); - } - }) - .response + } + if edit { + fields.set("__editBevels", true); + } + row.output }) .companions([BEVEL_NAME, BEVEL_PROFILE, "__editBevels"]) } @@ -675,12 +680,13 @@ fn light_color_row() -> Param { Param::custom("lightColor", tl!("Color"), |ui, fields, cx| { let hex = fields.text("lightColor").unwrap_or("#ffffff").to_owned(); let color = Srgba::from_hex(&hex).unwrap_or(Srgba::rgb(1.0, 1.0, 1.0)); - ui.horizontal(|ui| { - if pressed(ui, &hex.to_uppercase(), true, Some(tl!("Color"))) { - cx.pick_color("__lightPick", color); - } - }) - .response + // The row's body may run more than once in a pass: the picker opens after it. + let mut ask = false; + let row = Row::new().show(ui, |ui, _| ask = pressed(ui, &hex.to_uppercase(), true, Some(tl!("Color")))); + if ask { + cx.pick_color("__lightPick", color); + } + row.output }) .opens_with("#ffffff") } @@ -711,11 +717,11 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { // The classic effects' lights have no colour. let settings: Vec<Param> = settings.into_iter().filter(|p| !(classic && p.key == "lightColor")).collect(); Param::custom("lights", tl!("Lights"), move |ui, fields, cx| { + if let Some(Value::String(hex)) = fields.color("__lightPick").map(|c| json!(Srgba::from_rgb_array(c).to_hex())) { + fields.remove("__lightPick"); + set_light_value(fields, "lightColor", json!(hex)); + } ui.vertical(|ui| { - if let Some(Value::String(hex)) = fields.color("__lightPick").map(|c| json!(Srgba::from_rgb_array(c).to_hex())) { - fields.remove("__lightPick"); - set_light_value(fields, "lightColor", json!(hex)); - } let mut list = explicit_lights(fields).unwrap_or_else(|| vec![light_record(fields)]); let mut index = light_index(fields, list.len()); let titles: Vec<String> = (1..=list.len()).map(|i| format!("{} {i}", c3("Light"))).collect(); @@ -724,27 +730,31 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { } // Add Light is off while a setting of the single light is mixed. let mixed = explicit_lights(fields).is_none() && LIGHT_KEYS.iter().any(|(_, key)| fields.is_mixed(key)); - ui.horizontal(|ui| { - if pressed(ui, tl!("Add Light"), list.len() < vectorcraft_three_d::MAX_LIGHTS && !mixed, None) { - let mut added = selected_light(fields); - let defaults = vectorcraft_effects::default_params(fields.text("__effect").unwrap_or_default()).unwrap_or(json!({})); - for (_, key) in LIGHT_KEYS { - if let Some(value) = defaults.get(key) { - set_value(&mut added, key, value); - } - } - set_value(&mut added, "lightRotation", &json!(0.0)); - set_value(&mut added, "lightHeight", &json!(90.0)); - list.push(light_record(&added)); - index = list.len() - 1; - fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); - } - if pressed(ui, tl!("Delete Light"), list.len() > 1, None) && index < list.len() { - list.remove(index); - index = index.min(list.len().saturating_sub(1)); - fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); - } + // The row's body may run more than once in a pass: it reports the presses, which apply after it. + let (mut add, mut delete) = (false, false); + Row::new().show(ui, |ui, _| { + add = pressed(ui, tl!("Add Light"), list.len() < vectorcraft_three_d::MAX_LIGHTS && !mixed, None); + delete = pressed(ui, tl!("Delete Light"), list.len() > 1, None); }); + if add { + let mut added = selected_light(fields); + let defaults = vectorcraft_effects::default_params(fields.text("__effect").unwrap_or_default()).unwrap_or(json!({})); + for (_, key) in LIGHT_KEYS { + if let Some(value) = defaults.get(key) { + set_value(&mut added, key, value); + } + } + set_value(&mut added, "lightRotation", &json!(0.0)); + set_value(&mut added, "lightHeight", &json!(90.0)); + list.push(light_record(&added)); + index = list.len() - 1; + fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); + } + if delete && index < list.len() { + list.remove(index); + index = index.min(list.len().saturating_sub(1)); + fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); + } fields.set("__light", i64::try_from(index).unwrap_or(0)); if place == Place::Panel || classic { super::revolve_lights::sphere(ui, fields, cx, classic); diff --git a/crates/ui-egui/src/dialogs/tests_hpgl.rs b/crates/ui-egui/src/dialogs/tests_hpgl.rs index dab1dbe8c6..0330cd7521 100644 --- a/crates/ui-egui/src/dialogs/tests_hpgl.rs +++ b/crates/ui-egui/src/dialogs/tests_hpgl.rs @@ -160,8 +160,9 @@ fn pen_table_starts_from_the_art_s_pens_and_comes_back() { assert_eq!(pens(&fields(&app)), json!(automatic)); } -/// A press of Add adds one pen and a press of One Pen per Color sets the table aside, though the rows' body may run -/// twice in the pass that reads the press. +/// A press of Add adds one pen, a press of a pen's Remove removes that pen, a press of a pen's swatch opens one picker +/// whose color that pen takes, and a press of One Pen per Color sets the table aside, though the rows' bodies run more +/// than once in the pass that reads the press. #[test] fn pen_rows_apply_each_press_once() { let (mut app, _) = app(1); @@ -171,11 +172,24 @@ fn pen_rows_apply_each_press_once() { press_control(&mut app, json!({"name": "Add", "role": "Button"})); frame(&mut app); assert_eq!(pens(&fields(&app)), json!(["#ff0000", "#000000", "#000000"])); + press_control(&mut app, json!({"name": "Remove", "role": "Button", "index": 0})); + frame(&mut app); + assert_eq!(pens(&fields(&app)), json!(["#000000", "#000000"])); + // The second pen's swatch opens the picker over the dialog; its OK colors that pen alone. + press_control(&mut app, json!({"name": "Pen color", "role": "ColorWell", "index": 1})); + frame(&mut app); + let open = |app: &VectorcraftApp| app.dialogs().map_or(0, |d| d.with(|h| h.open_dialogs().len())); + assert_eq!(open(&app), 2, "one picker opens on the dialog"); + set(&mut app, "color", json!("#00ff00")); + confirm(&mut app); + frame(&mut app); + assert_eq!((open(&app), kind(&app).as_deref()), (1, Some("hpglOptions"))); + assert_eq!(pens(&fields(&app)), json!(["#000000", "#00ff00"])); press_control(&mut app, json!({"name": "One Pen per Color", "role": "RadioButton"})); frame(&mut app); let d = fields(&app); assert!(pens(&d).is_null()); - assert_eq!(serde_json::to_value(d.get("__pens")).unwrap(), json!(["#ff0000", "#000000", "#000000"])); + assert_eq!(serde_json::to_value(d.get("__pens")).unwrap(), json!(["#000000", "#00ff00"])); } /// Pen Table with options the export refuses keeps One Pen per Color and says why, rather than diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 390c536503..70fc5871ed 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -14,6 +14,7 @@ use craft::ui::canvas::{CanvasSpace, canvas_space}; use craft::ui::canvas_controls::SelectionOutline; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::Picture; +use craft::ui::layout_components::Row; use craft::ui::list::ThumbAspect; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind}; use craft::ui::pickers::Select; @@ -288,7 +289,9 @@ fn navigator(count: usize, seen: Vec<bool>) -> Param { Param::custom(MAP_SURFACE, tl!("Surface"), move |ui, fields, _| { let current = shown_surface(fields, count); let mut next = None; - let row = ui.horizontal(|ui| { + let row = Row::new().show(ui, |ui, _| { + // The row's body may run more than once in a pass: the last run's step applies. + next = None; for (icon, tip, target, enabled) in [ ("chevrons_left", tl!("First Surface"), 1, current > 1), ("chevron_left", tl!("Previous Surface"), current.saturating_sub(1), current > 1), @@ -318,7 +321,7 @@ fn navigator(count: usize, seen: Vec<bool>) -> Param { if fields.number(MAP_SURFACE) != Some(shown as f64) { fields.set(MAP_SURFACE, shown as f64); } - row.response + row.output }) } @@ -428,21 +431,25 @@ fn map_actions(flat: Flat, has_map: bool, any_map: bool) -> Param { Param::custom("__mapActions", "", move |ui, fields, _| { let surface = surface_number(fields); let map = maps_of(fields).into_iter().find(|m| m.surface == surface); - ui.horizontal(|ui| { - let fit = Button::new(tl!("Scale to Fit")).enabled(has_map && flat.art.is_some()).show(ui); - if let (true, Some(m), Some(art)) = (fit.clicked(), map.as_ref(), flat.art) { - let art = vectorcraft_geom::Rect::new(0.0, 0.0, art.0, art.1); - let (scale_x, scale_y) = m.fitting_scales(art, (flat.width, flat.height)).unwrap_or((m.scale_x, m.scale_y)); - store_map(fields, surface, Some(&SurfaceMap { x: 0.0, y: 0.0, scale_x, scale_y, ..m.clone() })); - } - if Button::new(tl!("Clear")).enabled(has_map).show(ui).clicked() { - store_map(fields, surface, None); - } - if Button::new(tl!("Clear All")).enabled(any_map).show(ui).clicked() { - fields.set(MAP_ART, FieldValue::Json(json!([]))); - } - }) - .response + // The row's body may run more than once in a pass: it reports the presses, which apply after it. + let (mut fit, mut clear, mut clear_all) = (false, false, false); + let row = Row::new().show(ui, |ui, _| { + fit = Button::new(tl!("Scale to Fit")).enabled(has_map && flat.art.is_some()).show(ui).clicked(); + clear = Button::new(tl!("Clear")).enabled(has_map).show(ui).clicked(); + clear_all = Button::new(tl!("Clear All")).enabled(any_map).show(ui).clicked(); + }); + if let (true, Some(m), Some(art)) = (fit, map.as_ref(), flat.art) { + let art = vectorcraft_geom::Rect::new(0.0, 0.0, art.0, art.1); + let (scale_x, scale_y) = m.fitting_scales(art, (flat.width, flat.height)).unwrap_or((m.scale_x, m.scale_y)); + store_map(fields, surface, Some(&SurfaceMap { x: 0.0, y: 0.0, scale_x, scale_y, ..m.clone() })); + } + if clear { + store_map(fields, surface, None); + } + if clear_all { + fields.set(MAP_ART, FieldValue::Json(json!([]))); + } + row.output }) .full_width() // The page's maps: automation sets them whole, as the rows above edit them one surface at a time. From aadcdb774a7d594a9ff76f50f8716d9aaa40d4de Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 18:45:30 -0800 Subject: [PATCH 76/78] Tests: the progress window's delay counts on the app's clock (now_override in tests), which the background-job tests hold still, and the heavy filter shortcut test keeps its run on a manual job queue, so neither depends on how fast a loaded machine runs --- crates/ui-egui/src/app.rs | 14 ++++++++---- crates/ui-egui/src/background.rs | 14 ++---------- crates/ui-egui/src/export_progress.rs | 13 ++++++----- crates/ui-egui/src/lib.rs | 5 +++-- crates/ui-egui/src/opening.rs | 2 +- crates/ui-egui/src/opening/tests.rs | 2 ++ crates/ui-egui/src/placing.rs | 3 ++- crates/ui-egui/src/placing/tests.rs | 2 ++ crates/ui-egui/src/plugin_runs.rs | 4 ++-- crates/ui-egui/src/shortcuts/tests.rs | 4 ++++ crates/ui-egui/src/tests/plugin_runs.rs | 30 +++++++++++++++++++++++-- crates/ui-egui/src/tests/trace_runs.rs | 4 +++- crates/ui-egui/src/trace_runs.rs | 2 +- 13 files changed, 68 insertions(+), 31 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 225be05ca7..fdf92146d2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -308,6 +308,15 @@ impl VectorcraftApp { /// eframe isn't a dependency of this crate (the host owns the event loop); these entry points are /// called from the host's `eframe::App` impl through `embed`'s hooks. impl VectorcraftApp { + /// Seconds on the app's clock: the monotonic clock, or the time a test set in `now_override`. + pub(crate) fn now(&self) -> f64 { + #[cfg(test)] + if let Some(now) = self.now_override { + return now; + } + now_secs() + } + /// Applies the work that finished off the UI thread. It stays pending while a script runs, since /// every change to the documents ends in a busy error until the script ends. pub(crate) fn poll_finished_work(&mut self) { @@ -415,10 +424,7 @@ impl VectorcraftApp { // Monotonic host time, never egui's `InputState::time`: a hidden window's `logic` replays // the last shown pass's time, freezing recovery, clipboard polling and deadlines. Tests // inject a clock to drive idle scheduling deterministically. - #[cfg(test)] - let now = self.now_override.unwrap_or_else(now_secs); - #[cfg(not(test))] - let now = now_secs(); + let now = self.now(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); self.refresh_replace_font_warning(false); diff --git a/crates/ui-egui/src/background.rs b/crates/ui-egui/src/background.rs index 779f6dc59c..57a9bf1086 100644 --- a/crates/ui-egui/src/background.rs +++ b/crates/ui-egui/src/background.rs @@ -263,6 +263,7 @@ fn start( let id = app.background.next_id; let jobs = app.jobs(); let (sets, status) = (app.ui.status_sets, if label.is_empty() { String::new() } else { format!("{label}…") }); + let started = export_progress::now(app); let bg = &mut app.background; bg.next_id += 1; let tx = bg.results.get_or_insert_with(channel).0.clone(); @@ -280,18 +281,7 @@ fn start( }), ); let line = status.clone(); - bg.jobs.push(Job { - id, - kind, - label: label.clone(), - doc, - progress, - hidden: false, - started: export_progress::now(), - sets, - line, - then: Box::new(then), - }); + bg.jobs.push(Job { id, kind, label: label.clone(), doc, progress, hidden: false, started, sets, line, then: Box::new(then) }); if label.is_empty() { return Ok(json!({ "background": true })); } diff --git a/crates/ui-egui/src/export_progress.rs b/crates/ui-egui/src/export_progress.rs index bfef9a1f61..c8170460a3 100644 --- a/crates/ui-egui/src/export_progress.rs +++ b/crates/ui-egui/src/export_progress.rs @@ -39,9 +39,10 @@ pub(crate) struct Shown { pub hide: Option<&'static str>, } -/// Seconds on the clock the jobs record their start with. -pub(crate) fn now() -> f64 { - craft::platform::clock::monotonic_ms() / 1000.0 +/// Seconds on the clock the jobs record their start with: the app's clock, which a test can hold +/// still. +pub(crate) fn now(app: &VectorcraftApp) -> f64 { + app.now() } /// The window of the first table that has a job it shows. Opening and placing wait for the tables @@ -58,7 +59,7 @@ fn first(app: &VectorcraftApp) -> Option<Shown> { /// no other dialog is open, and runs the command of the button pressed. pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let Some(shown) = first(app) else { return }; - let age = now() - shown.started; + let age = now(app) - shown.started; if age < DELAY { // Nothing else wakes the frame that opens the window. ui.ctx().request_repaint_after(Duration::from_secs_f64(DELAY - age)); @@ -99,7 +100,8 @@ mod tests { use super::DELAY; use crate::{Services, VectorcraftApp, background}; - /// An app whose background writer waits until `go` is set. + /// An app whose background writer waits until `go` is set. Its clock stands still: a job is only + /// old enough for its window after [`age`]. fn app(go: Arc<std::sync::atomic::AtomicBool>) -> VectorcraftApp { let services = Services { write_shared: Some(Arc::new(move |_: &str, _: &[u8]| { @@ -112,6 +114,7 @@ mod tests { }; let mut app = VectorcraftApp::new(Session::new(), services); crate::tests_background::threaded(&mut app); + app.now_override = Some(0.0); app } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 59aa12e06c..4fc00a0a78 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -340,8 +340,9 @@ pub struct VectorcraftApp { pub(crate) pen_end: stylus::PenEnd, /// The window pass whose [`Self::tick`] ran last: work started in that pass, before its end, waits for the next. pub(crate) ticked_pass: Option<u64>, - /// A test's clock for [`Self::tick`], replacing the monotonic clock so idle scheduling can be - /// driven one simulated frame at a time (production always leaves this `None`). + /// A test's clock for [`Self::tick`] and the progress window's delay, replacing the monotonic + /// clock so idle scheduling can be driven one simulated frame at a time (production always + /// leaves this `None`). #[cfg(test)] pub(crate) now_override: Option<f64>, /// An error the next tool choice returns before the engine sees it ([`Self::try_select_tool`]), diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 31e8ce20f2..15235131dd 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -129,7 +129,7 @@ pub(crate) fn finish_answered(app: &mut VectorcraftApp, path: &str, file: ReadFi /// Lists the file being read for `path` and tells the status bar → `{background: true, status}`. fn track(app: &mut VectorcraftApp, path: &str, done: Receiver<Result<ReadFile, String>>, scope: ScopeHandle, token: CancelToken) -> Value { let label = format!("Opening {}", fileio::file_name(path)); - let started = crate::export_progress::now(); + let started = crate::export_progress::now(app); app.opening.pending.push(Pending { path: path.to_string(), label: label.clone(), done, scope, token, hidden: false, started }); let status = format!("{label}…"); app.status(status.clone()); diff --git a/crates/ui-egui/src/opening/tests.rs b/crates/ui-egui/src/opening/tests.rs index 609f3c18a8..2466381a3d 100644 --- a/crates/ui-egui/src/opening/tests.rs +++ b/crates/ui-egui/src/opening/tests.rs @@ -526,6 +526,8 @@ fn bytes(title: &str) -> Vec<u8> { #[test] fn a_file_that_takes_a_while_to_open_shows_a_progress_window() { let mut app = VectorcraftApp::new(Session::new(), Services::default()); + // The app's clock stands still: a read is only old enough for its window after `age`. + app.now_override = Some(0.0); let ctx = crate::testing::ui_context(); assert_eq!(progress(&mut app, &ctx), "", "nothing opening"); start(&mut app, "/art/Big.vectorcraft", bytes("Big")); diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index d70caa18ae..6be029beba 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -363,6 +363,7 @@ fn spawn_labeled( }); let jobs = app.jobs(); app.placing.lane.push(&*jobs, "vectorcraft-place", job); + let started = crate::export_progress::now(app); app.placing.pending.push(Pending { name, label: label.clone(), @@ -375,7 +376,7 @@ fn spawn_labeled( scope: completion, token, hidden: false, - started: crate::export_progress::now(), + started, }); let status = format!("{label}…"); app.status(status.clone()); diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index 385600ab5a..990e449e88 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -2017,6 +2017,8 @@ fn a_file_that_takes_a_while_to_place_shows_a_progress_window() { let mut app = VectorcraftApp::new(Session::new(), services); crate::tests_background::threaded(&mut app); app.placing.off_the_ui_thread = true; + // The app's clock stands still: a read is only old enough for its window after `age`. + app.now_override = Some(0.0); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let ctx = crate::testing::ui_context(); diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index 1f9eae3978..f7c579337c 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -43,7 +43,7 @@ pub struct Running { pub progress: Arc<Progress>, /// Continue in Background: the progress window no longer shows it. pub hidden: bool, - /// When it started, in seconds of the monotonic clock: the progress window's age. + /// [`export_progress::now`] when it started: the progress window's age. started: f64, done: Receiver<Done>, } @@ -89,7 +89,7 @@ pub fn start(app: &mut VectorcraftApp, p: Value) -> Result<Value, String> { }; app.host.jobs().spawn("vectorcraft-plugin", Box::new(job)); let label = format!("Running {who}…"); - let started = craft::platform::clock::monotonic_ms() / 1000.0; + let started = export_progress::now(app); let runs = &mut app.plugin_runs; runs.running.push(Running { label: label.clone(), who, params, progress: shown, hidden: false, started, done }); app.status(label.clone()); diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 0f302c1551..4dc3ffaaa4 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1717,6 +1717,10 @@ fn a_filter_plugin_keeps_its_shortcut_when_replaced_or_reloaded() { fn a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item() { use vectorcraft_plugins::wat as tpl; let mut app = new_app(); + // The background work waits until the test runs it, which it never does: the run started from + // the key is still running when Cancel stops it, however long the frames take. + let jobs = std::sync::Arc::new(craft::host::ManualJobs::new()); + app.host = std::sync::Arc::new(craft::host::Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs).build()); app.session.allow_plugin_grants_from_requests(); app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); let (at_once, asks) = ("test.UI.heavy_filter-at-once", "test.UI.heavy_filter-asks"); diff --git a/crates/ui-egui/src/tests/plugin_runs.rs b/crates/ui-egui/src/tests/plugin_runs.rs index 0ebc06643d..ed161e797f 100644 --- a/crates/ui-egui/src/tests/plugin_runs.rs +++ b/crates/ui-egui/src/tests/plugin_runs.rs @@ -16,7 +16,7 @@ use vectorcraft_plugins::{registry, wat as tpl}; use super::plugins::{approve, window}; use crate::dialogs::plugin::InstallPrompt; -use crate::{VectorcraftApp, dialogs, plugin_runs}; +use crate::{VectorcraftApp, dialogs, export_progress, plugin_runs}; /// An app with a new 200 × 200 pt document. fn app() -> VectorcraftApp { @@ -28,9 +28,11 @@ fn app() -> VectorcraftApp { /// The window of an [`app`] whose background work waits until the test runs it: a run that OK /// started is still running when the frame that started it ends. On threads a fast run could end -/// before a later pass of that frame, which applies it. +/// before a later pass of that frame, which applies it. The app's clock stands still, so the +/// progress window, which would hold the results back, opens only when a test moves the clock. fn held_window() -> (Harness<'static, VectorcraftApp>, Arc<ManualJobs>) { let mut app = app(); + app.now_override = Some(0.0); let jobs = Arc::new(ManualJobs::new()); app.host = Arc::new(Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs.clone()).build()); (window(app), jobs) @@ -158,6 +160,30 @@ fn a_heavy_filter_runs_off_the_ui_thread_and_applies_as_one_undo_step() { assert!(app.ui.status.is_empty(), "{}", app.ui.status); } +/// The progress window opens once the run is [`export_progress::DELAY`] old on the app's clock, +/// however long the frames take; after Continue in Background closes it the result applies. +#[test] +fn the_progress_window_opens_by_the_app_clock() { + use egui_kittest::kittest::Queryable; + let (mut h, jobs) = held_window(); + let id = "test.ui.heavy.clock"; + install(h.state_mut(), id, 1, "{}"); + let undo = h.state().session.doc().unwrap().history.undo.len(); + assert_eq!(h.state_mut().run("plugin.dialog", json!({"id": id})).unwrap()["background"], true); + // Only the progress window shows its step. + let step = "The plug-in is computing…"; + frame(&mut h); + assert!(h.query_by_label(step).is_none(), "not before the delay"); + h.state_mut().now_override = Some(export_progress::DELAY); + frame(&mut h); + assert!(h.query_by_label(step).is_some(), "the progress window, after the delay"); + assert_eq!(h.state_mut().run("plugin.hideRuns", json!({})).unwrap(), json!({"hidden": 1})); + frame(&mut h); + assert!(h.query_by_label(step).is_none(), "Continue in Background closed it"); + finish_held(h.state_mut(), &jobs); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo + 1); +} + /// A document edited while the filter runs doesn't take its result: nothing changes, and the status /// bar says to run it again. #[test] diff --git a/crates/ui-egui/src/tests/trace_runs.rs b/crates/ui-egui/src/tests/trace_runs.rs index 5de44dbc68..17a92f9785 100644 --- a/crates/ui-egui/src/tests/trace_runs.rs +++ b/crates/ui-egui/src/tests/trace_runs.rs @@ -282,10 +282,12 @@ fn a_trace_started_before_a_revert_does_not_apply() { #[test] fn the_progress_window_shows_a_trace() { let mut app = app(); + // The app's clock stands still: the trace is only old enough for its window when made so. + app.now_override = Some(0.0); let ctx = crate::testing::ui_context(); crate::menus::invoke(&mut app, "imageTrace.make", json!({"preset": "Default"})); assert!(!progress(&mut app, &ctx, 0.0).contains("Tracing the image"), "not before the delay"); - // The delay counts on the monotonic clock: the trace started that long ago. + // The delay counts on the app's clock: the trace started that long ago. app.trace_runs.running[0].started -= DELAY; progress(&mut app, &ctx, DELAY + 0.05); // a new window measures itself unseen first let shown = progress(&mut app, &ctx, DELAY + 0.1); diff --git a/crates/ui-egui/src/trace_runs.rs b/crates/ui-egui/src/trace_runs.rs index 4f7b4f0dae..341c0c4113 100644 --- a/crates/ui-egui/src/trace_runs.rs +++ b/crates/ui-egui/src/trace_runs.rs @@ -125,7 +125,7 @@ pub fn start(app: &mut VectorcraftApp, command: &str, p: Value, from_panel: bool let _ = tx.send((run, traced)); }) .map_err(|e| e.to_string())?; - let started = crate::export_progress::now(); + let started = crate::export_progress::now(app); app.trace_runs.running.push(Running { started, doc, target, token, superseded: false, steps, from_panel, hidden: false, done }); // This frame may have asked for its next one before the trace started (`tick`): ask now. if let Some(ctx) = &app.ui_ctx { From 57a85d4a55538441fb14bf05b6a65fce06faf8e7 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 18:49:31 -0800 Subject: [PATCH 77/78] Tracing Presets: the selected preset's settings sit beside the list, under its name in strong type Since the port the manager drew the list, its buttons, the preset's name and its settings in one column, with the name in body type. The list and its buttons are now one column and the name and settings a second, as in production and as Perspective Grid Presets lays out the same sheet. The name is set in BodyStrong, and "Presets:" and the built-in note are muted captions. New test: the settings start right of the list's buttons and level with the list, and the name's font differs from its list row's. --- crates/ui-egui/src/dialogs/tracing_presets.rs | 90 ++++++++++--------- .../src/dialogs/tracing_presets/tests.rs | 28 +++++- 2 files changed, 76 insertions(+), 42 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tracing_presets.rs b/crates/ui-egui/src/dialogs/tracing_presets.rs index 917cd5dc50..569f93bf81 100644 --- a/crates/ui-egui/src/dialogs/tracing_presets.rs +++ b/crates/ui-egui/src/dialogs/tracing_presets.rs @@ -20,14 +20,15 @@ use craft::host::{PickRequest, Picked}; use craft::ui::buttons::Button; use craft::ui::contract::SelectMode; use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked}; -use craft::ui::display::Text; -use craft::ui::layout_components::Row; +use craft::ui::display::{Shade, Text}; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow}; // PLAN: assumed `craft::ui::patterns::form_dialogs::FieldValue` and `craft::ui::runtime::env::Label` paths. use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, PromptChoice, StackDialog, StandardPrompt, dialog_id}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; use craft::ui::sections::{DialogRole, FooterButton}; +use craft::ui::style::TypeRole; use serde_json::{Value, json}; use vectorcraft_engine::cmd::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES}; @@ -123,46 +124,55 @@ impl StackDialog for Manager { let (data, action) = (&self.data, &mut self.action); let dialog = Dialog::new(tl!("Tracing Presets")).buttons([FooterButton::new(tl!("Close"), DialogRole::Cancel)]); let shown = dialog.show(ui, |ui, _| { - Text::new(tl!("Presets:")).show(ui); - let out = List::new(tl!("Presets")) - .select(SelectMode::Single) - .max_rows(LIST_ROWS) - .selection(Bind::given(Selection::single(at))) - .show_items(ui, &Labels(&labels), &mut |&k, _| ListRow::new(labels[k].clone())); - for event in out.events { - if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event - && let Some(p) = keys.last().and_then(|&k| list.presets.get(k)) - { - *action = Some(Action::Select(p.0.clone())); - } - } - Row::new().show(ui, |ui, _| { - let buttons = [ - (Button::new(tl!("New…")).tooltip(tl!("A new preset starting from the selected one")), Action::New, true), - (Button::new(tl!("Edit…")), Action::Edit, !builtin), - (Button::new(tl!("Delete")), Action::Delete, !builtin), - (Button::new(tl!("Import…")), Action::Import, true), - (Button::new(tl!("Export…")), Action::Export, any_saved), - ]; - for (button, act, enabled) in buttons { - if clicked(&button.enabled(enabled).show(ui)) { - *action = Some(act); + // The list and its buttons on the left, the selected preset's name and settings on the right. + Row::new().id_salt("presets-body").show(ui, |ui, _| { + Stack::new().id_salt("presets-list").show(ui, |ui, _| { + Text::new(tl!("Presets:")).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + let out = List::new(tl!("Presets")) + .select(SelectMode::Single) + .max_rows(LIST_ROWS) + .selection(Bind::given(Selection::single(at))) + .show_items(ui, &Labels(&labels), &mut |&k, _| ListRow::new(labels[k].clone())); + for event in out.events { + if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event + && let Some(p) = keys.last().and_then(|&k| list.presets.get(k)) + { + *action = Some(Action::Select(p.0.clone())); + } } - } + Row::new().show(ui, |ui, _| { + let buttons = [ + (Button::new(tl!("New…")).tooltip(tl!("A new preset starting from the selected one")), Action::New, true), + (Button::new(tl!("Edit…")), Action::Edit, !builtin), + (Button::new(tl!("Delete")), Action::Delete, !builtin), + (Button::new(tl!("Import…")), Action::Import, true), + (Button::new(tl!("Export…")), Action::Export, any_saved), + ]; + for (button, act, enabled) in buttons { + if clicked(&button.enabled(enabled).show(ui)) { + *action = Some(act); + } + } + }); + }); + Stack::new().id_salt("presets-details").show(ui, |ui, _| { + Text::new(list_label(preset)).role(TypeRole::BodyStrong).show(ui); + // The selected preset's settings, as the editor shows them, to read only: edits land in a copy. + let mut params = preset.1.clone(); + // PLAN: the rows components take no `enabled` prop; the scope's `Ui` is disabled for them. + ui.scope(|ui| { + ui.disable(); + rows::main_rows(ui, &mut params, data, RowsHost::Dialog); + rows::advanced_rows(ui, &mut params, data, RowsHost::Dialog, None); + }); + if builtin { + Text::new(tl!("Built-in presets don't change: New makes a copy you can edit.")) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); + } + }); }); - // PLAN: the sheet's two columns and a strong name need layout and text variants that are not in the bundle; stacked and plain here. - Text::new(list_label(preset)).show(ui); - // The selected preset's settings, as the editor shows them, to read only: edits land in a copy. - let mut params = preset.1.clone(); - // PLAN: the rows components take no `enabled` prop; the scope's `Ui` is disabled for them. - ui.scope(|ui| { - ui.disable(); - rows::main_rows(ui, &mut params, data, RowsHost::Dialog); - rows::advanced_rows(ui, &mut params, data, RowsHost::Dialog, None); - }); - if builtin { - Text::new(tl!("Built-in presets don't change: New makes a copy you can edit.")).show(ui); - } }); shown.output.result(|| ()) } diff --git a/crates/ui-egui/src/dialogs/tracing_presets/tests.rs b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs index 1c1d25b0eb..3df7af4cc8 100644 --- a/crates/ui-egui/src/dialogs/tracing_presets/tests.rs +++ b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs @@ -66,9 +66,17 @@ fn finish(app: &mut VectorcraftApp, ctx: &egui::Context, ok: bool) { /// The texts the dialogs paint, once they have faded in (each frame is a quarter second on). fn frame_texts(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<String> { - fn walk(s: &egui::Shape, out: &mut Vec<String>) { + frame_runs(app, ctx).into_iter().map(|(text, _, _)| text).collect() +} + +/// The texts the dialogs paint with where each is drawn and its font, once they have faded in. +fn frame_runs(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<(String, egui::Rect, Option<egui::FontId>)> { + fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect, Option<egui::FontId>)>) { match s { - egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Text(t) => { + let font = t.galley.job.sections.first().map(|section| section.format.font_id.clone()); + out.push((t.galley.text().to_string(), t.galley.rect.translate(t.pos.to_vec2()), font)); + } egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), _ => {} } @@ -145,6 +153,22 @@ fn new_and_edit_save_through_the_editor_and_cancel_saves_nothing() { assert_eq!((field(&app, "name"), field(&app, "params")), (json!("Tracing Preset 1"), edited)); } +#[test] +fn the_selected_preset_shows_beside_the_list_under_a_strong_name() { + let (mut app, ctx) = windowed(Default::default()); + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + pass(&mut app, &ctx); + let runs = frame_runs(&app, &ctx); + let rect = |names: &[&str]| runs.iter().find(|r| names.contains(&r.0.as_str())).map(|r| r.1); + let (Some(export), Some(mode)) = (rect(&["Export…"]), rect(&["Mode", "Mode:"])) else { panic!("Export… and Mode: {runs:?}") }; + // The settings column starts right of the list's buttons and level with the list, not under it. + assert!(mode.left() >= export.right() && mode.top() < export.top(), "Mode {mode:?}, Export… {export:?}"); + // The selected preset's name over its settings is set apart from its row in the list. + let names: Vec<_> = runs.iter().filter(|r| r.0 == "[Default]").collect(); + assert_eq!(names.len(), 2, "{runs:?}"); + assert_ne!(names[0].2, names[1].2, "the list row and the name: {names:?}"); +} + #[test] fn the_editor_shows_document_library_s_library_and_colors() { let (mut app, ctx) = windowed(Default::default()); From 24be579cc47f57abdff8bf53666f28d79300ac57 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 24 Nov 2026 18:57:45 -0800 Subject: [PATCH 78/78] Tests: the empty-password Place tests use the dialog host The Import PDF dialog now lives in the craft dialog host, so an_empty_password_still_asks_for_the_password closes each dialog with cancel_by_id and checks it with the file's dialog_id helper instead of app.ui.dialog. --- crates/ui-egui/src/dialogs/tests_import_pdf.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 5051b8338b..30a1aa9d65 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -525,14 +525,18 @@ fn an_empty_password_still_asks_for_the_password() { let mut app = app(); let bytes = pdf(&[PdfPage::new(120.0, 60.0, "1 0 0 rg 0 0 20 20 re f")], Some("pw")); let data = vectorcraft_format::base64_encode(&bytes); + let close = |app: &VectorcraftApp| { + let id = dialog_id(app).expect("an Import PDF dialog"); + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx(app), id))); + assert!(!is_open(app)); + }; for password in [json!(""), json!(null)] { - app.ui.dialog = None; let p = json!({"name": "locked.pdf", "dataBase64": data, "password": password}); assert!(import_pdf::offer_place_password(&mut app, &p), "asks with password {password}"); assert_eq!((field(&app, "__locked"), field(&app, "__passwordOnly")), (json!(true), json!(true))); + close(&app); } - app.ui.dialog = None; let p = json!({"name": "locked.pdf", "dataBase64": data, "password": "pw"}); assert!(!import_pdf::offer_place_password(&mut app, &p), "a given password is placed with"); - assert!(app.ui.dialog.is_none()); + assert!(!is_open(&app)); }