From 4f065ccbbf72f683047b1559dedaaa03dc480a5c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:52:50 -0800 Subject: [PATCH 001/178] 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 002/178] 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 003/178] 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 004/178] 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 005/178] 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 006/178] 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 007/178] 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 008/178] 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 009/178] 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 010/178] 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 011/178] 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 012/178] 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 013/178] 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 014/178] 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 015/178] 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 016/178] 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 426ea942687c8005305ffaf2fd3defc7c1e97bdc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 15:32:07 -0800 Subject: [PATCH 017/178] Live Paint: bucket paint commands replay from the journal with any tool While the Live Paint Bucket is active, a paint or stroke command that names no objects changes only the colors the bucket paints with. The journal recorded the params as given, and the active tool is not journaled, so a replay with the Selection tool active painted the selection instead. The paint and stroke commands now take defaultsOnly: true, which keeps a command without ids, id or item to the defaults with any tool active. When the bucket routed a command, its journal entry notes defaultsOnly: true, also when the params gave false. library.use (a color, gradient or pattern) and swatch.library.add with apply note it too and pass it to the commands they run. - defaultsOnly is a bool. It is refused with ids, id or item, and in stroke.setAdvanced with brush. - With New Art Has Basic Appearance off, new-art inheritance does not replace the defaults after such a command, unless a later step of a batch selects another first object or changes its appearance. - A preview with defaultsOnly: true, and the one after it, starts from the defaults the interaction began with, and a cancel puts them back. - paint.sampleColor with a stop and defaultsOnly reads the default's gradient. Test: live_paint_bucket_commands_replay_from_the_journal_with_another_tool (engine). Docs: docs/mcp.md, the Live Paint Bucket paragraph; params text of each command. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/gradient.rs | 2 +- crates/engine/src/cmd/gradpresets.rs | 2 +- crates/engine/src/cmd/library.rs | 26 +++-- crates/engine/src/cmd/newart.rs | 43 +++++++- crates/engine/src/cmd/paint.rs | 95 ++++++++++++---- crates/engine/src/cmd/stroke.rs | 13 ++- crates/engine/src/cmd/swatchlib.rs | 6 +- crates/engine/src/cmd/xform.rs | 11 +- crates/engine/src/lib.rs | 5 + crates/engine/src/session/documents.rs | 1 + crates/engine/src/session/edit.rs | 14 ++- crates/engine/src/session/execute.rs | 11 +- crates/engine/src/tests/build.rs | 145 +++++++++++++++++++++++++ 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/es.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/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/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/mcp.md | 8 +- 35 files changed, 367 insertions(+), 57 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..86b73ee159 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -853,7 +853,7 @@ pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; /// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. pub use object::{reflect_axis, scale_factors, shear_tangent}; -pub(crate) use paint::LIVE_PAINT_BUCKET; +pub(crate) use paint::{LIVE_PAINT_BUCKET, asks_defaults_only}; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 8cf1091492..2b14fdba2d 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. 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 paint the bucket paints with)", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, defaultsOnly?: bool (as paint.setFill), strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. 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), or `defaultsOnly: true` is given, only the default changes (the paint the bucket paints with)", has_doc, edit_gradient ), diff --git a/crates/engine/src/cmd/gradpresets.rs b/crates/engine/src/cmd/gradpresets.rs index c8eaa07135..89deda43ad 100644 --- a/crates/engine/src/cmd/gradpresets.rs +++ b/crates/engine/src/cmd/gradpresets.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Apply Gradient Preset", [], None, - "{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (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, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}", + "{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, defaultsOnly?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (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), or `defaultsOnly: true` is given, only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}", has_doc, apply ), diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 4d562a76e7..3da204e3ad 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -713,7 +713,7 @@ pub fn specs() -> Vec { "Use Library Item", [], None, - "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}", + "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), defaultsOnly?: bool (colors, gradients, patterns: paint only the defaults, as with paint.setFill's; the journal records it for an item used while the Live Paint Bucket is the active tool), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}", has_doc, use_item ), @@ -1186,6 +1186,7 @@ fn item_param<'a>(s: &Session, p: &'a Value, cmd: &str) -> Result<(String, Kind, fn use_item(s: &mut Session, p: &Value) -> Result { const C: &str = "library.use"; + super::switch_or(p, "defaultsOnly", false, C)?; // A replay (the journal) carries what the item was, so it doesn't depend on the library. let recorded = p.get("recorded").cloned(); let (kind, data) = match recorded { @@ -1247,18 +1248,20 @@ fn use_item(s: &mut Session, p: &Value) -> Result { } Kind::FillColor | Kind::StrokeColor => { let stroke = to_stroke(p, kind)?; + let only = super::paint::defaults_only(s, p, C)?; let color = data.get("color").cloned().ok_or_else(|| bad(C, "no colour"))?; let set = if stroke { "paint.setStroke" } else { "paint.setFill" }; match str_param(&data, "spot").map(str::trim).filter(|n| !n.is_empty()) { - Some(ink) => use_spot(s, set, ink, &color, &data)?, + Some(ink) => use_spot(s, set, ink, &color, &data, only)?, None => { - s.execute(set, &json!({ "color": color }))?; + s.execute(set, &super::paint::with_defaults_only(json!({ "color": color }), only))?; } } Ok(json!({ "kind": if stroke { "strokeColor" } else { "fillColor" } })) } Kind::FillGradient | Kind::StrokeGradient => { let stroke = to_stroke(p, kind)?; + let only = super::paint::defaults_only(s, p, C)?; let damaged = || bad(C, "the library item is damaged"); let mut g: GradientPaint = data.get("gradient").cloned().and_then(|v| serde_json::from_value(v).ok()).ok_or_else(damaged)?; if !clean_gradient(&mut g) { @@ -1268,12 +1271,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result { for st in &mut g.gradient.stops { st.color = super::paint::new_color(s, &json!({}), st.color); } - super::paint::apply_paint(s, &json!({}), Paint::Gradient(Box::new(g)), !stroke)?; + super::paint::apply_paint(s, &super::paint::with_defaults_only(json!({}), only), Paint::Gradient(Box::new(g)), !stroke)?; Ok(json!({ "kind": if stroke { "strokeGradient" } else { "fillGradient" } })) } Kind::FillPattern | Kind::StrokePattern => { let stroke = to_stroke(p, kind)?; - let pattern = use_pattern(s, &data, stroke)?; + let only = super::paint::defaults_only(s, p, C)?; + let pattern = use_pattern(s, &data, stroke, only)?; Ok(json!({ "kind": if stroke { "strokePattern" } else { "fillPattern" }, "pattern": pattern })) } Kind::CharStyle | Kind::ParaStyle => { @@ -1304,8 +1308,8 @@ fn use_item(s: &mut Session, p: &Value) -> Result { /// Paint with library spot colour `ink` (`color` its full-strength colour, `data`'s `tint` its /// tint) through `set` (paint.setFill or paint.setStroke), linked to the document's spot swatch of /// that name: the one it has when it is the same colour, else a new one (a name taken by another -/// colour gets a number), one undo step (#5812). -fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value) -> Result<()> { +/// colour gets a number), one undo step (#5812). With `only`, only the default takes it. +fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value, only: bool) -> Result<()> { const C: &str = "library.use"; let c = color_value(color).ok_or_else(|| bad(C, "the library item is damaged"))?; let tint = data.get("tint").and_then(Value::as_f64).filter(|t| t.is_finite()).map_or(1.0, |t| t.clamp(0.0, 1.0)); @@ -1322,7 +1326,7 @@ fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value) if tint < 1.0 { p["tint"] = json!(tint * 100.0); } - s.execute(set, &p)?; + s.execute(set, &super::paint::with_defaults_only(p, only))?; Ok(()) }) } @@ -1340,8 +1344,8 @@ fn to_stroke(p: &Value, kind: Kind) -> Result { /// Add library pattern `data` (`{pattern, data}`) to the document, with its swatch and the /// resources its art uses (the same pattern there already is reused; a name the document gives /// another one gets a number), and paint the selection's fill (`stroke`: stroke) and the default -/// with it, one undo step → the pattern's name in the document. -fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result { +/// with it (with `only`, only the default), one undo step → the pattern's name in the document. +fn use_pattern(s: &mut Session, data: &Value, stroke: bool, only: bool) -> Result { const C: &str = "library.use"; let damaged = || bad(C, "the library item is damaged"); let bytes = data.get("data").and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or_else(damaged)?; @@ -1378,7 +1382,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result { } // The pattern itself, not a swatch of its name (a color swatch can share it); `swatch` keeps // the placement of a pattern the targets already have, as picking its swatch does. - super::paint::apply_paint(s, &json!({ "swatch": target }), paint.clone(), !stroke) + super::paint::apply_paint(s, &super::paint::with_defaults_only(json!({ "swatch": target }), only), paint.clone(), !stroke) })?; Ok(target) } diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index a42088e7e3..88e025ea41 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -19,6 +19,18 @@ use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer}; use vectorcraft_tools::PaintDefaults; +/// The object new art takes its appearance from, with that appearance +/// ([`Session::new_art_source`]). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct NewArtSource { + doc: u64, + id: vectorcraft_doc::NodeId, + appearance: Appearance, + opacity: f32, + blend: BlendMode, + style: Option, +} + use super::gradient::unplaced; use super::{CommandSpec, Result, Session, always, cmd, switch_or}; @@ -207,16 +219,35 @@ impl Session { /// After each command: with New Art Has Basic Appearance off, new art takes the appearance of /// the first selected object (so the last selection's once nothing is selected). Not while the - /// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with. + /// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with. Nor + /// after a command that changed only them (`defaultsOnly`), unless a later step of a batch + /// changed what new art would take ([`Session::new_art_source`]). pub(crate) fn inherit_new_art(&mut self) { if self.prefs.new_art_basic || self.bucket_paints() { return; } - let Some(st) = self.active() else { return }; - let Some(n) = st.selection.subjects().first().and_then(|id| st.doc.node(*id)) else { return }; - let style = super::style::linked_style(&st.doc, n).map(|g| g.name.clone()); - let (ap, opacity, blend) = (super::style::captured(n), n.opacity, n.blend); - self.take_new_art(ap, opacity, blend, style, true); + let Some(source) = self.new_art_source() else { return }; + if matches!(&self.defaults_only_ran, Some(Some(ran)) if *ran == source) { + return; + } + let NewArtSource { appearance, opacity, blend, style, .. } = source; + self.take_new_art(appearance, opacity, blend, style, true); + } + + /// What [`Session::inherit_new_art`] gives new art: the appearance of the active document's + /// first selected object, if any. + pub(crate) fn new_art_source(&self) -> Option { + let st = self.active()?; + let id = *st.selection.subjects().first()?; + let n = st.doc.node(id)?; + Some(NewArtSource { + doc: st.uid, + id, + appearance: super::style::captured(n), + opacity: n.opacity, + blend: n.blend, + style: super::style::linked_style(&st.doc, n).map(|g| g.name.clone()), + }) } /// After a command changed the selection, with New Art Has Basic Appearance on: the fill and diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index b94a45e4f5..e96ae7ed05 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), 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 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 (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), ids?|id?, defaultsOnly?: bool, 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 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 (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), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change the bucket made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {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) ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Swap Fill and Stroke", [], Some("Shift+X"), - "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change", + "{ids?|id?, defaultsOnly?: bool} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change", has_doc, swap ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Default Fill and Stroke", [], Some("D"), - "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters 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 (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change", + "{ids?|id?, defaultsOnly?: bool} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters 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 (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change", has_doc, default_paint ), @@ -75,11 +75,12 @@ pub fn specs() -> Vec { "None", [], Some("/"), - "{} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, only the default changes) → {objects}", + "{defaultsOnly?: bool} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, or with `defaultsOnly: true`, only the default changes) → {objects}", has_doc, - |s, _| { + |s, p| { let f = s.fill_active; - set_paint(s, &json!({"none": true}), f) + let only = switch_or(p, "defaultsOnly", false, "paint.none")?; + set_paint(s, &with_defaults_only(json!({"none": true}), only), f) } ), cmd!( @@ -102,7 +103,7 @@ pub fn proxy_specs() -> Vec { "Invert", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or 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), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color 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); no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or 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), or `defaultsOnly: true` is given, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color 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); no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert) ), @@ -111,7 +112,7 @@ pub fn proxy_specs() -> Vec { "Complement", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or 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), the default; no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or 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), or `defaultsOnly: true` is given, the default; no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model()) ), @@ -120,7 +121,7 @@ pub fn proxy_specs() -> Vec { "Apply Last Color", [], Some(","), - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (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), to the default only) → {objects} (as paint.setFill)", + "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (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), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)", has_doc, |s, p| { let paint = Paint::solid(s.last_solid); @@ -132,7 +133,7 @@ pub fn proxy_specs() -> Vec { "Apply Last Gradient", [], Some("."), - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (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), to the default only) → {objects} (as paint.setFill)", + "{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (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), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)", has_doc, |s, p| { let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone()))); @@ -750,28 +751,84 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) Ok(json!({"objects": ids.iter().collect::>().len()})) } -/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]) while `p` names no `ids`, -/// `id` or `item`? A fill, -/// stroke or stroke weight chosen then is what the bucket paints with, so it goes to the defaults -/// and the selection keeps its paint. -pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool { +/// Does `p` name no `ids`, `id` or `item`? +fn names_no_target(p: &Value) -> bool { // A null `ids` or `id` is no target, as `given_nodes` reads it; `item: null` names the top row. - s.bucket_paints() && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none() + ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none() } -/// `p` with `ids: []` when [`for_bucket`]: the paint goes to the defaults only. None otherwise. -/// A bad `target` or `aligned` is refused first, as it is without the bucket. -pub(crate) fn bucket_color_params(s: &Session, p: &Value, cmd: &str) -> Result> { +/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]), or does `p` give +/// `defaultsOnly: true`, while `p` names no `ids`, `id` or `item`? A fill, stroke or stroke weight +/// chosen then is what the bucket paints with, so it goes to the defaults and the selection keeps +/// its paint. +pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool { + names_no_target(p) && (s.bucket_paints() || asks_defaults_only(p)) +} + +/// Does `p` give `defaultsOnly: true`? +pub(crate) fn asks_defaults_only(p: &Value) -> bool { + p.get("defaultsOnly") == Some(&Value::Bool(true)) +} + +/// `p` with `ids: []` (and without `defaultsOnly`) when [`for_bucket`]: the paint goes to the +/// defaults only. None otherwise. A bad `target` or `aligned` is refused first, as it is without +/// the bucket, and so is a `defaultsOnly` that is not a bool or comes with `ids`, `id` or `item`. +/// When the bucket routed the command, the journal entry notes `defaultsOnly: true`, so replaying +/// it with another tool active changes the defaults only as well. +pub(crate) fn bucket_color_params(s: &mut Session, p: &Value, cmd: &str) -> Result> { + let only = switch_or(p, "defaultsOnly", false, cmd)?; + if only && !names_no_target(p) { + return Err(bad(cmd, "`defaultsOnly` cannot be combined with `ids`, `id` or `item`")); + } if !for_bucket(s, p) { return Ok(None); } super::appearance::aligned(p, cmd)?; super::appearance::targets_contents(p)?; + if !only { + s.note_journal("defaultsOnly", json!(true)); + } + s.note_defaults_only(); let mut v = p.as_object().cloned().unwrap_or_default(); + v.remove("defaultsOnly"); v.insert("ids".into(), json!([])); Ok(Some(Value::Object(v))) } +/// Whether the paint commands that `cmd` runs with params of its own change only the defaults: +/// `p` gives `defaultsOnly: true`, or the Live Paint Bucket paints ([`Session::bucket_paints`]), +/// which the journal entry of `cmd` notes for a replay. +pub(crate) fn defaults_only(s: &mut Session, p: &Value, cmd: &str) -> Result { + if switch_or(p, "defaultsOnly", false, cmd)? { + s.note_defaults_only(); + return Ok(true); + } + let bucket = s.bucket_paints(); + if bucket { + s.note_journal("defaultsOnly", json!(true)); + s.note_defaults_only(); + } + Ok(bucket) +} + +impl Session { + /// Note that the running command changed only the paint defaults, with the appearance new art + /// takes from the selection now ([`Session::inherit_new_art`]). No appearance is captured + /// while inheritance does not run (New Art Has Basic Appearance on, or the bucket painting). + fn note_defaults_only(&mut self) { + let inherits = !self.prefs.new_art_basic && !self.bucket_paints(); + self.defaults_only_ran = Some(if inherits { self.new_art_source() } else { None }); + } +} + +/// `q` with `defaultsOnly: true` when `only` ([`defaults_only`]). +pub(crate) fn with_defaults_only(mut q: Value, only: bool) -> Value { + if only && let Some(o) = q.as_object_mut() { + o.insert("defaultsOnly".into(), json!(true)); + } + q +} + /// The Live Paint groups in `roots` (or inside them), given or selected whole, with the ids of /// their faces and of their edges, found where [`leaf_targets`] finds the objects a paint command /// changes: a given or selected object other than a group or layer (a blend, say) and a compound diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index cb5d1fd374..16be04723a 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", 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)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. 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 stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", 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)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. 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), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Stroke Weight Up", [], Some("Cmd+Alt+."), - "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none). On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row 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) → {objects}", + "{ids?|id?, defaultsOnly?: bool (as stroke.set)} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row 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) → {objects}", has_doc, |s, p| stroke_step(s, p, true) ), @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Stroke Weight Down", [], Some("Cmd+Alt+,"), - "{ids?|id?} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}", + "{ids?|id?, defaultsOnly?: bool (as stroke.set)} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}", has_doc, |s, p| stroke_step(s, p, false) ), @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Stroke Options", [], None, - "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)", + "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, defaultsOnly?: bool (as stroke.set; refused with brush), target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool, or with `defaultsOnly: true`, and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)", has_doc, stroke_advanced ), @@ -618,7 +618,10 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "nothing to change")); } // As stroke.set: the stroke the Live Paint Bucket paints with changes; the selection keeps its own. - // A brush still goes to the selection. + // A brush still goes to the selection, and new art has no brush for `defaultsOnly` to set. + if brush.is_some() && super::switch_or(p, "defaultsOnly", false, C)? { + return Err(bad(C, "`defaultsOnly` cannot be combined with `brush`")); + } let bucket_p = if brush.is_none() { super::paint::bucket_color_params(s, p, C)? } else { None }; let bucket = bucket_p.is_some(); let p = bucket_p.as_ref().unwrap_or(p); diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index e4d89b9c13..c36fb6413b 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,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) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, 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, and the pattern links to it → {library, added: [names in the document], 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), defaultsOnly?: bool (with apply: apply it to the defaults only, as paint.setFill does; the journal records it for swatches applied while the Live Paint Bucket is the active tool)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, 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, and the pattern links to it → {library, added: [names in the document], existing: [names already there], applied?: name}", has_doc, add ), @@ -1021,6 +1021,7 @@ fn add(s: &mut Session, p: &Value) -> Result { Some(other) => return Err(bad(C, format!("apply is \"fill\" or \"stroke\", not `{other}`"))), }; let focus = switch_or(p, "focus", true, C)?; + switch_or(p, "defaultsOnly", false, C)?; let picked = picked(&lib, &names_param(p, C)?, C)?; // Swatches the document already has (same name and paint; for a pattern swatch, a swatch of the // same pattern) are reused, not added again. The patterns are in a built-in pattern library's @@ -1144,7 +1145,8 @@ fn add(s: &mut Session, p: &Value) -> Result { let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)}); if let (Some(cmd), Some((_, first))) = (apply, picked.first()) { let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone()); - s.execute(cmd, &json!({"swatch": name, "focus": focus}))?; + let only = super::paint::defaults_only(s, p, C)?; + s.execute(cmd, &super::paint::with_defaults_only(json!({"swatch": name, "focus": focus}), only))?; // Adding and applying undo together. squash(s, undo_before, "Add to Swatches"); out["applied"] = json!(name); diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index ba8f7e94ab..2ef9edbeb5 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Sample Color", [], None, - "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", + "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, defaultsOnly?: bool, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool or with `defaultsOnly: true` (refused with ids), `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", has_doc, sample_color ), @@ -523,13 +523,19 @@ fn sample_color(s: &mut Session, p: &Value) -> Result { if clear_stroke && (stroke || p.get("stroke") != Some(&Value::Bool(false)) || p.get("ids") != Some(&json!([])) || p.get("stop").is_some()) { return Err(bad(C, "`clearStroke` requires `stroke: false`, `ids: []` and no `stop`")); } + let only = super::switch_or(p, "defaultsOnly", false, C)?; + if only && p.get("ids").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "`defaultsOnly` cannot be combined with `ids`, `id` or `item`")); + } let c = p.get("color").ok_or_else(|| bad(C, "missing color"))?; let (id, mut q) = match p.get("stop") { None | Some(Value::Null) => (if stroke { "paint.setStroke" } else { "paint.setFill" }, json!({ "color": c })), Some(v) => { let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`stop` must be a stop index"))?; let color = super::paint::new_color(s, p, color_value(c).ok_or_else(|| bad(C, format!("bad color {c}")))?); - let (fill, stroke_paint) = s.proxy_paints(); + // The default's gradient with `defaultsOnly`, as the proxies show it while the Live + // Paint Bucket paints. + let (fill, stroke_paint) = if only { (s.paint.fill.clone(), s.paint.stroke.clone()) } else { s.proxy_paints() }; let Paint::Gradient(g) = (if stroke { stroke_paint } else { fill }) else { return Err(bad(C, "the paint behind the proxy is not a gradient")); }; @@ -542,6 +548,7 @@ fn sample_color(s: &mut Session, p: &Value) -> Result { if let Some(ids) = p.get("ids") { q["ids"] = ids.clone(); } + let q = super::paint::with_defaults_only(q, only); let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; let result = super::run_checked(s, spec, &q)?; if clear_stroke { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..0283829552 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -234,6 +234,11 @@ pub struct Session { /// The running top-level query command changed the selection and is journaled like any other /// command ([`Session::journal_query`]). journal_query: bool, + /// The running top-level command changed only the paint defaults, as the Live Paint Bucket + /// or `defaultsOnly: true` has a paint command do, when new art would have taken this + /// appearance (none: nothing selected): unless a later batch step changes it, the selection's + /// appearance does not replace the defaults afterwards ([`Session::inherit_new_art`]). + pub(crate) defaults_only_ran: Option>, /// From `edit.undoGroup.begin` to `edit.undoGroup.end`: the name of the undo step (`None`: after /// its first edit). Each document opened or created meanwhile opens an undo group of its own /// ([`Session::add_document`]). `None` otherwise. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..7627635797 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -114,6 +114,7 @@ impl Session { journal_note: Default::default(), note_depth: 1, journal_query: false, + defaults_only_ran: None, explicit_undo_group: None, batch_stash: None, batch_steps: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index bbd20fa5bb..a6af80f6a7 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -322,7 +322,8 @@ impl Session { return Err(EngineError::Busy); } // While the Live Paint Bucket is active, paint previews change only the bucket's colors, so - // each preview starts from the colors the interaction began with. + // each preview starts from the colors the interaction began with; so does a preview with + // `defaultsOnly: true`, and one after it. let bucket = self.bucket_paints(); let (paint, restore_paint) = { let menu = self.menu.clone(); @@ -339,7 +340,8 @@ impl Session { // the paints the interaction began with. let restore_paint = bucket || cmd == "command.batch" - || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") + || cmd::asks_defaults_only(params) + || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some(); let paint = it.paint.clone(); it.preview_paint = None; @@ -484,12 +486,16 @@ impl Session { self.decoded_images.empty(); self.pending_paint = None; // While the Live Paint Bucket is active, a previewed color is the bucket's color, which the - // cancel puts back as well. + // cancel puts back as well, as it does a color previewed with `defaultsOnly: true`. let bucket = self.bucket_paints(); if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) - .filter(|it| bucket || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some()) + .filter(|it| { + bucket + || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) + || it.color_mode_paints.is_some() + }) .map(|it| it.paint.clone()) { self.paint = paint; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..f2c9c62f42 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -161,6 +161,7 @@ impl Session { self.journal_note.clear(); self.note_depth = 1; self.journal_query = false; + self.defaults_only_ran = None; self.batch_stash = None; self.batch_steps = None; } @@ -263,8 +264,9 @@ impl Session { } /// Record `key: value` in the running top-level command's journal entry (or its interaction's - /// preview, or its step in a batch) unless its params give `key` (a null gives nothing): a value - /// it resolved from the preferences or the clock. + /// preview, or its step in a batch) unless its params give `key` (a null gives nothing, and a + /// noted `defaultsOnly` replaces the params' own): a value it resolved from the preferences or + /// the clock. pub fn note_journal(&mut self, key: &str, value: Value) { if self.depth == self.note_depth { self.journal_note.insert(key.to_string(), value); @@ -359,10 +361,11 @@ impl Session { let mut note = std::mem::take(&mut self.journal_note); match params { // The params' own values win, except a null: it reads as a key left out, so the - // noted value is the one the command resolved. + // noted value is the one the command resolved. A noted `defaultsOnly` wins too: the + // Live Paint Bucket kept the command to the defaults although the params gave `false`. Value::Object(m) if !note.is_empty() => { for (k, v) in m { - if !v.is_null() || !note.contains_key(k) { + if (!v.is_null() && k != "defaultsOnly") || !note.contains_key(k) { note.insert(k.clone(), v.clone()); } } diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 316e9b8ffc..dfe61cdd9e 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3331,6 +3331,151 @@ fn live_paint_bucket_paint_and_stroke_commands_leave_the_selection_unpainted() { assert!(failed.is_empty(), "{failed:#?}"); } +/// A paint or stroke command that the Live Paint Bucket kept to its own colors is journaled with +/// `defaultsOnly: true`, also when its params gave `false`. Replaying the entry with the Selection +/// tool active changes the same defaults and leaves the selection's paint as it was, also with New +/// Art Has Basic Appearance off. Every command that fails is listed. +#[test] +fn live_paint_bucket_commands_replay_from_the_journal_with_another_tool() { + let blue = Color::from_hex("#0000ff").unwrap(); + // A Live Paint group and a rectangle, both selected, a library with a fill color, a radial + // gradient as the default fill and a 2 pt default weight. + let setup = |s: &mut Session, basic: bool| { + s.execute("appearance.setNewArtBasic", &json!({"on": basic})).unwrap(); + let g = live(s); + let art = rect(s, 300.0, 300.0, 40.0, 40.0); + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [art.0]})).unwrap(); + let lib = s.execute("library.create", &json!({})).unwrap()["id"].as_str().unwrap().to_string(); + s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); + let item = s.execute("library.add", &json!({"library": lib, "kind": "fillColor"})).unwrap()["name"].as_str().unwrap().to_string(); + s.execute("select.set", &json!({"ids": [g.0, art.0]})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": {"kind": "radial"}, "defaultsOnly": true})).unwrap(); + s.paint.stroke_width = 2.0; + s.last_solid = blue; + (g, art, lib, item) + }; + let cases: Vec<(&str, Value)> = vec![ + ("paint.setFill", json!({"color": "#00ffff"})), + ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": false})), + ("paint.setStroke", json!({"color": "#00ffff"})), + ("paint.none", json!({})), + ("paint.swap", json!({})), + ("paint.default", json!({})), + ("paint.lastColor", json!({"stroke": false})), + ("paint.lastGradient", json!({"stroke": true})), + ("paint.invert", json!({"stroke": false})), + ("paint.complement", json!({"stroke": false})), + ("paint.sampleColor", json!({"color": "#00ffff", "stroke": true})), + ("paint.sampleColor", json!({"color": "#00ffff", "stroke": false, "stop": 0})), + ("paint.editGradient", json!({"stroke": false, "angle": 45})), + ("gradient.presets.apply", json!({"name": "vignette"})), + ("stroke.set", json!({"weight": 5})), + ("stroke.weightUp", json!({})), + ("stroke.weightDown", json!({})), + ("stroke.setAdvanced", json!({"arrowScale": [150, 200]})), + ("swatch.library.add", json!({"library": "web-safe-216", "names": ["#FF6600"], "apply": "fill"})), + ("library.use", json!({"kind": "fillColor"})), + ]; + let mut failed = vec![]; + for basic in [true, false] { + for (cmd, params) in &cases { + let mut params = params.clone(); + let mut a = session(); + let (_, _, lib, item) = setup(&mut a, basic); + if *cmd == "library.use" { + params["library"] = json!(lib); + params["item"] = json!(item); + } + a.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + let start = a.journal.len(); + if let Err(e) = a.execute(cmd, ¶ms) { + failed.push(format!("{cmd} {params} (basic {basic}): {e}")); + continue; + } + let Some((id, recorded)) = a.journal.since(start).last().cloned() else { + failed.push(format!("{cmd} {params} (basic {basic}): not journaled")); + continue; + }; + if recorded.get("defaultsOnly") != Some(&json!(true)) { + failed.push(format!("{cmd} {params} (basic {basic}): the journal entry {recorded} does not keep the change to the defaults")); + } + let mut b = session(); + let (g, art, _, _) = setup(&mut b, basic); + let (group, painted) = (node(&b, g), node(&b, art)); + if let Err(e) = b.replay(&id, &recorded) { + failed.push(format!("{cmd} {params} (basic {basic}): the replay failed: {e}")); + continue; + } + if node(&b, g) != group || node(&b, art) != painted { + failed.push(format!("{cmd} {params} (basic {basic}): the replay painted the selection")); + } + if (&b.paint.fill, &b.paint.stroke, b.paint.stroke_width, b.new_art_stroke()) + != (&a.paint.fill, &a.paint.stroke, a.paint.stroke_width, a.new_art_stroke()) + { + failed.push(format!("{cmd} {params} (basic {basic}): the replay left other defaults")); + } + } + } + assert!(failed.is_empty(), "{failed:#?}"); + // In a batch with New Art Has Basic Appearance off, a selection change after a `defaultsOnly` + // step still gives new art the new selection's appearance; without one, the defaults stay. + let cyan = Paint::solid(Color::from_hex("#00ffff").unwrap()); + let set_cyan = json!({"command": "paint.setFill", "params": {"color": "#00ffff", "defaultsOnly": true}}); + let mut s = session(); + let (_, art, ..) = setup(&mut s, false); + s.execute("command.batch", &json!({"commands": [set_cyan.clone()]})).unwrap(); + assert_eq!(s.paint.fill, cyan, "the defaults keep the batch's fill"); + s.execute("paint.setFill", &json!({"color": "#ff0000", "defaultsOnly": true})).unwrap(); + s.execute("command.batch", &json!({"commands": [set_cyan.clone(), {"command": "select.key", "params": {"id": art.0}}]})).unwrap(); + assert_eq!(s.paint.fill, cyan, "a new key object leaves the objects new art takes its appearance from"); + s.execute("command.batch", &json!({"commands": [set_cyan.clone(), {"command": "select.set", "params": {"ids": [art.0]}}]})).unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#00ff00").unwrap()), "new art takes the newly selected fill"); + // A later step that changes the selected object's appearance gives new art that appearance. + s.execute("command.batch", &json!({"commands": [set_cyan, {"command": "transparency.set", "params": {"opacity": 40, "ids": [art.0]}}]})).unwrap(); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + assert_eq!((&s.paint.fill, s.paint.opacity), (&green, 0.4), "new art takes the selection's new opacity, and its fill"); + // `defaultsOnly: true` with the Selection tool: a canceled preview puts the defaults back, and + // each preview starts from the defaults the interaction began with. + let mut s = session(); + let (g, art, ..) = setup(&mut s, true); + let (group, painted, fill) = (node(&s, g), node(&s, art), s.paint.fill.clone()); + s.begin_interaction("Fill Color").unwrap(); + s.preview("paint.setFill", &json!({"color": "#123456", "defaultsOnly": true})).unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#123456").unwrap())); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, fill, "the canceled color is not kept"); + s.begin_interaction("Stroke Weight").unwrap(); + for _ in 0..3 { + s.preview("stroke.weightUp", &json!({"defaultsOnly": true})).unwrap(); + } + assert_eq!(s.paint.stroke_width, 3.0, "each preview starts from 2 pt"); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.stroke_width, 2.0); + // A preview with `defaultsOnly: true` after one that set the defaults with the selection + // starts from the defaults the interaction began with too. + s.begin_interaction("Stroke Weight").unwrap(); + s.preview("stroke.set", &json!({"weight": 7})).unwrap(); + assert_eq!(s.paint.stroke_width, 7.0); + s.preview("paint.setFill", &json!({"color": "#123456", "defaultsOnly": true})).unwrap(); + assert_eq!(s.paint.stroke_width, 2.0, "the discarded preview's weight is not kept"); + s.cancel_interaction().unwrap(); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (fill.clone(), 2.0)); + assert_eq!((node(&s, g), node(&s, art)), (group, painted), "the selection keeps its paint"); + // `defaultsOnly` is a bool, and names no objects or brush. + let (g, ..) = setup(&mut s, true); + for (cmd, params) in [ + ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": "yes"})), + ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": true, "ids": [g.0]})), + ("stroke.set", json!({"weight": 3, "defaultsOnly": true, "item": 0})), + ("paint.sampleColor", json!({"color": "#00ffff", "defaultsOnly": true, "ids": [g.0]})), + ("paint.none", json!({"defaultsOnly": 1})), + ("stroke.setAdvanced", json!({"brush": null, "defaultsOnly": true})), + ("stroke.setAdvanced", json!({"brush": "3 pt. Round", "defaultsOnly": true})), + ] { + assert!(s.execute(cmd, ¶ms).is_err(), "{cmd} {params}"); + } +} + /// `paint.editGradient` with an `aspect` and no object to edit (the Live Paint Bucket's gradient, /// nothing selected, or a fill edit of a Live Paint group without faces) is an error that leaves the default gradient as it was, since a gradient /// fitted to each object has no aspect of its own. Named objects still take the aspect. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 9ef6f066e6..2a2cd7273e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9022,6 +9022,8 @@ breakText Glyphs Glyfy @msg `dataBase64` is larger than the module limit `dataBase64` je větší než limit modulu @msg `dataBase64` is not valid base64 `dataBase64` není platný base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` nelze kombinovat s `ids`, `reverse` ani `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` nelze kombinovat s `ids`, `id` ani `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` nelze kombinovat s `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` a `childLimit` omezují souhrn: předejte `summary: true` @msg `design` is a design name, or null for plain columns `design` je název návrhu, nebo null pro obyčejné sloupce @msg `design` is a design name, or null for the default marker `design` je název návrhu, nebo null pro výchozí značku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0d8b14dba4..39ffd4b602 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1136,6 +1136,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg `dataBase64` is larger than the module limit `dataBase64` er større end modulgrænsen @msg `dataBase64` is not valid base64 `dataBase64` er ikke gyldig base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` kan ikke kombineres med `ids`, `reverse` eller `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` kan ikke kombineres med `ids`, `id` eller `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` kan ikke kombineres med `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` og `childLimit` opdeler oversigten: angiv `summary: true` @msg `design` is a design name, or null for plain columns `design` er et designnavn eller null for almindelige søjler @msg `design` is a design name, or null for the default marker `design` er et designnavn eller null for standardmarkøren diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index bd04b8cc19..59b4ec7966 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8868,6 +8868,8 @@ breakText Glyphs Glyphen @msg `dataBase64` is larger than the module limit `dataBase64` ist größer als die Modulgrenze @msg `dataBase64` is not valid base64 `dataBase64` ist kein gültiges Base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` kann nicht mit `ids`, `reverse` oder `append` kombiniert werden +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` kann nicht mit `ids`, `id` oder `item` kombiniert werden +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` kann nicht mit `brush` kombiniert werden @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` und `childLimit` begrenzen die Zusammenfassung: Übergeben Sie `summary: true` @msg `design` is a design name, or null for plain columns `design` ist ein Designname oder null für einfache Säulen @msg `design` is a design name, or null for the default marker `design` ist ein Designname oder null für die Standardmarkierung diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 016f297b3b..d6f3c2226d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -9311,6 +9311,8 @@ breakText Glyphs Glifos @msg `dataBase64` is larger than the module limit `dataBase64` supera el límite de módulos @msg `dataBase64` is not valid base64 `dataBase64` no es base64 válido @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` no se puede combinar con `ids`, `reverse` ni `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` no se puede combinar con `ids`, `id` ni `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` no se puede combinar con `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` y `childLimit` recortan el resumen: pasa `summary: true` @msg `design` is a design name, or null for plain columns `design` es el nombre de un diseño, o null para columnas simples @msg `design` is a design name, or null for the default marker `design` es el nombre de un diseño, o null para el marcador predeterminado diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4ce31cfc06..48b1e5b5c4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8888,6 +8888,8 @@ breakText Glyphs Glyphes @msg `dataBase64` is larger than the module limit `dataBase64` dépasse la limite des modules @msg `dataBase64` is not valid base64 `dataBase64` n’est pas du base64 valide @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` ne peut pas être combiné avec `ids`, `reverse` ou `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` ne peut pas être combiné avec `ids`, `id` ou `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` ne peut pas être combiné avec `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` et `childLimit` découpent le résumé : passez `summary: true` @msg `design` is a design name, or null for plain columns `design` est un nom de motif, ou null pour des colonnes simples @msg `design` is a design name, or null for the default marker `design` est un nom de motif, ou null pour le repère par défaut diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index c8852f1ddd..bbd26b9ca4 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7008,6 +7008,8 @@ arrowhead Feather पंख @msg `dataBase64` is not valid base64 `dataBase64` मान्य नहीं है base64 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` होना चाहिए `fileNumber`, `fileDataSetName` या `dataSetName` @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` को `ids`, `reverse` या `append` के साथ उपयोग नहीं कर सकते +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` को `ids`, `id` या `item` के साथ उपयोग नहीं कर सकते +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` को `brush` के साथ उपयोग नहीं कर सकते @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` और `childLimit` सारांश के हिस्से चुनते हैं: `summary: true` दें @msg `design` is a design name, or null for plain columns `design` एक डिजाइन नाम है, या सादे स्तंभों के लिए null है @msg `design` is a design name, or null for the default marker `design` एक डिजाइन नाम है, या डिफ़ॉल्ट मार्कर के लिए null है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 54ff192eed..e3dae2312f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8893,6 +8893,8 @@ breakText Glyphs Glifák @msg `dataBase64` is larger than the module limit `dataBase64`: nagyobb a modulok méretkorlátjánál @msg `dataBase64` is not valid base64 `dataBase64`: nem érvényes base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly`: nem használható együtt ezekkel: `ids`, `reverse`, `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly`: nem használható együtt ezekkel: `ids`, `id`, `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly`: nem használható együtt ezzel: `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` és `childLimit`: az összegzést szűkítik; add meg ezt: `summary: true` @msg `design` is a design name, or null for plain columns `design`: diagramminta neve, vagy null az egyszerű oszlopokhoz @msg `design` is a design name, or null for the default marker `design`: diagramminta neve, vagy null az alapértelmezett jelölőhöz diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 190b136a06..c26a6120b8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8921,6 +8921,8 @@ breakText Glyphs Glifi @msg `dataBase64` is larger than the module limit `dataBase64` supera il limite del modulo @msg `dataBase64` is not valid base64 `dataBase64` non è un base64 valido @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` non può essere combinato con `ids`, `reverse` o `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` non può essere combinato con `ids`, `id` o `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` non può essere combinato con `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` e `childLimit` riducono il riepilogo: passa `summary: true` @msg `design` is a design name, or null for plain columns `design` è il nome di un design, o null per colonne semplici @msg `design` is a design name, or null for the default marker `design` è il nome di un design, o null per il marcatore predefinito diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 665e74c319..7a8823f851 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7738,6 +7738,8 @@ axis Y Axis Y 軸 @msg `dataBase64` is larger than the module limit `dataBase64` がモジュールの上限を超えています @msg `dataBase64` is not valid base64 `dataBase64` が有効な base64 ではありません @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` は `ids`、`reverse`、`append` と同時に使用できません +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` は `ids`、`id`、`item` と同時に使用できません +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` は `brush` と同時に使用できません @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` と `childLimit` はサマリーを絞り込みます: `summary: true` を指定してください @msg `design` is a design name, or null for plain columns `design` にはデザイン名を指定します。通常の棒にするには null を指定します @msg `design` is a design name, or null for the default marker `design` にはデザイン名を指定します。初期設定のマーカーにするには null を指定します diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d3ea2160c1..38eea76371 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -217,6 +217,8 @@ @msg `dataBase64` is larger than the module limit `dataBase64` მოდულის ლიმიტზე დიდია @msg `dataBase64` is not valid base64 `dataBase64` სწორი base64 არ არის @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` ვერ გამოიყენება `ids`-თან, `reverse`-თან ან `append`-თან ერთად +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` ვერ გამოიყენება `ids`-თან, `id`-თან ან `item`-თან ერთად +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` ვერ გამოიყენება `brush`-თან ერთად @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` და `childLimit` შეჯამებას ზღუდავს: გადაეცით `summary: true` @msg `design` is a design name, or null for plain columns `design` არის დიზაინის სახელი, ან null — ჩვეულებრივი სვეტებისთვის @msg `design` is a design name, or null for the default marker `design` არის დიზაინის სახელი, ან null — ნაგულისხმევი მარკერისთვის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0c2642f758..15597a0192 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8661,6 +8661,8 @@ breakText Glyphs 글리프 @msg `dataBase64` is larger than the module limit `dataBase64`이(가) 모듈 한도보다 큽니다 @msg `dataBase64` is not valid base64 `dataBase64`이(가) 올바른 base64가 아닙니다 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly`은(는) `ids`, `reverse` 또는 `append`와 함께 쓸 수 없습니다 +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly`은(는) `ids`, `id` 또는 `item`과 함께 쓸 수 없습니다 +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly`은(는) `brush`와 함께 쓸 수 없습니다 @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth`와 `childLimit`은 요약을 잘라 냅니다: `summary: true`를 전달하세요 @msg `design` is a design name, or null for plain columns `design`은(는) 디자인 이름이며, 일반 막대에는 null입니다 @msg `design` is a design name, or null for the default marker `design`은(는) 디자인 이름이며, 기본 마커에는 null입니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c1f7e36426..2492a94d48 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6531,6 +6531,8 @@ imageTrace Outline Contour @msg `dataBase64` is larger than the module limit `dataBase64` is groter dan de modulelimiet @msg `dataBase64` is not valid base64 `dataBase64` is geen geldige base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` kan niet worden gecombineerd met `ids`, `reverse` of `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` kan niet worden gecombineerd met `ids`, `id` of `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` kan niet worden gecombineerd met `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` en `childLimit` beperken de samenvatting: geef `summary: true` op @msg `design` is a design name, or null for plain columns `design` is de naam van een ontwerp, of null voor gewone kolommen @msg `design` is a design name, or null for the default marker `design` is de naam van een ontwerp, of null voor de standaardmarkering diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5808ddb8c2..2258f53359 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9129,6 +9129,8 @@ breakText Glyphs Glify @msg `dataBase64` is larger than the module limit `dataBase64` przekracza limit rozmiaru modułu @msg `dataBase64` is not valid base64 `dataBase64` nie jest prawidłowym kodem base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` nie można łączyć z `ids`, `reverse` ani `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` nie można łączyć z `ids`, `id` ani `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` nie można łączyć z `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` i `childLimit` ograniczają podsumowanie: przekaż `summary: true` @msg `design` is a design name, or null for plain columns `design` to nazwa wzoru albo null dla zwykłych kolumn @msg `design` is a design name, or null for the default marker `design` to nazwa wzoru albo null dla domyślnego znacznika diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2204a2bdc1..2a9c0b1d75 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9084,6 +9084,8 @@ swatch Yellow Green Verde-amarelado @msg `dataBase64` is larger than the module limit `dataBase64` excede o limite do módulo @msg `dataBase64` is not valid base64 `dataBase64` não é base64 válido @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` não pode ser combinado com `ids`, `reverse` ou `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` não pode ser combinado com `ids`, `id` ou `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` não pode ser combinado com `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` e `childLimit` recortam o resumo: passe `summary: true` @msg `design` is a design name, or null for plain columns `design` é o nome de um projeto, ou null para colunas simples @msg `design` is a design name, or null for the default marker `design` é o nome de um projeto, ou null para o marcador padrão diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b3ca5d5d93..dbd54f0746 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -9007,6 +9007,8 @@ shape Open Открытый @msg `dataBase64` is larger than the module limit `dataBase64` больше ограничения для модуля @msg `dataBase64` is not valid base64 `dataBase64` не является допустимым base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` нельзя сочетать с `ids`, `reverse` или `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` нельзя сочетать с `ids`, `id` или `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` нельзя сочетать с `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` и `childLimit` ограничивают сводку: передайте `summary: true` @msg `design` is a design name, or null for plain columns `design` — имя дизайна или null для обычных столбцов @msg `design` is a design name, or null for the default marker `design` — имя дизайна или null для маркера по умолчанию diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 94a83ef975..bdab8aa5fe 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8864,6 +8864,8 @@ digits Hindi Hindi @msg `dataBase64` is larger than the module limit `dataBase64` är större än modulgränsen @msg `dataBase64` is not valid base64 `dataBase64` är inte giltig base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` kan inte kombineras med `ids`, `reverse` eller `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` kan inte kombineras med `ids`, `id` eller `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` kan inte kombineras med `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` och `childLimit` begränsar sammanfattningen: ange `summary: true` @msg `design` is a design name, or null for plain columns `design` är ett designnamn, eller null för vanliga kolumner @msg `design` is a design name, or null for the default marker `design` är ett designnamn, eller null för standardmarkören diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2fcd6d3b54..25f69773e3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -8119,6 +8119,8 @@ axis Y Axis Y ekseni @msg `dataBase64` is larger than the module limit `dataBase64` modül sınırından büyük @msg `dataBase64` is not valid base64 `dataBase64` geçerli bir base64 değil @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly`; `ids`, `reverse` veya `append` ile birleştirilemez +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly`; `ids`, `id` veya `item` ile birleştirilemez +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly`; `brush` ile birleştirilemez @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` ve `childLimit` özeti dilimler: `summary: true` verin @msg `design` is a design name, or null for plain columns `design` bir tasarım adıdır veya düz sütunlar için null olur @msg `design` is a design name, or null for the default marker `design` bir tasarım adıdır veya varsayılan işaretçi için null olur diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 49f8383268..464b9773f1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8670,6 +8670,8 @@ breakText Glyphs Гліфи @msg `dataBase64` is larger than the module limit `dataBase64` перевищує обмеження модуля @msg `dataBase64` is not valid base64 `dataBase64` не є припустимим base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` не можна поєднувати з `ids`, `reverse` або `append` +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` не можна поєднувати з `ids`, `id` або `item` +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` не можна поєднувати з `brush` @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` і `childLimit` обмежують зведення: передайте `summary: true` @msg `design` is a design name, or null for plain columns `design` — це назва дизайну або null для звичайних стовпців @msg `design` is a design name, or null for the default marker `design` — це назва дизайну або null для стандартного маркера diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f51baaa7e7..1979424953 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9140,6 +9140,8 @@ breakText Glyphs 字形 @msg `dataBase64` is larger than the module limit `dataBase64` 超过了模块大小上限 @msg `dataBase64` is not valid base64 `dataBase64` 不是有效的 base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` 不能与 `ids`、`reverse` 或 `append` 同时使用 +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` 不能与 `ids`、`id` 或 `item` 同时使用 +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` 不能与 `brush` 同时使用 @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` 和 `childLimit` 用于截取摘要:请传入 `summary: true` @msg `design` is a design name, or null for plain columns `design` 是设计名称,或用 null 表示普通柱形 @msg `design` is a design name, or null for the default marker `design` 是设计名称,或用 null 表示默认标记 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d794ea15d9..8be1458d9b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9076,6 +9076,8 @@ breakText Glyphs 字符 @msg `dataBase64` is larger than the module limit `dataBase64` 大於模組上限 @msg `dataBase64` is not valid base64 `dataBase64` 不是有效的 base64 @msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` 不能與 `ids`、`reverse` 或 `append` 一起使用 +@msg `defaultsOnly` cannot be combined with `ids`, `id` or `item` `defaultsOnly` 不能與 `ids`、`id` 或 `item` 一起使用 +@msg `defaultsOnly` cannot be combined with `brush` `defaultsOnly` 不能與 `brush` 一起使用 @msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` 和 `childLimit` 用於裁切摘要:請傳入 `summary: true` @msg `design` is a design name, or null for plain columns `design` 是設計名稱,或以 null 表示一般直條 @msg `design` is a design name, or null for the default marker `design` 是設計名稱,或以 null 表示預設標記 diff --git a/docs/mcp.md b/docs/mcp.md index ae119cc4b1..afea44461b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4839,7 +4839,13 @@ already walks Image Trace. Short agent entry points: `paint.invert`, `paint.complement`, `paint.sampleColor`, `gradient.presets.apply`, a swatch or the Color Picker), and `paint.swap` or `paint.default` without `ids` or `id`, becomes the color the bucket paints with, and a stroke weight (`stroke.set`, `stroke.weightUp`, `stroke.weightDown`) becomes the weight it paints with. The selection keeps its - paint, and no undo step is recorded. A null `ids` or `id` counts as left out. The Stroke panel's other options + paint, and no undo step is recorded. A null `ids` or `id` counts as left out. The journal records each of these + commands with `defaultsOnly: true`, and it records `library.use` with a color, gradient or pattern and + `swatch.library.add` with `apply` the same way. A replay of the entry, or the same params sent with any tool active, changes + only the defaults. `defaultsOnly` is a bool, and it is refused together with `ids`, `id` or `item`, and in + `stroke.setAdvanced` together with `brush`. While the bucket is active, `defaultsOnly: false` without a target is + journaled as `true`. A preview with `defaultsOnly: true` starts from the defaults the interaction began with, and + canceling the interaction puts them back. The Stroke panel's other options (`stroke.set`, `stroke.setAdvanced` without `brush`) change the stroke for new art and leave the selection as it is; the bucket takes only the color and weight of that stroke. A stop selected on the bucket's gradient (`gradient.selectStop`) is deselected when another tool is chosen, when the first selected object changes, when an From 88e3575a1ed368b35031a02e82d9aa029440faca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:22:09 -0800 Subject: [PATCH 018/178] 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 c609eb49af15e2116176982d3221474f89034dc5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:59:44 -0800 Subject: [PATCH 019/178] Live Paint: canceling restores the defaults after a later ordinary preview An interaction that previewed a command with defaultsOnly: true keeps putting the defaults it began with back on every later preview and on cancel, also when the latest preview gives no defaultsOnly. docs/mcp.md says that library.use keeps item as the library item. --- crates/engine/src/interaction.rs | 3 +++ crates/engine/src/session/edit.rs | 5 ++++- crates/engine/src/tests/build.rs | 12 ++++++++++++ docs/mcp.md | 6 +++--- 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 99a2569005..efadf86ec3 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -10,6 +10,9 @@ pub struct Interaction { pub preview: Option<(String, Value)>, /// A replaced or canceled preview restores these new-art paints from before the interaction. pub(crate) paint: vectorcraft_tools::PaintDefaults, + /// A preview of the interaction gave `defaultsOnly: true`: every later preview and a cancel put + /// `paint` back, whichever preview is the latest. + pub(crate) used_defaults_only: bool, /// An accepted batch preview uses these final paints after changing the document color mode. pub(crate) preview_paint: Option, /// Conversion of new-art paints waits until a color-mode preview is accepted. diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index a6af80f6a7..4a7b9bc1c2 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -301,6 +301,7 @@ impl Session { selection: Arc::new(st.selection.clone()), preview: None, paint, + used_defaults_only: false, preview_paint: None, color_mode_paints: None, deferred_color_mode: None, @@ -338,9 +339,10 @@ impl Session { st.doc = it.doc.clone(); // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. + it.used_defaults_only |= cmd::asks_defaults_only(params); let restore_paint = bucket || cmd == "command.batch" - || cmd::asks_defaults_only(params) + || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some(); let paint = it.paint.clone(); @@ -493,6 +495,7 @@ impl Session { .and_then(|st| st.interaction.as_ref()) .filter(|it| { bucket + || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() }) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index dfe61cdd9e..39618bf201 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3461,9 +3461,21 @@ fn live_paint_bucket_commands_replay_from_the_journal_with_another_tool() { s.cancel_interaction().unwrap(); assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (fill.clone(), 2.0)); assert_eq!((node(&s, g), node(&s, art)), (group, painted), "the selection keeps its paint"); + // A later preview without `defaultsOnly` leaves the interaction one that changed the defaults: + // canceling puts them back. + s.begin_interaction("Stroke Weight").unwrap(); + s.preview("stroke.weightUp", &json!({"defaultsOnly": true})).unwrap(); + s.preview("stroke.set", &json!({"weight": 7})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.stroke_width, 2.0, "the canceled interaction's weight is not kept"); // `defaultsOnly` is a bool, and names no objects or brush. let (g, ..) = setup(&mut s, true); for (cmd, params) in [ + ("paint.none", json!({"defaultsOnly": true, "ids": [g.0]})), + ("paint.none", json!({"defaultsOnly": true, "id": g.0})), + ("paint.none", json!({"defaultsOnly": true, "item": null})), + ("paint.sampleColor", json!({"color": "#00ffff", "defaultsOnly": true, "id": g.0})), + ("paint.sampleColor", json!({"color": "#00ffff", "defaultsOnly": true, "item": null})), ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": "yes"})), ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": true, "ids": [g.0]})), ("stroke.set", json!({"weight": 3, "defaultsOnly": true, "item": 0})), diff --git a/docs/mcp.md b/docs/mcp.md index afea44461b..51edbf0d2a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4842,10 +4842,10 @@ already walks Image Trace. Short agent entry points: paint, and no undo step is recorded. A null `ids` or `id` counts as left out. The journal records each of these commands with `defaultsOnly: true`, and it records `library.use` with a color, gradient or pattern and `swatch.library.add` with `apply` the same way. A replay of the entry, or the same params sent with any tool active, changes - only the defaults. `defaultsOnly` is a bool, and it is refused together with `ids`, `id` or `item`, and in - `stroke.setAdvanced` together with `brush`. While the bucket is active, `defaultsOnly: false` without a target is + only the defaults. `defaultsOnly` is a bool, and it is refused together with `ids`, `id` or an appearance `item` (`library.use` takes + `item` as the library item to apply, which stays valid), and in `stroke.setAdvanced` together with `brush`. While the bucket is active, `defaultsOnly: false` without a target is journaled as `true`. A preview with `defaultsOnly: true` starts from the defaults the interaction began with, and - canceling the interaction puts them back. The Stroke panel's other options + canceling the interaction puts them back, also after a later preview without `defaultsOnly`. The Stroke panel's other options (`stroke.set`, `stroke.setAdvanced` without `brush`) change the stroke for new art and leave the selection as it is; the bucket takes only the color and weight of that stroke. A stop selected on the bucket's gradient (`gradient.selectStop`) is deselected when another tool is chosen, when the first selected object changes, when an From 01f1ffa4cb0706c9c4a3e762b2780b316cda7b9a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 18:11:43 -0800 Subject: [PATCH 020/178] 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 e0629ad03a3bd999e61c12042a4d2f78f9d404ba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 18:44:45 -0800 Subject: [PATCH 021/178] Live Paint: canceling keeps the defaults a defaultsOnly preview began with With New Art Has Basic Appearance off and an object selected, canceling an interaction that had previewed a command with defaultsOnly: true replaced the restored defaults with the selection's appearance. Cancel now skips the new-art inheritance for such an interaction. --- crates/engine/src/session/edit.rs | 11 +++++++++-- crates/engine/src/tests/build.rs | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 4a7b9bc1c2..7c52f211ff 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -373,6 +373,8 @@ impl Session { let outer = std::mem::replace(&mut self.previewing, true); let r = self.execute(cmd, params); self.previewing = outer; + // A step inside a batch that changed only the defaults counts as well. + let ran_defaults_only = self.defaults_only_ran.is_some(); if let Some(paint) = color_mode_paint { self.paint = paint; } @@ -380,6 +382,7 @@ impl Session { let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone()); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { + it.used_defaults_only |= ran_defaults_only; // A failed preview leaves the document at the snapshot, so nothing is left to commit // (not even an earlier successful preview, which the reset above already undid). it.preview = r.is_ok().then(|| (cmd.to_string(), params)); @@ -490,6 +493,7 @@ impl Session { // While the Live Paint Bucket is active, a previewed color is the bucket's color, which the // cancel puts back as well, as it does a color previewed with `defaultsOnly: true`. let bucket = self.bucket_paints(); + let used_defaults_only = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.used_defaults_only); if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) @@ -511,8 +515,11 @@ impl Session { // A canceled preview's Assign Profile is undone with it. self.sync_front_profiles(); // With New Art Has Basic Appearance off, new art takes the appearance of the selection as - // the document has it again, not as a preview left it. - self.inherit_new_art(); + // the document has it again, not as a preview left it. An interaction that changed only the + // defaults (`defaultsOnly: true`) leaves the defaults it began with. + if !used_defaults_only { + self.inherit_new_art(); + } Ok(()) } diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 39618bf201..8a214f5522 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3468,6 +3468,25 @@ fn live_paint_bucket_commands_replay_from_the_journal_with_another_tool() { s.preview("stroke.set", &json!({"weight": 7})).unwrap(); s.cancel_interaction().unwrap(); assert_eq!(s.paint.stroke_width, 2.0, "the canceled interaction's weight is not kept"); + // With New Art Has Basic Appearance off and an object selected, canceling such an interaction + // keeps the defaults it began with, not the selection's appearance. + let mut s = session(); + let (_, art, ..) = setup(&mut s, false); + s.execute("paint.setFill", &json!({"color": "#ff0000", "defaultsOnly": true})).unwrap(); + let (red, selected) = (s.paint.fill.clone(), node(&s, art)); + s.begin_interaction("Fill Color").unwrap(); + s.preview("paint.setFill", &json!({"color": "#00ffff", "defaultsOnly": true})).unwrap(); + s.preview("stroke.set", &json!({"weight": 7})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (red, 2.0), "the defaults the interaction began with stay"); + assert_eq!(node(&s, art), selected, "the selection keeps its paint"); + // The same when the defaults-only step was inside a batch that a later preview replaced. + s.begin_interaction("Fill Color").unwrap(); + let step = json!({"command": "paint.setFill", "params": {"color": "#00ffff", "defaultsOnly": true}}); + s.preview("command.batch", &json!({"commands": [step]})).unwrap(); + s.preview("stroke.set", &json!({"weight": 7})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#ff0000").unwrap()), "a batch's defaults-only step is put back"); // `defaultsOnly` is a bool, and names no objects or brush. let (g, ..) = setup(&mut s, true); for (cmd, params) in [ From 77f0cf29ff10c0c1a9a3ef5347cd5154d9218f69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:13:01 -0800 Subject: [PATCH 022/178] 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 8b304e232a50a928844a6c9f02b71ed6213fcbb5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:51:18 -0800 Subject: [PATCH 023/178] Retype: no retyped line starts with a combining mark A drawn bar, dot or ring can be the same shape as a combining mark in one of the loaded fonts, and Retype turned it into point text that held only that mark. On Linux, once other tests had loaded the system fonts, the 80x40 rectangle in a_drawn_shape_is_reported_and_left_alone matched U+05BD in DejaVu Sans Bold, so that test failed in full runs of the engine's tests. - When a shape would start a line and its first 16 matched glyphs include another character's glyph, in its own font or another loaded one, it starts the line as that character. A line's first shape is not turned into a mark to take the glyph after it. - When all of them are marks, the shape stays an outline and is listed in unmatched, and the glyph after it starts the line. A lone one-contour glyph after it (a dot after a bar) is judged alone, as on its own. - A mark left at the start of a part split off where type stops drawing the outlines in place becomes the other character its shape matches, on a line of its own, or else stays an outline. The glyphs after it are measured for tracking again without the mark's gap. - A mark that follows another glyph on its line is retyped with it, as before. - type.retypeFonts does not list a font whose glyphs match the shapes only as combining marks. Docs: docs/mcp.md and the params text of type.retype and type.retypeFonts. --- crates/engine/src/cmd/retype.rs | 90 ++++++++++++++-- crates/engine/src/cmd/retype_fonts.rs | 24 +++-- crates/engine/src/cmd/retype_fonts_tests.rs | 15 +++ crates/engine/src/cmd/retype_tests.rs | 109 +++++++++++++++++++- crates/text/src/retype.rs | 19 ++++ crates/text/src/test_fonts.rs | 9 ++ docs/mcp.md | 10 +- 7 files changed, 259 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 0e31d5632a..51d9398870 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches", + "{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches", has_selected_path, retype )] @@ -613,8 +613,14 @@ fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64) -> Option, system_layout: bool, unmatched: &mut Vec) -> Vec { +fn verified( + lines: Vec, + system_layout: bool, + spacing: &std::collections::HashMap, + unmatched: &mut Vec, +) -> Vec { // Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines. let mut budget = lines.iter().map(|l| l.pieces.len()).sum::().saturating_mul(16).saturating_add(256); // Measuring the tracking of the glyphs after a split has a budget of its own, so it cannot @@ -630,6 +636,40 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) let mut out = vec![]; while let Some(l) = todo.pop_front() { let n = l.pieces.len(); + // A combining mark goes with the character before it: a mark that a split left first on + // a line becomes the other character its shape is (`spacing`), alone on a line, or else + // stays an outline, and the line goes on from the glyph after it ([`new_line`] starts no + // line with one). + if l.matches.first().is_some_and(|m| vectorcraft_text::retype::is_combining_mark(m.ch)) { + let first = l.pieces.first().copied(); + let alone = first.and_then(|id| spacing.get(&id).map(|m| reposed(&l, id, m))); + if alone.is_none() { + unmatched.extend(first); + } + if n > 1 { + // The tracking was measured with the mark's gap in it: the rest is measured again + // without it, from the same budgets as the rest after a split. + let measurable = n > 3 && remeasured >= (n - 1).saturating_mul(6) && track_budget >= (n - 1).saturating_mul(6); + let rest = if measurable { + remeasured = remeasured.saturating_sub((n - 1).saturating_mul(6)); + track_budget = track_budget.saturating_sub(n - 1); + l.respaced(1, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget)) + } else if l.tracking == 0.0 { + l.part(1, n) + } else { + l.respaced(1, n, 0.0) + }; + match rest { + Some(rest) => todo.push_front(rest), + None => unmatched.extend(l.pieces.get(1..).unwrap_or_default().iter().copied()), + } + } + // Checked before the rest, so the lines keep the outlines' order. + if let Some(alone) = alone { + todo.push_front(alone); + } + continue; + } // The line's type is laid out over a window from its start that doubles while the type // draws the window's glyphs as the outlines do, so finding where it stops costs about // twice the glyphs before that point, not the whole rest of the line each time. @@ -1024,6 +1064,8 @@ fn join(l: &mut Line, pc: &Piece, cands: &[GlyphMatch]) -> bool { .iter() .flat_map(|c| c.poses()) .filter(|fp| !(fp.gid == current.gid && fp.face.id() == current.face.id() && fp.angle == current.angle)) + // No line starts with a combining mark (see [`new_line`]). + .filter(|fp| !vectorcraft_text::retype::is_combining_mark(fp.ch)) .collect(); for fp in others { let mut turned = reposed(l, id, &fp); @@ -1057,9 +1099,11 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line { } } -/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`). +/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` that is not a +/// combining mark (none: `None`). No line starts with a mark: a mark combines with the character +/// before it. fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option { - let m = cands.first()?; + let m = cands.iter().find(|m| !vectorcraft_text::retype::is_combining_mark(m.ch))?; let dir = Vec2::new(m.angle.cos(), m.angle.sin()); Some(Line { pieces: vec![pc.id], @@ -1141,6 +1185,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { let mut unmatched = vec![]; // An unmatched shape between glyphs ends the line: the type after it is painted after it. let mut open = false; + let mut spacing: std::collections::HashMap = std::collections::HashMap::new(); for (pc, ms) in pieces.iter().zip(&found) { if pc.after_barrier { open = false; @@ -1158,8 +1203,41 @@ fn retype(s: &mut Session, p: &Value) -> Result { Some(l) if open => join(l, pc, &cands), _ => false, }; + // A shape that joined a line, perhaps as a mark, that is also another character, in that + // face or else in the face most shapes fit of those it is a character in: the character, + // should a split leave the shape first on a line ([`verified`]). + let is_mark = |m: &GlyphMatch| vectorcraft_text::retype::is_combining_mark(m.ch); + if joined + && cands.iter().any(is_mark) + && let Some(m) = cands.iter().find(|m| !is_mark(m)).or_else(|| { + ms.iter().enumerate().filter(|(_, m)| !is_mark(m)).max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m) + }) + { + spacing.insert(pc.id, m.clone()); + } if !joined { - lines.extend(new_line(pc, &cands)); + // A shape that is only marks in that face may be another character in a face + // fewer shapes fit: it starts its line in the one of those most shapes fit. + let started = new_line(pc, &cands).or_else(|| { + let face = ms + .iter() + .enumerate() + .filter(|(_, m)| !vectorcraft_text::retype::is_combining_mark(m.ch)) + .max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))) + .map(|(_, m)| m.face.id()); + let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); + new_line(pc, &cands) + }); + match started { + Some(l) => lines.push(l), + // Only combining marks: no line starts with one, so the shape stays an outline + // and the glyph after it starts the next line. + None => { + unmatched.push(pc.id); + open = false; + continue; + } + } } open = true; } @@ -1176,7 +1254,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add); let mut lines: Vec = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect(); share_tracking(&mut lines, system_layout); - let mut lines = verified(lines, system_layout, &mut unmatched); + let mut lines = verified(lines, system_layout, &spacing, &mut unmatched); if pieces.len() > 1 { lines.retain(|l| { let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id)); diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs index dc9a413d5f..a901ac7e12 100644 --- a/crates/engine/src/cmd/retype_fonts.rs +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -26,7 +26,7 @@ pub(in crate::cmd) fn specs() -> Vec { "Find Matching Fonts", [], None, - "{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only); of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error", + "{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error", has_selected_path, retype_fonts )] @@ -44,6 +44,8 @@ struct Ranked { matched: usize, /// The sum of those matches' leftover distances. residual: f64, + /// Whether some shape matched a glyph of it that is not a combining mark. + character: bool, } impl Ranked { @@ -101,23 +103,31 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { for pc in &pieces { // A shape can fit several glyphs or poses of one font: it counts once for the font, at its // closest fit. - let mut best: Vec<(Arc, f64)> = vec![]; + let mut best: Vec<(Arc, f64, bool)> = vec![]; for m in index.all_matches(&pc.path) { - match best.iter_mut().find(|(f, _)| f.id() == m.face.id()) { - Some(b) => b.1 = b.1.min(m.residual), - None => best.push((m.face, m.residual)), + let character = !vectorcraft_text::retype::is_combining_mark(m.ch); + match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) { + Some(b) => { + b.1 = b.1.min(m.residual); + b.2 |= character; + } + None => best.push((m.face, m.residual, character)), } } - for (face, residual) in best { + for (face, residual, character) in best { match ranked.iter_mut().find(|r| r.face.id() == face.id()) { Some(r) => { r.matched += 1; r.residual += residual; + r.character |= character; } - None => ranked.push(Ranked { face, matched: 1, residual }), + None => ranked.push(Ranked { face, matched: 1, residual, character }), } } } + // A font whose glyphs match the shapes only as combining marks would retype none of them, as + // type.retype starts no line with a mark: it is not listed. + ranked.retain(|r| r.character); ranked.sort_by(|a, b| { b.matched .cmp(&a.matched) diff --git a/crates/engine/src/cmd/retype_fonts_tests.rs b/crates/engine/src/cmd/retype_fonts_tests.rs index d7e675f503..ac7723d82a 100644 --- a/crates/engine/src/cmd/retype_fonts_tests.rs +++ b/crates/engine/src/cmd/retype_fonts_tests.rs @@ -106,6 +106,21 @@ fn shapes_that_are_no_glyph_list_no_font() { assert!(s.execute("type.retypeFonts", &json!({})).is_err()); } +#[test] +fn a_font_that_matches_only_combining_marks_is_not_listed() { + let mut s = session(); + // A lone combining mark (a drawn dot, bar or ring is the same shape): type.retype keeps it. + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = query(&mut s, json!({}), bundled()); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + // After a base, the mark counts with it. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = query(&mut s, json!({}), bundled()); + assert!(names(&r).contains(&("Source Sans 3".into(), "Regular".into(), 2)), "{r}"); +} + #[test] fn shapes_past_the_limits_are_reported_as_left_out() { let mut s = session(); diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 80361f1e0a..d77fe00774 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -91,6 +91,109 @@ fn a_drawn_shape_is_reported_and_left_alone() { assert!(s.doc().unwrap().doc == before); } +#[test] +fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() { + use vectorcraft_text::test_fonts::{SPACING_COMMA_FAMILY, spacing_comma_font}; + // The comma below of Source Sans 3 is only marks there, and a modifier letter in this face. + vectorcraft_text::FontDb::global().add_font(spacing_comma_font().unwrap()); + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{326}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["\u{2bb}"]), "{r}"); + assert_eq!(r["fonts"][0]["family"], json!(SPACING_COMMA_FAMILY), "{r}"); + // After a base, it joins the line as the mark; moved off its base, the split leaves it first, + // and it becomes the other face's character there. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{326}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2bb}", "yz"]), &json!([])), "{r}"); + assert_eq!(r["fonts"][1]["family"], json!(SPACING_COMMA_FAMILY), "{r}"); +} + +#[test] +fn a_combining_mark_starts_no_line() { + // A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline. + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("no selected shape matches"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); + // A shape that is both a mark (tilde below) and a character (small tilde) starts its line as + // the character. + let g = outlined(&mut s, json!({"x": 140, "y": 100, "text": "\u{303}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["\u{2dc}"]), "{r}"); + // A glyph after it does not turn it back into the mark (diaeresis below, diaeresis). + let g = outlined(&mut s, json!({"x": 240, "y": 100, "text": "\u{324}a", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["\u{a8}", "a"]), &json!([])), "{r}"); + // First on a line, the mark stays an outline and the glyphs after it are retyped. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0; + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab"]), "{r}"); + assert_eq!(r["unmatched"], json!([mark])); + // After a base, the mark is retyped with it. + let g = outlined(&mut s, json!({"x": 40, "y": 300, "text": "x\u{323}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["x\u{323}"]), "{r}"); + // Moved off its base, the mark is where the line splits, and the part after the split does + // not start with it either. + let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": "x\u{312}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}"); + // A mark that is also another character (dot below, dot above) becomes that character there. + let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2d9}", "yz"]), &json!([])), "{r}"); + // Tracked, the part after the mark keeps the tracking its own glyphs are spaced by. + let id = s + .execute("text.create", &json!({"x": 40, "y": 60, "text": "x\u{312}yzw", "size": 40, "font": "Source Sans 3", "style": "Regular"})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 5, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}"); + assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}"); + // A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and + // beside other shapes it stays an outline too. + let dot = outlined(&mut s, json!({"x": 300, "y": 300, "text": "\u{312}.", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mut pair: Vec = s.doc().unwrap().doc.children(Some(NodeId(dot))).unwrap().iter().map(|n| n.id.0).collect(); + pair.sort_unstable(); + let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [dot, word]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab"]), "{r}"); + let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + left.sort_unstable(); + assert_eq!(left, pair, "{r}"); +} + #[test] fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() { let mut s = session(); @@ -922,7 +1025,7 @@ fn the_glyphs_after_one_type_cannot_draw_keep_their_tracking() { l.matches[bad].gid = other; let bad_id = l.pieces[bad]; let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched, vec![bad_id], "{bad}"); let last = out.last().unwrap(); assert_eq!(last.pieces.len(), 5 - bad, "{bad}: {:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); @@ -974,7 +1077,7 @@ fn the_rest_of_a_widely_tracked_line_keeps_its_tracking_after_a_split() { assert_eq!(l.tracking, 8000.0); l.matches[0].gid += 1; let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched.len(), 1); let last = out.last().unwrap(); assert_eq!((last.pieces.len(), last.tracking), (99, 8000.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); @@ -996,7 +1099,7 @@ fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() { m.gid += 1; } let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched.len(), 5); let last = out.last().unwrap(); assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index d7c7be71d6..083aef7d48 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -332,6 +332,13 @@ fn is_shape_symbol(c: char) -> bool { ) } +/// Whether `c` is a combining mark (general category Mn, Mc or Me). A mark combines with the +/// character before it, so no retyped line starts with one. +pub fn is_combining_mark(c: char) -> bool { + use unicode_general_category::{GeneralCategory, get_general_category}; + matches!(get_general_category(c), GeneralCategory::NonspacingMark | GeneralCategory::SpacingMark | GeneralCategory::EnclosingMark) +} + /// Complex multiply: `z` (a scaled turn) applied to `p`. fn mul(z: (f64, f64), p: Point) -> Point { Point::new(z.0 * p.x - z.1 * p.y, z.1 * p.x + z.0 * p.y) @@ -780,6 +787,18 @@ mod tests { } } + #[test] + fn combining_marks_are_told_from_spacing_characters() { + // Nonspacing (Mn), spacing (Mc) and enclosing (Me) marks. + for c in ['\u{0312}', '\u{05BD}', '\u{0903}', '\u{20DD}'] { + assert!(is_combining_mark(c), "{c:?}"); + } + // Spacing forms of the same accents are characters of their own. + for c in ['a', '\u{00A8}', '\u{02DC}', '\u{00AF}', '-'] { + assert!(!is_combining_mark(c), "{c:?}"); + } + } + #[test] fn degenerate_and_hostile_shapes_give_none() { assert!(signature(&BezPath::new()).is_none()); diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 7a2a23f089..1cbc4b6e77 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1518,6 +1518,15 @@ pub fn private_use_font() -> Option> { remapped_source_sans(PRIVATE_USE_FAMILY, "PrivateUseSans-Regular", &[(PRIVATE_USE_CHAR, 'H')]) } +/// The family of [`spacing_comma_font`]. +pub const SPACING_COMMA_FAMILY: &str = "Spacingcomma Sans"; + +/// A face that maps only U+02BB (a modifier letter) to the bundled Source Sans 3 outline of U+0326 +/// (a combining mark), for tests of a shape that is a mark in one face and a character in another. +pub fn spacing_comma_font() -> Option> { + remapped_source_sans(SPACING_COMMA_FAMILY, "SpacingcommaSans-Regular", &[('\u{2BB}', '\u{326}')]) +} + /// The family of [`large_cmap_font`]. pub const LARGE_CMAP_FAMILY: &str = "Largecmap Sans"; diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..9cc1c68b43 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12592,6 +12592,13 @@ per glyph. A line splits where its type stops drawing the outlines in place, and tracking their own gaps give. These rules are VectorCraft's own. Each entry of the result's `fonts` list has `tracking`. +No retyped line starts with a combining mark (Unicode general category Mn, Mc or Me). When a shape would start a line +and the first 16 glyphs it matches include another character's glyph, it starts the line as that character. When they +are all marks, the shape stays an outline and is listed in `unmatched`, and the glyph after it starts the line. The +same holds for a mark at the start of a part that a split leaves: it becomes that other character on a line of its +own, or stays an outline. A mark that follows another glyph on its line is retyped with +that glyph. This rule is VectorCraft's own. + ```json {"name":"run_command","arguments":{"command":"type.retype","params":{}}} ``` @@ -12627,7 +12634,8 @@ name. `count` is a whole number from 1 to 96 (default 10); any other value is an `{fonts: [{family, style, matched}], shapes, more, truncated}`: `matched` is the number of shapes the font matches, `shapes` the number of shapes compared, `more` is true when more fonts match than `count`, and `truncated` is true when shapes past the limits of `type.retype` were left out. Shapes that `type.retype` would keep as outlines because of -their paint still count. The command does not change the document and records no undo step. With no path or compound +their paint still count. A font whose glyphs match the shapes only as combining marks is not listed. The +command does not change the document and records no undo step. With no path or compound path selected it is an error. Window › Retype shows the Retype panel. Find Matching Fonts runs `retype.find {}`, which shows the panel, ranks up to From fd33180c84423597002fb801b44ff4ed5b7d5040 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 21:50:34 -0800 Subject: [PATCH 024/178] Live Corners: a Selection tool double-click on a corner widget shows the Transform panel With the Selection tool, a double-click on a visible corner widget of a selected live rectangle or polygon now shows and selects the Transform panel, where the shape's corner radius fields are, as the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools already do. It used to open the Corners dialog. The tool, the selection, the document and the undo history stay as they were. Direct Selection's double-click still opens Corners. Docs: docs/mcp.md (Live Corners), the ui.corners params text, docs/ui-parity.md and docs/target-app-parity.md. Part of #1232 --- crates/engine/src/tests/livecorners.rs | 33 +++++++++++++++++++++++++ crates/mcp/src/tests/shapewidgets.rs | 9 +++++-- crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/corners.rs | 6 +++-- crates/tools/src/corners/tests.rs | 15 +++++++++-- crates/tools/src/select.rs | 9 +++++-- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 8 ++++-- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 10 files changed, 74 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 288f0236d1..96a2aedff8 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -1002,3 +1002,36 @@ fn a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_pa assert!(st.interaction.is_none()); assert_eq!(s.tool_id(), "rectangle"); } + +/// A double-click on a corner widget of a selected live rectangle with the Selection tool asks +/// the frontend for the Transform panel, and leaves the document, its undo history, the +/// selection and the tool as they were; with Direct Selection it still opens Corners. +#[test] +fn a_double_click_on_a_corner_widget_with_the_selection_tool_asks_for_the_transform_panel() { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + let (mut s, id) = session(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let v = ViewInfo::default(); + let st = s.doc().unwrap(); + let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show"); + let at = w.visible().next().expect("a widget"); + let (doc, selection, steps) = (st.doc.clone(), st.selection.clone(), st.history.undo.len()); + let double_click = |s: &mut Session, tool: &str| { + s.select_tool(tool, v).unwrap(); + let mut asked = vec![]; + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + asked.extend(s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(Mods::default()), v).unwrap()); + } + asked + }; + assert_eq!(double_click(&mut s, "selection"), vec![UiRequest::Panel("transform".into())]); + let st = s.doc().unwrap(); + assert!(*st.doc == *doc, "the document is unchanged"); + assert_eq!(st.selection, selection); + assert_eq!(st.history.undo.len(), steps, "no undo step"); + assert!(st.interaction.is_none()); + assert_eq!(s.tool_id(), "selection"); + // Direct Selection opens Corners for the corner it picked with the first click. + let asked = double_click(&mut s, "directSelection"); + assert!(matches!(asked.as_slice(), [UiRequest::Dialog(k, _)] if k == vectorcraft_tools::corners::DIALOG), "{asked:?}"); +} diff --git a/crates/mcp/src/tests/shapewidgets.rs b/crates/mcp/src/tests/shapewidgets.rs index bce666d484..06bb550219 100644 --- a/crates/mcp/src/tests/shapewidgets.rs +++ b/crates/mcp/src/tests/shapewidgets.rs @@ -1,5 +1,6 @@ -//! Live shape widgets through MCP: a shape tool's double-click on a selected live shape's corner -//! widget, whose gesture's `requests` carry the Transform panel, and a drag on a live polygon's +//! Live shape widgets through MCP: a shape tool's or the Selection tool's double-click on a +//! selected live shape's corner widget, whose gesture's `requests` carry the Transform panel, and a +//! drag on a live polygon's //! side widget. use serde_json::{Value, json}; @@ -28,6 +29,10 @@ fn a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel() // Off the widgets, the double-click asks for nothing. let off = ok(&mut h, "pointer_gesture", json!({"events": [{"kind": "doubleclick", "x": 280, "y": 280}]})); assert_eq!(off["requests"], json!([]), "{off}"); + // The Selection tool's double-click on the widget asks for the panel too. + let sel = ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [{"kind": "doubleclick", "x": at.x, "y": at.y}]})); + assert_eq!(sel["requests"], json!([{"panel": "transform"}]), "{sel}"); + assert_eq!(h.session.doc().unwrap().history.undo.len(), steps, "no undo step"); } /// The selected live polygon's sides, radius and transform. diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 359f41676b..68f43889f7 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.corners", "Corners…", "", - "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget opens it too): OK runs object.setLiveShape", + "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget with Direct Selection opens it too): OK runs object.setLiveShape", ), ( "ui.simplifyAuto", diff --git a/crates/tools/src/corners.rs b/crates/tools/src/corners.rs index ab234cf507..00f72f6f4d 100644 --- a/crates/tools/src/corners.rs +++ b/crates/tools/src/corners.rs @@ -4,7 +4,8 @@ //! sharpens) the corners whose widgets show together, on every selected path (#938): every corner //! of a path selected whole, those with a selected anchor when Direct Selection picked some. Alt-clicking a widget cycles their corner //! kind (round, inverted round, chamfer), as the Up and Down arrows do while one is dragged -//! (#2898); double-clicking one opens the Corners dialog. The +//! (#2898); double-clicking one opens the Corners dialog with Direct Selection and shows the +//! Transform panel with the Selection tool. The //! Selection and Direct Selection tools share this, and the canvas draws the widgets from the same //! geometry. @@ -212,7 +213,8 @@ pub fn over_widget(cx: &ToolContext, p: Point, any_path: bool) -> bool { CornerWidgets::for_tool(cx, any_path).and_then(|w| w.hit(p, cx.tol(5.0))).is_some() } -/// A double-click on a corner widget opens the Corners dialog for the shown corners of its path. +/// A double-click on a corner widget opens the Corners dialog for the shown corners of its path +/// (Direct Selection; the Selection tool shows the Transform panel instead). pub fn double_click(cx: &ToolContext, p: Point, any_path: bool) -> Option { let w = CornerWidgets::for_tool(cx, any_path)?; let (i, _) = w.hit(p, cx.tol(5.0))?; diff --git a/crates/tools/src/corners/tests.rs b/crates/tools/src/corners/tests.rs index 21b240b453..e9235b33e9 100644 --- a/crates/tools/src/corners/tests.rs +++ b/crates/tools/src/corners/tests.rs @@ -355,13 +355,24 @@ fn alt_click_cycles_the_kind_and_double_click_opens_the_dialog() { assert_eq!(a, vec![Action::Exec("object.setLiveShape".into(), want.clone())], "{tool}"); } } - // A double-click on a widget opens Corners for the shown corners; elsewhere it doesn't. + // With Direct Selection, a double-click on a widget opens Corners for the shown corners; + // elsewhere it doesn't. let cx1 = cx(&d, &part, &p); let a = crate::create("directSelection").pointer(&cx1, &PointerEvent::new(PointerKind::DoubleClick, 110.0, 110.0)); assert_eq!(a, vec![Action::Dialog(DIALOG.into(), json!({"id": id.0, "corners": [0]}))]); let cx2 = cx(&d, &whole, &p); - let a = crate::create("selection").pointer(&cx2, &PointerEvent::new(PointerKind::DoubleClick, 190.0, 110.0)); + let a = crate::create("directSelection").pointer(&cx2, &PointerEvent::new(PointerKind::DoubleClick, 190.0, 110.0)); assert_eq!(a, vec![Action::Dialog(DIALOG.into(), json!({"id": id.0, "corners": [0, 1, 2, 3]}))]); + // With the Selection tool, it shows the Transform panel instead, on any of the widgets. + for at in [(110.0, 110.0), (190.0, 110.0), (190.0, 190.0), (110.0, 190.0)] { + let a = crate::create("selection").pointer(&cx2, &PointerEvent::new(PointerKind::DoubleClick, at.0, at.1)); + assert_eq!(a, vec![Action::Panel("transform".into())], "{at:?}"); + } + // With the shape widgets hidden, the same double-click isolates the shape, as off the widgets. + let mut hidden = cx(&d, &whole, &p); + hidden.shape_widgets = false; + let a = crate::create("selection").pointer(&hidden, &PointerEvent::new(PointerKind::DoubleClick, 190.0, 110.0)); + assert_eq!(a, vec![Action::Exec("object.isolate".into(), json!({"id": id.0}))]); // Off the widgets, the Selection tool's double-click isolates the shape (Double Click To // Isolate) instead. let a = crate::create("selection").pointer(&cx2, &PointerEvent::new(PointerKind::DoubleClick, 150.0, 150.0)); diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index fc18a978e6..faa2d2cd8d 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -4,7 +4,7 @@ //! bounding-box scale (Shift proportional, Alt from center; Snap to Grid, Snap to Pixel, Smart //! Guides and Snap to Point snap what the handle moves) and rotate (outside corners, Shift 45°), //! drag a live rectangle's or polygon's corner widget to round its corners (Alt-click cycles their kind, -//! double-click opens the Corners dialog), drag a live ellipse's pie widgets to set its pie angles +//! double-click shows the Transform panel), drag a live ellipse's pie widgets to set its pie angles //! (double-click makes it whole again: [`crate::pie`]), double-click a group or an object to enter isolation //! mode (Double Click To Isolate), Cmd/Ctrl-click to select the object behind (Command Click to Select Objects Behind), //! click or drag a ruler guide ([`crate::rulerguide`]), Cmd/Ctrl+Shift-double-click a ruler guide or @@ -1789,7 +1789,12 @@ impl SelectionTool { } return vec![]; } - if let Some(a) = corners::double_click(cx, p, false).or_else(|| pie::double_click(cx, p)).or_else(|| typewidget::double_click(cx, p)) { + // A corner widget of a selected live shape shows the Transform panel, as with the shape + // tools; the tool and the selection stay as they are. Direct Selection opens Corners. + if corners::over_widget(cx, p, false) { + return vec![Action::Panel("transform".into())]; + } + if let Some(a) = pie::double_click(cx, p).or_else(|| typewidget::double_click(cx, p)) { return vec![a]; } // The Shaper Group's mode widget answers each click of a double-click on it. diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4602e12072..c356bc207e 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1533,7 +1533,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.corners", "Corners…", "", - "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget opens it too): OK runs object.setLiveShape", + "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget with Direct Selection opens it too): OK runs object.setLiveShape", ), ( "ui.simplifyAuto", diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..9431c342d8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7693,8 +7693,12 @@ outlining in red those that reach their limit; the Selection tool shows the widg the Direct Selection tool those of any path. `rectanglesOnly: true` sets them on the live rectangles among the targets alone and leaves the other objects as they are (the Rectangle Properties corner fields and menus send it with the selection, so an action that records them acts on the rectangles selected when it plays). Several objects each with their own corners are one call: -`items: [{id, corners?}]` in place of `ids` and `corners`. Alt-clicking one cycles their kind and double-clicking one opens Corners (`ui.corners {id?, corners?}`, -dialog `corners`: `kind`, `radius`; OK runs `object.setLiveShape`). +`items: [{id, corners?}]` in place of `ids` and `corners`. Alt-clicking one cycles their kind. Double-clicking one with Direct Selection opens Corners (`ui.corners {id?, corners?}`, +dialog `corners`: `kind`, `radius`; OK runs `object.setLiveShape`). Double-clicking a selected live shape's corner +widget with the Selection tool shows and selects the Transform panel, as the Rectangle, Rounded Rectangle, Ellipse, +Polygon and Star tools do. With the headless backend, the `pointer_gesture` reply carries `{"panel": "transform"}` in its +`requests`; the desktop app runs `window.panel.activate {"panel": "transform"}` instead, and its reply has no `requests`. The tool, the selection and the document stay as they are, and +no undo step is added. `view.shapeWidgets {on?}` (desktop app, the Hide Shape Widgets and Show Shape Widgets button in the Control bar of the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools) hides or shows the corner widgets of selected live rectangles and polygons, the pie widgets of live ellipses and the side widget of a live polygon, for the Selection tool diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..5f6f4ae48d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1479,7 +1479,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, an Alt-click on a path selected whole adds its group, and each further Alt-click adds the next group up, as Group Selection's clicks do; the climb stops below the layer and its sublayers and at the isolated object. An Alt-drag still copies the selection, and Alt+Shift-click on a segment or the fill still adds or removes the path. Public references: [Select objects](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copies). With Alt held at the press, a Direct Selection marquee is Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), not the anchors inside it, and the Group Selection pointer stays until the release (#4890; test `an_alt_marquee_selects_the_paths_it_touches_whole`). With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). + - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it with Direct Selection for the Corners dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)) or with the Selection tool for the Transform panel (a double-click on a selected live shape's corner widget shows the Transform panel, [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html); which tool gives which is VectorCraft's own rule), and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 911f08d192..1187ea9844 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -267,7 +267,7 @@ tools, never checked side by side) isn't captured row by row. | Alt with Direct Selection makes a marquee Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), and the Group Selection pointer stays until the release | done | #4890 | | Direct Selection: a click on a selected object's centre point (Attributes › Show Center) selects the object whole, and a drag from it moves the object in one undo step | done | #4891 | | Escape cancels a Direct Selection drag | done | #1803 (#1743) | -| Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | +| Live Corners widgets (radius readout, Alt-click cycles kind, Direct Selection double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; a double-click on a selected live shape's corner widget shows the Transform panel ([Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)) and a Direct Selection double-click opens Corners ([Create and modify live shapes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)); giving the Transform panel to the Selection tool and Corners to Direct Selection is VectorCraft's own rule; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | | Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets | | Side widget on a live polygon: drag it to set the number of sides from 3 to 11 | done | Selection tool and the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets; a drag down adds sides and a drag up removes them; Escape cancels ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html)) | From f355716ffe5079d0223bc1c0bc920e3b904e37ce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 22:26:27 -0800 Subject: [PATCH 025/178] Retype: a mark first after a split leaves the shared measures alone When the rest of a line after a mark that a split left first starts with another mark, that rest is no longer measured for tracking. Its own pass leaves the mark out and measures the glyphs after it, so the earlier measure was thrown away but still took from the measures shared by every line in the call. A run of marks could use them up, and a tracked line retyped with them then lost its tracking and split glyph by glyph. --- crates/engine/src/cmd/retype.rs | 8 ++++-- crates/engine/src/cmd/retype_tests.rs | 35 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 51d9398870..ad222dd5d3 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -648,9 +648,13 @@ fn verified( } if n > 1 { // The tracking was measured with the mark's gap in it: the rest is measured again - // without it, from the same budgets as the rest after a split. + // without it, from the same budgets as the rest after a split. A rest that starts + // with a mark too is not measured here: its own pass leaves that mark out and + // measures the glyphs after it. let measurable = n > 3 && remeasured >= (n - 1).saturating_mul(6) && track_budget >= (n - 1).saturating_mul(6); - let rest = if measurable { + let rest = if l.matches.get(1).is_some_and(|m| vectorcraft_text::retype::is_combining_mark(m.ch)) { + l.part(1, n) + } else if measurable { remeasured = remeasured.saturating_sub((n - 1).saturating_mul(6)); track_budget = track_budget.saturating_sub(n - 1); l.respaced(1, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget)) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index d77fe00774..a862a3f1b5 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -194,6 +194,41 @@ fn a_combining_mark_starts_no_line() { assert_eq!(left, pair, "{r}"); } +#[test] +fn marks_first_after_a_split_leave_other_lines_their_tracking() { + // Twenty marks moved off their base, each one first on its line in turn, do not use up the + // measures of the other lines: the tracked line retyped with them keeps its tracking. + let mut s = session(); + let marks = outlined( + &mut s, + json!({"x": 40, "y": 100, "text": format!("x{}a", "\u{312}".repeat(20)), "size": 40, "font": "Source Sans 3", "style": "Regular"}), + ); + let mut moved: Vec = s.doc().unwrap().doc.children(Some(NodeId(marks))).unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(moved.len(), 22); + moved = moved[1..21].to_vec(); + let id = s + .execute("text.create", &json!({"x": 40, "y": 300, "text": "x\u{312}yzw", "size": 40, "font": "Source Sans 3", "style": "Regular"})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 5, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let tracked = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mark = s.doc().unwrap().doc.children(Some(NodeId(tracked))).unwrap()[1].id.0; + moved.push(mark); + s.execute("select.set", &json!({"ids": moved})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts = r["texts"].as_array().unwrap(); + let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}")); + assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}"); + let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + left.sort_unstable(); + moved.sort_unstable(); + assert_eq!(left, moved, "{r}"); +} + #[test] fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() { let mut s = session(); From cbe31304f10c9e01bd469f4c5a3713727c76bffa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 22:38:14 -0800 Subject: [PATCH 026/178] Docs: the Selection tool's corner widget double-click shows the Transform panel in the shape tools entry --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1187ea9844..7ae6226a81 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -271,7 +271,7 @@ tools, never checked side by side) isn't captured row by row. | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | | Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets | | Side widget on a live polygon: drag it to set the number of sides from 3 to 11 | done | Selection tool and the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets; a drag down adds sides and a drag up removes them; Escape cancels ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html)) | -| A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing (the corner and pie widgets only while the Control bar's Hide Shape Widgets has not hidden them; the bounding box stays); a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). A drag on one of the box's handles scales the selection as the Selection tool's handles do. A double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel where it is (closed, docked, floating or in an icon column; a second double-click keeps it on show), and leaves the tool, the selection and the document as they were; a double-click on a pie widget, off the widgets, with Show Corner Widget off or with Line Segment does nothing, and the Selection tool's double-click on a corner widget still opens the Corners dialog. Public description: [Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) (a double-click on a corner widget of a selected live shape opens the Transform panel). Tests `a_shape_tool_drags_the_selected_shapes_widgets`, `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner`, `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_double_click_on_a_corner_widget_shows_the_transform_panel`, `a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel` (engine), `a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel` (MCP: the `pointer_gesture` reply's `requests` carry `{"panel": "transform"}`) and `a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown` (UI) | +| A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing (the corner and pie widgets only while the Control bar's Hide Shape Widgets has not hidden them; the bounding box stays); a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). A drag on one of the box's handles scales the selection as the Selection tool's handles do. A double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel where it is (closed, docked, floating or in an icon column; a second double-click keeps it on show), and leaves the tool, the selection and the document as they were; a double-click on a pie widget, off the widgets, with Show Corner Widget off or with Line Segment does nothing; the Selection tool's double-click on a corner widget shows the Transform panel too, and a Direct Selection double-click opens the Corners dialog. Public description: [Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) (a double-click on a corner widget of a selected live shape opens the Transform panel). Tests `a_shape_tool_drags_the_selected_shapes_widgets`, `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner`, `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_double_click_on_a_corner_widget_shows_the_transform_panel`, `a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel` (engine), `a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel` (MCP: the `pointer_gesture` reply's `requests` carry `{"panel": "transform"}`) and `a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown` (UI) | | Isolation mode by double-click (groups and single objects), breadcrumbs, Esc to exit | done | Single paths, compound paths, images, meshes and placed files isolate too ([helpx: Isolate objects](https://helpx.adobe.com/africa/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)); locking or hiding the layer (or a group) around the isolated object afterwards keeps clicks and marquees off it, as outside isolation mode (#5309) | | "Magnetic" moves of selected anchors with a modifier (#955 request) | missing | not a feature of the reference app as documented; under discussion | | Coinciding anchors of overlapping objects: the selected object's anchor is taken, also under another object | done | #1508 | From 018d6c87aa6345a74685764b65262a3f89d2c748 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 07:33:33 -0800 Subject: [PATCH 027/178] 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 028/178] 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 c4e360fec288cd4f57c87e225efc2ac41ad66119 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:57:41 -0800 Subject: [PATCH 029/178] Align: align.toSelection returns "artboard" only for one object with no anchor points selected The align.toSelection params text and docs/mcp.md said the command returns "artboard" while one object is selected. With anchor points selected (Direct Selection) it returns "selection", because the points align to each other, and with the Artboard tool chosen it returns the stored choice, Selection. The texts now name both cases, and crates/mcp/src/ui_catalog.rs is regenerated with cargo xtask ui-commands. A test covers two anchor points of one path selected while Artboard is the stored choice. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/align/tests.rs | 14 ++++++++++++++ docs/mcp.md | 4 +++- 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..1a8e3730b4 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -395,7 +395,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "align.toSelection", "Align to Selection", "", - "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected, since one object aligns to the artboard}; with the Artboard tool chosen the selected objects keep their key", + "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected with no anchor points selected, since one object aligns to the artboard; \"selection\" while anchor points are selected (Direct Selection) and with the Artboard tool chosen}; with the Artboard tool chosen the selected objects keep their key", ), ( "align.toKeyObject", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..cc6466fa94 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -396,7 +396,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "align.toSelection", "Align to Selection", "", - "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected, since one object aligns to the artboard}; with the Artboard tool chosen the selected objects keep their key", + "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected with no anchor points selected, since one object aligns to the artboard; \"selection\" while anchor points are selected (Direct Selection) and with the Artboard tool chosen}; with the Artboard tool chosen the selected objects keep their key", ), ( "align.toKeyObject", diff --git a/crates/ui-egui/src/panels/align/tests.rs b/crates/ui-egui/src/panels/align/tests.rs index ffdc0b10a3..77194f7623 100644 --- a/crates/ui-egui/src/panels/align/tests.rs +++ b/crates/ui-egui/src/panels/align/tests.rs @@ -679,6 +679,20 @@ fn object_align_lists_the_align_to_choices() { assert_eq!(app.ui.align_to, AlignTo::Selection); } +/// With anchor points of one path selected (Direct Selection), Align to Selection returns +/// `"selection"`: the points align to each other, so the lone path does not make it Artboard. +#[test] +fn align_to_selection_with_anchor_points_returns_selection() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("path.create", json!({"d": "M100 40 L200 60 L150 160 Z"})).unwrap()["id"].as_u64().unwrap(); + app.ui.align_to = AlignTo::Artboard; + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + assert_eq!(app.run("align.toSelection", json!({})).unwrap(), json!({"alignTo": "selection"})); + assert_eq!(app.ui.align_to, AlignTo::Selection); + assert_eq!(align_to_checks(&app), [Some(true), Some(false), Some(false)]); +} + /// With the Artboard tool chosen, Align to Key Object is off and fails, and Align to Artboard and /// Align to Selection store the choice while the selected objects keep their key. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..0ad023455a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7827,7 +7827,9 @@ and each item runs its command. The Align panel's Align To choices are UI commands too, with no params: `align.toSelection`, `align.toKeyObject` and `align.toArtboard`. Each chooses what a click on its Align To button chooses and returns `{alignTo}`, the choice the -panel then shows (`align.toSelection` returns `"artboard"` while one object is selected, which aligns to the artboard). +panel then shows (`align.toSelection` returns `"artboard"` while one object is selected with no anchor points selected, +which aligns to the artboard; it returns `"selection"` while anchor points are selected with Direct Selection, which +align to each other, and with the Artboard tool chosen). `align.toSelection` and `align.toArtboard` store the choice (`ui.inspect` › `ui.align_to`) and let the key go; with the Artboard tool chosen they store it and the selected objects keep their key. With no key, `align.toKeyObject` makes the topmost of two or more selected objects the key object, or a ruler guide selected with one object the key guide, and From d3985afb348a749d909bb22546ea0671f9ebaddc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:21:13 -0800 Subject: [PATCH 030/178] i18n: the message scan reads string escapes the way Rust does The untranslated-strings scan kept only the letter after a backslash for every escape other than \n, \t and a line continuation, so a message with \r, \0, \x41 or \u{e9} was checked against text the program never shows. It now decodes every character escape the Rust Reference lists (https://doc.rust-lang.org/reference/tokens.html#character-escapes), and leaves out a literal whose escape Rust rejects, such as \q, \x80 or \u{D800}, instead of building a key from it. The interface-string and message dumps are byte-identical before and after the change, so no catalog row matches differently. --- crates/ui-egui/src/i18n/tests.rs | 86 ++++++++++++++++++++++++++++++-- docs/target-app-parity.md | 1 + 2 files changed, 84 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..25e378a43a 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -4653,6 +4653,55 @@ fn message_scan_joins_a_literal_continued_on_the_next_line() { } } +/// The scan reads each of Rust's character escapes in a message as the character Rust gives it +/// (https://doc.rust-lang.org/reference/tokens.html#character-escapes), and stops at the literal's +/// own closing quote, not at an escaped one. +#[test] +fn message_scan_decodes_rust_character_escapes() { + let cases = [ + (r#"a\rb" tail"#, "a\rb"), + (r#"a\0b""#, "a\0b"), + (r#"\x41\x7f\x7F""#, "A\x7f\x7f"), + (r#"caf\u{e9}""#, "café"), + (r#"caf\u{E_9}""#, "café"), + (r#"\u{1F600}\u{10_FFFF}\u{0}""#, "\u{1F600}\u{10FFFF}\0"), + (r#"a\\b""#, "a\\b"), + (r#"say \"hi\"" tail"#, "say \"hi\""), + (r#"it\'s""#, "it's"), + (r#"\n\t""#, "\n\t"), + ]; + let wrong: Vec<_> = cases.iter().filter(|(body, text)| string_literal(body).as_deref() != Some(*text)).collect(); + assert!(wrong.is_empty(), "{wrong:?}"); + let found = source_messages(r#"fn run() { let _ = Err("bad \x41 value \u{e9}"); }"#, &[], &Default::default()); + assert_eq!(found, ["bad A value é"]); +} + +/// A literal with an escape Rust does not accept is not read as a message: an unknown letter, `\x` +/// with fewer than two hex digits or above `7F`, and `\u` without braces, without digits, with a +/// leading underscore, with more than six digits, or naming a surrogate or a value above `10FFFF`. +#[test] +fn message_scan_rejects_invalid_rust_escapes() { + let bodies = [ + r#"bad \q""#, + r#"bad \x4""#, + r#"bad \x4g""#, + r#"bad \x80""#, + r#"bad \x+1""#, + concat!(r"bad \u", "00e9\""), + r#"bad \u{""#, + r#"bad \u{}""#, + r#"bad \u{_e9}""#, + r#"bad \u{e9""#, + r#"bad \u{D800}""#, + r#"bad \u{110000}""#, + r#"bad \u{1234567}""#, + ]; + let read: Vec<_> = bodies.iter().filter(|body| string_literal(body).is_some()).collect(); + assert!(read.is_empty(), "{read:?}"); + let code = r#"fn run() { let _ = Err("bad \q value"); let _ = Err("bad \u{D800} value"); let _ = Err("good value"); }"#; + assert_eq!(source_messages(code, &[], &Default::default()), ["good value"]); +} + /// The scan reads the message of each of the plug-in host's [`ERROR_HELPERS`]: a literal, a /// `format!` string with or without a `&` before it, after the location of `out_err` (a /// `format!` string too), the number and range of `in_range`, the number and location of `unit`, @@ -7362,8 +7411,12 @@ fn without_test_module(text: &str) -> &str { text } -/// The text of a string literal whose opening quote was just read, escapes resolved. A `\` at the -/// end of a line drops the line break and the whitespace that starts the next line, as Rust does. +/// The text of a string literal whose opening quote was just read, escapes resolved as Rust resolves +/// them (https://doc.rust-lang.org/reference/tokens.html#character-escapes): `\n`, `\r`, `\t`, `\0`, +/// `\\`, `\'`, `\"`, `\x` with two hex digits up to `7F`, and `\u{…}` with one to six hex digits +/// (underscores allowed after the first) naming a Unicode scalar value. A `\` at the end of a line +/// drops the line break and the whitespace that starts the next line. A literal with any other +/// escape, or one left unclosed, is `None`. fn string_literal(s: &str) -> Option { let mut out = String::new(); let mut it = s.chars(); @@ -7372,9 +7425,36 @@ fn string_literal(s: &str) -> Option { '"' => return Some(out), '\\' => match it.next()? { 'n' => out.push('\n'), + 'r' => out.push('\r'), 't' => out.push('\t'), + '0' => out.push('\0'), + c @ ('\\' | '\'' | '"') => out.push(c), + 'x' => { + let (high, low) = (it.next()?.to_digit(16)?, it.next()?.to_digit(16)?); + out.push(char::from_u32(high * 16 + low).filter(char::is_ascii)?); + } + 'u' => { + if it.next()? != '{' { + return None; + } + let (mut value, mut digits) = (0u32, 0); + loop { + match it.next()? { + '}' if digits > 0 => break, + '_' if digits > 0 => {} + c => { + value = value * 16 + c.to_digit(16)?; + digits += 1; + if digits > 6 { + return None; + } + } + } + } + out.push(char::from_u32(value)?); + } '\n' | '\r' => it = it.as_str().trim_start_matches([' ', '\t', '\n', '\r']).chars(), - c => out.push(c), + _ => return None, }, c => out.push(c), } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..77b2531f39 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1151,6 +1151,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Polish labels and messages call drawn art and artwork *kompozycja*, the term the catalog's header sets, instead of *grafika* or *rysunek*. *Grafika* stays for what the English calls a graphic (graphic styles, library and 3D graphics, GPU graphics), and line art, the art brush and an artboard (*obszar kompozycji*) keep their own terms (`polish_rows_call_artwork_kompozycja`). - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - The untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog's (`ka`) row for PDF export's warning about knockout groups with too many translucent elements matches that text (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). + - The untranslated-strings report reads the escapes in a message (`\r`, `\0`, `\x41`, `\u{e9}` and the others the Rust Reference lists at https://doc.rust-lang.org/reference/tokens.html#character-escapes) as the characters the program shows, and leaves out a literal with an escape Rust does not accept, such as `\q` or `\u{D800}` (`message_scan_decodes_rust_character_escapes`, `message_scan_rejects_invalid_rust_escapes`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). - The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`). From 5744a52e1e08cb1aca5c20b6e6ce5908109772f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:13:07 -0800 Subject: [PATCH 031/178] 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 032/178] 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 033/178] 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 a6c0557819487afa2b0926beffd5ee17810817a9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:28:12 -0800 Subject: [PATCH 034/178] Align: align.toSelection returns "artboard" for one object only without the Artboard tool With one object selected, no anchor points selected and the Artboard tool chosen, align.toSelection returns "selection", the stored choice. The params text and docs/mcp.md now name that condition, and crates/mcp/src/ui_catalog.rs is regenerated. A test covers the case. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/align/tests.rs | 13 +++++++++++++ docs/mcp.md | 6 +++--- 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 1a8e3730b4..75ae121ece 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -395,7 +395,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "align.toSelection", "Align to Selection", "", - "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected with no anchor points selected, since one object aligns to the artboard; \"selection\" while anchor points are selected (Direct Selection) and with the Artboard tool chosen}; with the Artboard tool chosen the selected objects keep their key", + "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected with no anchor points selected and the Artboard tool is not chosen, since one object aligns to the artboard; \"selection\" while anchor points are selected (Direct Selection) and with the Artboard tool chosen}; with the Artboard tool chosen the selected objects keep their key", ), ( "align.toKeyObject", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index cc6466fa94..8cc699ea76 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -396,7 +396,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "align.toSelection", "Align to Selection", "", - "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected with no anchor points selected, since one object aligns to the artboard; \"selection\" while anchor points are selected (Direct Selection) and with the Artboard tool chosen}; with the Artboard tool chosen the selected objects keep their key", + "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected with no anchor points selected and the Artboard tool is not chosen, since one object aligns to the artboard; \"selection\" while anchor points are selected (Direct Selection) and with the Artboard tool chosen}; with the Artboard tool chosen the selected objects keep their key", ), ( "align.toKeyObject", diff --git a/crates/ui-egui/src/panels/align/tests.rs b/crates/ui-egui/src/panels/align/tests.rs index 77194f7623..7bbcb1af18 100644 --- a/crates/ui-egui/src/panels/align/tests.rs +++ b/crates/ui-egui/src/panels/align/tests.rs @@ -713,6 +713,19 @@ fn align_to_commands_with_the_artboard_tool() { assert_eq!(app.session.active().unwrap().selection.key.map(|k| k.0), front.as_u64(), "the key stays"); } +/// With the Artboard tool chosen and one object selected with no anchor points, Align to Selection +/// returns `"selection"`, the stored choice, not `"artboard"`. +#[test] +fn align_to_selection_with_one_object_and_the_artboard_tool_returns_selection() { + let (mut app, back, _) = back_and_front(); + app.run("select.set", json!({"ids": [back]})).unwrap(); + app.ui.align_to = AlignTo::Artboard; + app.select_tool("artboard"); + assert_eq!(app.run("align.toSelection", json!({})).unwrap(), json!({"alignTo": "selection"})); + assert_eq!(app.ui.align_to, AlignTo::Selection); + assert_eq!(align_to_checks(&app), [Some(true), Some(false), Some(false)]); +} + /// Align to Key Object is off and fails when the topmost selected object can't be the key: a group /// selected with an object inside it. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 0ad023455a..4d1de4b1ff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7827,9 +7827,9 @@ and each item runs its command. The Align panel's Align To choices are UI commands too, with no params: `align.toSelection`, `align.toKeyObject` and `align.toArtboard`. Each chooses what a click on its Align To button chooses and returns `{alignTo}`, the choice the -panel then shows (`align.toSelection` returns `"artboard"` while one object is selected with no anchor points selected, -which aligns to the artboard; it returns `"selection"` while anchor points are selected with Direct Selection, which -align to each other, and with the Artboard tool chosen). +panel then shows (`align.toSelection` returns `"artboard"` while one object is selected with no anchor points selected +and the Artboard tool is not chosen, which aligns to the artboard; it returns `"selection"` while anchor points are +selected with Direct Selection, which align to each other, and with the Artboard tool chosen). `align.toSelection` and `align.toArtboard` store the choice (`ui.inspect` › `ui.align_to`) and let the key go; with the Artboard tool chosen they store it and the selected objects keep their key. With no key, `align.toKeyObject` makes the topmost of two or more selected objects the key object, or a ruler guide selected with one object the key guide, and From 5132eaebfeb33043584dbbc92f734a1e9708f476 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:42:31 -0800 Subject: [PATCH 035/178] PDF: a distorted CMYK image with an image mask keeps the resolution its pieces need A distorted CMYK image whose opacity mask is a gray image with the same corners writes the mask as the image's /SMask, and every piece of its mesh draws that one image. The image was resampled for the size its transform places it at, before the pieces' shared size was known, so with downsampling on every piece stretched a smaller image across the corners. The masked image is now resampled for the size the pieces share, as the same image without a mask is, and the pieces are drawn from the same expansion they were measured on. --- crates/pdf/src/export/images.rs | 25 ++++++++++++++++ crates/pdf/src/export/nodes.rs | 6 ++-- crates/pdf/src/tests/cmykimages.rs | 46 ++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 2 deletions(-) diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 3da2079b9b..b43e758377 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -223,6 +223,31 @@ impl Exporter<'_> { img } + /// [`Self::masked_image`] of image `im` of node `n`. A distorted image's is resampled for the + /// size every piece of its mesh shares ([`Self::warp_image_size`]), since each piece draws this + /// one image; its expanded art, whose pieces were measured, is left in `expanded` for drawing. + pub(super) fn node_masked_image( + &mut self, + n: &Node, + im: &vectorcraft_doc::ImageObject, + m: &vectorcraft_doc::OpacityMask, + expanded: &mut Option, + ) -> Option { + let interpolate = !n.extras().pixelated; + if !n.is_distorted_image() { + return self.masked_image(im, m, interpolate); + } + let g = expanded.insert(vectorcraft_effects::expand_live_deep(Some(self.doc), n)); + let pieces = g.children().and_then(|c| c.first()).map_or(&[][..], |art| vectorcraft_doc::image_quad::distorted_pieces(art)); + let shared = self.warp_image_size(pieces).map(|s| SharedSize { key: im.key.clone(), width: im.width, height: im.height, size: s.size }); + let outer = shared.map(|w| self.warp_size.replace(w)); + let img = self.masked_image(im, m, interpolate); + if let Some(outer) = outer { + self.warp_size = outer; + } + img + } + /// Draw image `im`: `img` when given (its pixels already written), else as it is loaded; with /// `pixelated` ([`vectorcraft_doc::NodeExtras::pixelated`]) viewers are asked not to smooth it. pub(super) fn image(&mut self, s: &mut Surface, im: &vectorcraft_doc::ImageObject, img: Option, pixelated: bool) { diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 94b1c819c5..1d514a569d 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -373,9 +373,11 @@ impl Exporter<'_> { let enclosing = std::mem::replace(&mut self.knockout, knockout); let (mut pushes, isolated_children) = transparency(s, n, page, container, knockout); let mask = n.extras().mask.as_deref().filter(|m| !m.disabled); + // A distorted image's art, when its masked image needs the size its pieces share. + let mut expanded = None; let alpha = match (&n.kind, mask) { // The mask's image shares the pixel grid only when it has the same corners (or none). - (NodeKind::Image(im), Some(m)) if n.image_quad() == m.art.image_quad() => self.masked_image(im, m, !n.extras().pixelated), + (NodeKind::Image(im), Some(m)) if n.image_quad() == m.art.image_quad() => self.node_masked_image(n, im, m, &mut expanded), _ => None, }; if let Some(m) = mask @@ -502,7 +504,7 @@ impl Exporter<'_> { | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } | NodeKind::Image(_) => { - let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + let g = expanded.unwrap_or_else(|| vectorcraft_effects::expand_live_deep(Some(self.doc), n)); // The pieces draw the image as it is shown, under its color mask's key. let piece = match (&n.kind, &alpha) { (NodeKind::Image(im), Some(img)) => Some((self.doc.shown_image(n, im).key.clone(), img.clone())), diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index b5f6185ea9..83f9340dc0 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -1210,6 +1210,52 @@ fn a_distorted_cmyk_image_and_its_grid_mask_with_the_same_corners_write_it_as_it } } +/// A distorted CMYK image masked on its pixel grid is resampled for the size its mesh's pieces +/// share, as it is without the mask, and not for the smaller size its transform places it at: +/// every piece draws the one image, so a smaller one would lower the resolution of every piece. +#[test] +fn a_distorted_cmyk_image_with_its_grid_mask_is_resampled_for_the_size_of_its_pieces() { + let side = 400u32; + let cmyk_widths = |masked: bool| { + let mut d = Document::new_with_mode(400.0, 400.0, ColorMode::Cmyk); + let inks = Inks::new(side, side, flat([0u8, 102, 255, 0], (side * side) as usize)).unwrap(); + d.images.insert("img".into(), ImageBlob::cmyk_tiff(&inks).unwrap()); + let alpha = image::GrayImage::from_fn(side, side, |x, y| image::Luma([((x + y) % 256) as u8])); + d.images.insert("alpha".into(), ImageBlob::new("image/png", png(alpha))); + let image = |key: &str| { + NodeKind::Image(Box::new(ImageObject { + key: key.into(), + width: side, + height: side, + // 50 pt: smaller than the corners below. + xf: Affine::scale(0.125), + link: None, + placement: Default::default(), + pixels: None, + })) + }; + let q = [(0.0, 0.0), (150.0, 0.0), (125.0, 150.0), (25.0, 150.0)].map(|(x, y)| Point::new(x, y)); + let mut n = Node::new(d.alloc_id(), image("img")); + if masked { + let mut art = Node::new(d.alloc_id(), image("alpha")); + art.set_image_corners(q).unwrap(); + n = n.with_mask(Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)))); + } + n.set_image_corners(q).unwrap(); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let s = json!({"compression": {"color": {"downsample": "bicubic", "ppi": 72.0, "abovePpi": 100.0}}}); + let out = export_with_report(&d, &opts(s)).unwrap(); + let w = written(&out.bytes); + assert_eq!(w.iter().filter(|w| w.space == "DeviceCMYK" && w.smask).count(), usize::from(masked), "{w:?}"); + w.iter().filter(|w| w.space == "DeviceCMYK").map(|w| w.width).collect::>() + }; + let plain = cmyk_widths(false); + assert_eq!(plain.len(), 1, "one image for every piece: {plain:?}"); + assert!(plain[0] > 100 && plain[0] < side, "resampled for the pieces, not for the transform's 50 pt: {plain:?}"); + assert_eq!(cmyk_widths(true), plain); +} + /// A grey mask image with a color mask masks the CMYK image with the pixels it shows: its hidden /// pixels are clear in the image's `/SMask`. #[test] From d4cd3f2c485f79c02c43d1a87cf21dba7e970302 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:52:46 -0800 Subject: [PATCH 036/178] Tests: the missing-font question's tests check the open question and the clicked caret An answer that names another question, Cancel or OK, now has to leave the open question answerable: the right token's OK still starts the edit at the clicked character. The canvas double-click lands a quarter of the way into the text, and after OK the caret has to be the one a click at that point puts in the type being edited. --- crates/tools/src/text/tests.rs | 13 ++++++++++++- crates/ui-egui/src/canvas/tests.rs | 7 ++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index 7ee90ee1c8..249bf9d412 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -2273,7 +2273,8 @@ fn the_answer_to_the_missing_font_question_passes_the_option_check() { } /// Cancel starts no edit, and the edit in progress on other type goes on; an answer that names -/// another question, or one given to a document changed since, starts nothing either. +/// another question, or one given to a document changed since, starts nothing either. An answer +/// naming another question leaves the open question as it was. #[test] fn cancel_or_a_stale_answer_starts_no_edit_in_missing_fonts() { let (mut d, first, mut tool) = editing("First"); @@ -2296,6 +2297,16 @@ fn cancel_or_a_stale_answer_starts_no_edit_in_missing_fonts() { assert!(tool.poll(&changed, false).is_empty()); assert_eq!(tool.editing, Some(first)); assert!(!tool.waiting()); + // An answer naming another question leaves the open one answerable: its OK still starts the edit. + let (token, _) = asked(&click(&mut tool, &c, at.x, at.y)); + tool.set_option("missingFontEdit", &json!({"token": token + 1, "ok": false})); + tool.set_option("missingFontEdit", &json!({"token": token + 1, "ok": true})); + assert!(!tool.waiting(), "another question's answer"); + tool.set_option("missingFontEdit", &json!({"token": token, "ok": true})); + assert!(tool.waiting()); + let acts = tool.poll(&c, false); + assert!(acts.contains(&Action::Exec("select.set".into(), json!({"ids": [other.0]}))), "{acts:?}"); + assert_eq!((tool.editing, tool.caret), (Some(other), 2)); } /// Every new edit of such type asks again, after an earlier OK too, and a style the family lacks diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..52d455d0d6 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -9471,7 +9471,8 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); let node = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); let b = node(&app).geometric_bounds().unwrap(); - let at = xf.to_screen(b.center()); + // A quarter of the way in, away from the middle of the text. + let at = xf.to_screen(Point::new(b.x0 + b.width() * 0.25, b.center().y)); let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; let double_click = |app: &mut VectorcraftApp, time: f64| { timed(app, time, vec![egui::Event::PointerMoved(at), button(true), button(false), button(true), button(false)]); @@ -9502,6 +9503,10 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { assert_eq!(o["editing"], json!(id)); let caret = o["caret"].as_u64().unwrap(); assert!((1..11).contains(&caret), "caret {caret}"); + // The caret is the one a click at that point puts in the type being edited. + timed(&mut app, 5.0, vec![button(true), button(false)]); + timed(&mut app, 5.1, vec![]); + assert_eq!(app.session.tool_options()["caret"], json!(caret), "the caret where the type was double-clicked"); app.session.tool_text("X", app.view_info()).unwrap(); let NodeKind::Text(t) = &node(&app).kind else { panic!("not text") }; assert_eq!(t.plain_text().find('X'), Some(caret as usize), "{}", t.plain_text()); From 153f6c07500de9d1f875645b6a6809e880d869e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:23:01 -0800 Subject: [PATCH 037/178] 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 038/178] 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 039/178] 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 fd27b2e6d4309daecc5ac222f8b28928213aa819 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:40:58 -0800 Subject: [PATCH 040/178] Command Palette: docs rank typo results that match a word by description last A result matched through a typo that also matches another query word only through its description ranks after every other result, since the ranking compares that before the whole-query match and the label-before-path rule. Two typo words split between label and menu path tie with the reverse split only when the other words get the same grades in both results. --- 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 f8a3dc84a0..8223cfd204 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1590,7 +1590,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A modal window that opens without a press in the window (a dialog opened from the macOS menu bar or by an automation command, the About window, a file dialog, the update prompt, or the progress window of a plug-in, trace or open run) closes the Command Palette, a tool group's flyout, the All Tools drawer and any open menu or popup in the pass it opens. While such a window is open, the palette stays closed, so opening it from the macOS menu bar or by an automation command does not take the keyboard from the window; it opens again once the window closes (`palette` tests `a_dialog_opened_from_the_system_menu_closes_the_palette`, `the_about_window_closes_the_palette`, `a_progress_window_closes_the_palette`, `the_palette_opened_over_a_dialog_closes`, `a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens`, `a_dialog_opened_without_a_press_closes_a_flyout`, `a_dialog_opened_without_a_press_closes_the_tools_drawer`, `a_dialog_opened_without_a_press_closes_a_menu`, `the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`). - A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them, how the whole query matches is judged with the misspelled word replaced by the word it meets. Results that match it equally then come in this order: a result whose label holds every word matched through a typo before one whose menu path holds such a word, then by the grades of the other words and how many such words the menu path holds, and after that as every other result is ordered, so two such results can come in a different order than the words spelled right give them. With two words matched through typos, a result whose label holds one and whose menu path holds the other ties on these grades with a result that holds them the other way round. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). + A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result that matches a query word only through its description; a result matched through a typo that also matches another query word only through its description comes after every other result. Within each of these groups, how the whole query matches a result matched through a typo is judged with the misspelled word replaced by the word it meets. Results matched through a typo in the same group that match it equally then come in this order: a result whose label holds every word matched through a typo before one whose menu path holds such a word, then by the grades of the other words and how many such words the menu path holds, and after that as every other result is ordered, so two such results can come in a different order than the words spelled right give them. With two words matched through typos, a result whose label holds one and whose menu path holds the other ties on these grades with a result that holds them the other way around, when the other words get the same grades in both results. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`). The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do and have the same use grade (described below), the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool unless the Rectangle Tool has the higher use grade, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades, the matches through a typo, a description or a word with the same meaning, and the use grade, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. A pick is counted only when Recent Commands records it, so a refused pick and a pick of Search Commands… are not counted. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes, of the half of the commands picked longest ago, the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `new_commands_build_up_counts_when_every_counted_one_has_more_picks`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`, `only_a_pick_recorded_in_recent_commands_is_counted`). From 63fe462a1d77c90f6bf36a3a0e95426b0dd097dd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:41:24 -0800 Subject: [PATCH 041/178] Docs: a clipping mask that matches the old file's clipping path is relinked as the file's The PSD clipping-path entry in docs/target-app-parity.md said that links.update and links.relink keep every clipping mask made in the document. placed_clip_to in crates/engine/src/cmd/links.rs treats a clip group holding just the image as the old file's when same_path finds its clipping path equal to the old file's (anchors and handles within a thousandth of a point) and the fill rule matches, whoever made it. Such a mask takes the new file's clipping path, or becomes a plain group when the new file names none. The entry and the matching DCS sentence in docs/mcp.md now say so. --- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..a44f0aada7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9023,7 +9023,7 @@ file's composite is drawn through clips the image (a clipping group, its path un clipping path kept as the same area), and `file.place` answers the image's id as `image`, since the Links commands take the image and not the group. `links.update` and `links.relink` clip the image by the file's clipping path again (a plain group holding just the image becomes its clipping group, a new clipping group holds it when no group does, and it goes inside a clipping mask made in the -document, whose path is kept), the same way for the images in symbols, graph designs, patterns and opacity masks. When Placement Options also clip the image, the file's clipping group goes inside a clipping group of the placement's clip (the clipping group holding just the file's one, or a clipping group holding just the image that is not the file's, takes that clip, else a new one does), and a later update or relink changes the same two groups; when the new file has no +document, whose path is kept unless it matches the old file's clipping path and fill rule, when it takes the new file's path), the same way for the images in symbols, graph designs, patterns and opacity masks. When Placement Options also clip the image, the file's clipping group goes inside a clipping group of the placement's clip (the clipping group holding just the file's one, or a clipping group holding just the image that is not the file's, takes that clip, else a new one does), and a later update or relink changes the same two groups; when the new file has no clipping path, a clipping group holding just the image whose path is the old file's clipping path loses that path and stays as a plain group of the image, with its id, name, visibility and transparency (one whose path was given the even-odd fill rule stays as it is). The link shows as modified when a plate file of its own changes diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..330330957f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2325,7 +2325,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. A clipping mask made in the document whose clipping path matches the old file's clipping path (the same subpaths, each open or closed alike, every anchor and handle within a thousandth of a point, and the same fill rule) is taken for the old file's clip group: its clipping path becomes the one the new file names, or it is left as a plain group when the new file names none. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). From 011b6fb0e7e7e6bbe08f80ef4a2397109dd54993 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:56:06 -0800 Subject: [PATCH 042/178] Docs: limit the matching-mask rule to a single path holding just the image The relink rule for a clipping mask whose path matches the old file's clipping path applies only when the mask holds just the image and its clipping path is a single path. A mask that also holds other objects, or whose clipping path is a compound path or text, is kept, with the new file's clip group inside it. The kept-mask sentence now excludes the matching masks. Update Links and Relink keep a distorted image's corners and draw the new file's clipping path through them; the PSD clipping-path entry said that Update Links left that clipping as it was. --- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index a44f0aada7..1ebbf85d45 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9023,7 +9023,7 @@ file's composite is drawn through clips the image (a clipping group, its path un clipping path kept as the same area), and `file.place` answers the image's id as `image`, since the Links commands take the image and not the group. `links.update` and `links.relink` clip the image by the file's clipping path again (a plain group holding just the image becomes its clipping group, a new clipping group holds it when no group does, and it goes inside a clipping mask made in the -document, whose path is kept unless it matches the old file's clipping path and fill rule, when it takes the new file's path), the same way for the images in symbols, graph designs, patterns and opacity masks. When Placement Options also clip the image, the file's clipping group goes inside a clipping group of the placement's clip (the clipping group holding just the file's one, or a clipping group holding just the image that is not the file's, takes that clip, else a new one does), and a later update or relink changes the same two groups; when the new file has no +document, whose path is kept unless the mask holds just the image and its clipping path is a single path, not a compound path or text, that matches the old file's clipping path and fill rule, when it takes the new file's path), the same way for the images in symbols, graph designs, patterns and opacity masks. When Placement Options also clip the image, the file's clipping group goes inside a clipping group of the placement's clip (the clipping group holding just the file's one, or a clipping group holding just the image that is not the file's, takes that clip, else a new one does), and a later update or relink changes the same two groups; when the new file has no clipping path, a clipping group holding just the image whose path is the old file's clipping path loses that path and stays as a plain group of the image, with its id, name, visibility and transparency (one whose path was given the even-odd fill rule stays as it is). The link shows as modified when a plate file of its own changes diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 330330957f..d6acb9a509 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2325,7 +2325,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. A clipping mask made in the document whose clipping path matches the old file's clipping path (the same subpaths, each open or closed alike, every anchor and handle within a thousandth of a point, and the same fill rule) is taken for the old file's clip group: its clipping path becomes the one the new file names, or it is left as a plain group when the new file names none. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; for a distorted image, they keep its corners and draw the new file's clipping path through them. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document that is not taken for the old file's clip group (as the next sentence describes) are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. A clipping mask made in the document that holds just the image, and whose clipping path is a single path (not a compound path or text) that matches the old file's clipping path (the same subpaths, each open or closed alike, every anchor and handle within a thousandth of a point, and the same fill rule) is taken for the old file's clip group: its clipping path becomes the one the new file names, or it is left as a plain group when the new file names none. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). From cd4ac68c09bc3e55439e6b777e26d6015bcaae54 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:05:34 -0800 Subject: [PATCH 043/178] 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 b919dbd66f7a70dd0b56c5dca81d37d83ea32963 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:41:45 -0800 Subject: [PATCH 044/178] Plug-ins: read the manifest from a custom section before running any code A module may carry its manifest in a `vc_manifest` custom section, with `"abi": 1` in place of the `vc_abi_version` export. When it does, Plugin::load parses the manifest from the section and does not instantiate the module: its start function, data segments, `vc_abi_version` and `vc_manifest` do not run when it is inspected, installed or loaded at startup. The host checks the imports against the manifest's permissions, the exports `memory`, `vc_alloc` and `vc_run` by type, and the initial memory and the tables against the limits a run has (at most 4 tables of 100,000 elements). A module with more than one such section is refused, and so is a section over 64 KiB, before its contents are decoded, and a manifest in the section without `"abi": 1`. The host uses the section and does not call a `vc_manifest` export. Modules without the section load as before. The Desaturate example carries the section and keeps the export, and its fixture is rebuilt with Rust 1.100.0. build.sh clears RUSTFLAGS: .cargo/config.toml sets `+simd128` for wasm32, and the host refuses SIMD instructions. wat::sectioned builds test plug-ins with the section. --- crates/engine/src/tests/plugins.rs | 17 ++ crates/engine/tests/plugin_fuzz.rs | 12 +- crates/plugins/example/build.sh | 4 +- crates/plugins/example/src/lib.rs | 20 +++ crates/plugins/src/manifest.rs | 6 +- crates/plugins/src/runtime.rs | 160 +++++++++++++++--- crates/plugins/src/wat.rs | 51 +++++- crates/plugins/tests/abi.rs | 126 ++++++++++++++ crates/plugins/tests/fixtures/desaturate.wasm | Bin 60341 -> 63851 bytes 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/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/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + docs/plugins.md | 33 +++- docs/target-app-parity.md | 1 + 36 files changed, 539 insertions(+), 41 deletions(-) diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..2c6026c85d 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2017,6 +2017,23 @@ fn a_heavy_filter_installs_once_the_user_agrees() { assert!(install(&mut s, DESATURATE).get("budget").is_none()); } +/// A module that carries its manifest in a `vc_manifest` custom section is inspected and installed +/// without any of its code running: its start function traps and its `vc_manifest` export loops. +#[test] +fn a_plugin_with_a_manifest_section_installs_without_running() { + let mut s = session(); + let id = "test.engine.section"; + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","abi":1}}"#); + let extra = r#"(func (export "vc_manifest") (result i64) (loop $l (br $l)) (i64.const 0)) (func $trap unreachable) (start $trap)"#; + let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::sectioned(&manifest, tpl::ECHO, extra, 1)).unwrap()); + let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": data})); + assert_eq!(inspected["id"], id); + assert!(vectorcraft_plugins::registry::get(id).is_none(), "inspecting installs nothing"); + assert_eq!(run(&mut s, "plugin.install", json!({"dataBase64": data}))["id"], id); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + run(&mut s, "plugin.remove", json!({"id": id})); +} + #[test] fn invalid_install_flags_are_refused() { let mut s = session(); diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 20546835c1..d0b99e3efe 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -1,6 +1,6 @@ -//! Untrusted plug-ins never crash the app: mutated and garbage modules handed to `plugin.install`, -//! and plug-ins returning hostile output (random JSON in the object model's shape: huge or -//! malformed coordinates, unknown ids, broken paints and gradients, junk of every type) as object +//! Untrusted plug-ins never crash the app: mutated and garbage modules, and modules whose +//! `vc_manifest` custom section holds garbage, handed to `plugin.install`, and plug-ins returning +//! hostile output (random JSON in the object model's shape: huge or malformed coordinates, unknown ids, broken paints and gradients, junk of every type) as object //! filters (`plugin.run`) or live effects (`effect.apply`), and plug-ins running bulk memory //! instructions (`memory.fill`, `memory.copy`, `memory.init`, `data.drop`) on ranges in, at and past //! the ends of memory and the data segment, under small and default budgets. Each run must end as @@ -620,7 +620,11 @@ proptest! { } let mut s = rich_session(); s.execute("select.all", &json!({})).unwrap(); - for module in [bytes, [b"\0asm\x01\0\0\0".as_slice(), &garbage].concat(), garbage.clone()] { + // A module whose `vc_manifest` custom section holds the garbage. + let section = tpl::custom_section(vectorcraft_plugins::manifest::MANIFEST_SECTION, &garbage); + let sectioned = tpl::with_field(&tpl::module(&tpl::manifest("fuzz.section", "filter", "{}"), tpl::ECHO, "", 1), §ion).unwrap(); + let sectioned = wat::parse_str(sectioned).unwrap(); + for module in [bytes, [b"\0asm\x01\0\0\0".as_slice(), &garbage].concat(), garbage.clone(), sectioned] { let r = catch_quiet(|| { if let Ok(info) = install(&mut s, &module) { let _ = s.execute("plugin.run", &json!({"id": info["id"]})); diff --git a/crates/plugins/example/build.sh b/crates/plugins/example/build.sh index 1bedbc2fb0..614f683613 100644 --- a/crates/plugins/example/build.sh +++ b/crates/plugins/example/build.sh @@ -3,7 +3,9 @@ # Needs the wasm32-unknown-unknown target: `rustup target add wasm32-unknown-unknown`. set -eu cd "$(dirname "$0")" -cargo build --release --target wasm32-unknown-unknown +# An empty RUSTFLAGS replaces the `+simd128` flag that the repository's .cargo/config.toml sets for +# the web build: the plug-in host does not accept SIMD instructions. +RUSTFLAGS= cargo build --release --target wasm32-unknown-unknown out=target/wasm32-unknown-unknown/release/vectorcraft_plugin_desaturate.wasm cp "$out" ../tests/fixtures/desaturate.wasm echo "built $out ($(wc -c < "$out") bytes) -> crates/plugins/tests/fixtures/desaturate.wasm" diff --git a/crates/plugins/example/src/lib.rs b/crates/plugins/example/src/lib.rs index a1b08d8696..d5451860c5 100644 --- a/crates/plugins/example/src/lib.rs +++ b/crates/plugins/example/src/lib.rs @@ -12,6 +12,7 @@ const MANIFEST: &str = r#"{ "name": "Desaturate", "version": "1.0.0", "kind": "filter", + "abi": 1, "author": "VectorCraft contributors", "description": "Moves the colours of the selected paths towards grey; an example of the plug-in ABI.", "params": { @@ -19,6 +20,25 @@ const MANIFEST: &str = r#"{ } }"#; +/// The manifest in the `vc_manifest` custom section, where the host reads it, with its `abi` +/// version, without running any of the module's code. The `vc_manifest` export below returns the +/// same text for hosts that read only the export. +#[used] +#[unsafe(link_section = "vc_manifest")] +static MANIFEST_SECTION: [u8; MANIFEST.len()] = section_bytes(); + +/// `MANIFEST` as a byte array, which `link_section` needs. +const fn section_bytes() -> [u8; N] { + let text = MANIFEST.as_bytes(); + let mut out = [0; N]; + let mut i = 0; + while i < N { + out[i] = text[i]; + i += 1; + } + out +} + #[unsafe(no_mangle)] pub extern "C" fn vc_abi_version() -> u32 { 1 diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..899cdb9152 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -10,6 +10,9 @@ use crate::{Error, Result}; /// Longest manifest the host reads. pub const MAX_MANIFEST_BYTES: usize = 64 * 1024; +/// The name of the custom section a module may carry its manifest in, so the host reads it +/// without running any of the module's code. +pub const MANIFEST_SECTION: &str = "vc_manifest"; /// Most parameters a plug-in may declare. pub const MAX_PARAMS: usize = 256; /// Most parameters outside groups (`group`): a dialog of more is sorted into sections. @@ -299,7 +302,8 @@ impl ParamSpec { } } -/// The manifest a plug-in returns from `vc_manifest` (UTF-8 JSON). +/// The manifest a plug-in carries in its [`MANIFEST_SECTION`] custom section or returns from +/// `vc_manifest` (UTF-8 JSON). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Manifest { diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 1a25e9e6b0..853fe5def0 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -1,13 +1,13 @@ //! The wasmi host: loading, instantiating and calling a plug-in under resource limits. use wasmi::{ - Config, CustomFuelCosts, EnforcedLimits, Engine, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, Val, - WasmParams, WasmResults, + Config, CustomFuelCosts, EnforcedLimits, Engine, ExternType, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, + Val, ValType, WasmParams, WasmResults, }; use wasmparser::{Validator, WasmFeatures}; use crate::host::{self, Bridge, Deadline, Host, Report, Run}; -use crate::manifest::{MAX_MANIFEST_BYTES, Manifest}; +use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest}; use crate::permissions::Permission; use crate::{Error, Kind, Result}; @@ -198,10 +198,96 @@ fn wasm_err(e: wasmi::Error) -> Error { /// `vc_run(input_ptr, input_len, params_ptr, params_len) -> len << 32 | ptr` (negative: error). type RunArgs = (i32, i32, i32, i32); +/// The manifest in the module's [`MANIFEST_SECTION`] custom section, or `None` when it has none. +/// A module with more than one is refused, and so is a section longer than [`MAX_MANIFEST_BYTES`], +/// which [`Manifest::parse`] checks before it decodes the bytes. The manifest in the section must +/// give the ABI version as `abi`, in place of the `vc_abi_version` export. +fn section_manifest(module: &Module) -> Result> { + let mut sections = module.custom_sections().filter(|s| s.name() == MANIFEST_SECTION); + let Some(section) = sections.next() else { + return Ok(None); + }; + if sections.next().is_some() { + return Err(Error::Manifest(format!("the module has more than one `{MANIFEST_SECTION}` custom section"))); + } + let manifest = Manifest::parse(section.data())?; + // `Manifest::parse` has checked that the section is UTF-8 JSON of at most `MAX_MANIFEST_BYTES`. + let abi = serde_json::from_slice::(section.data()).ok().and_then(|v| v.get("abi").and_then(serde_json::Value::as_i64)); + if abi != Some(i64::from(ABI_VERSION)) { + return Err(Error::Abi(format!( + "the manifest in the `{MANIFEST_SECTION}` custom section must give `abi` as {ABI_VERSION}, the ABI version this host implements" + ))); + } + Ok(Some(manifest)) +} + +/// Most tables a module may define: the store an instance runs in holds no more. +const MAX_TABLES: u64 = 4; +/// Most elements a table may hold: the store an instance runs in holds no more. +const MAX_TABLE_ELEMENTS: u64 = 100_000; + +/// The number of tables the module in `bytes` defines and the largest initial size among them, +/// from its table section, or `None` when its sections can't be read. `bytes` is a module +/// [`check_features`] has validated. +fn table_sizes(bytes: &[u8]) -> Option<(u64, u64)> { + for payload in wasmparser::Parser::new(0).parse_all(bytes) { + if let wasmparser::Payload::TableSection(reader) = payload.ok()? { + let count = u64::from(reader.count()); + let mut largest = 0; + for table in reader { + largest = largest.max(table.ok()?.ty.initial); + } + return Some((count, largest)); + } + } + Some((0, 0)) +} + +/// Checks the tables the module in `bytes` defines against the store's limits ([`MAX_TABLES`] +/// tables of at most [`MAX_TABLE_ELEMENTS`] elements), which instantiating it checks. The host +/// offers no tables to import, so the module defines every table it has. +fn check_tables(bytes: &[u8]) -> Result<()> { + let Some((count, largest)) = table_sizes(bytes) else { + return Err(Error::Module("the module's table section could not be read".into())); + }; + if count > MAX_TABLES || largest > MAX_TABLE_ELEMENTS { + return Err(Error::Limit(format!( + "table budget (the module defines {count} tables, the largest with {largest} elements; limit {MAX_TABLES} tables of {MAX_TABLE_ELEMENTS} elements)" + ))); + } + Ok(()) +} + +/// Checks the exports a run needs without instantiating `module`: its memory as `memory`, whose +/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types. +fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> { + use ValType::{I32, I64}; + let export = |name: &str| module.exports().find(|e| e.name() == name).map(|e| e.ty().clone()); + let Some(ExternType::Memory(memory)) = export("memory") else { + return Err(Error::Abi("the module must export its linear memory as `memory`".into())); + }; + // Pages are 64 KiB: the engine's configuration leaves custom page sizes off. + let initial = memory.minimum().saturating_mul(1 << 16); + if initial > max_memory_bytes as u64 { + return Err(Error::Limit(format!("memory budget (the module's initial memory is {initial} bytes, limit {max_memory_bytes})"))); + } + let wanted: [(&str, &[ValType], &[ValType], &str); 2] = + [("vc_alloc", &[I32], &[I32], "(param i32) (result i32)"), ("vc_run", &[I32, I32, I32, I32], &[I64], "(param i32 i32 i32 i32) (result i64)")]; + for (name, params, results, signature) in wanted { + if !matches!(export(name), Some(ExternType::Func(f)) if f.params() == params && f.results() == results) { + return Err(Error::Abi(format!("the module must export `{name}` with the type {signature}"))); + } + } + Ok(()) +} + impl Plugin { - /// Validates and loads a module: checks the ABI version, the exports and reads the manifest, and - /// checks that each host import it asks for is one the host offers ([`crate::host::IMPORTS`]) - /// and its manifest allows. In Safe Mode nothing is loaded ([`Error::SafeMode`]). + /// Validates and loads a module: reads the manifest, checks that each host import it asks for + /// is one the host offers ([`crate::host::IMPORTS`]) and its manifest allows, and checks the + /// exports. A module that carries its manifest in a [`MANIFEST_SECTION`] custom section is + /// checked without being instantiated, so none of its code runs; one without that section is + /// instantiated to call `vc_abi_version` and `vc_manifest`. In Safe Mode nothing is loaded + /// ([`Error::SafeMode`]). pub fn load(bytes: &[u8], limits: Limits) -> Result { crate::safe_mode::check()?; if bytes.len() > limits.max_module_bytes { @@ -222,22 +308,31 @@ impl Plugin { let imports = host::check_imports(&module)?; let hash = crate::permissions::sha256_hex(bytes); let mut p = Plugin { manifest: Manifest::placeholder(), engine, module, limits, size: bytes.len(), hash, source: None, serial: 0 }; - let deadline = Deadline::new(p.limits.wall_time_ms); - // The manifest isn't read yet: every host import is linked, what it reports is dropped and - // there is no storage to reach. - let mut live = p.instantiate(Run::new("", false, false, deadline), &crate::permissions::ALL, &mut Report::default())?; - let version: TypedFunc<(), i32> = live.func("vc_abi_version")?; - let v = p.call(&mut live, &version, (), p.limits.fuel_base, &deadline)?; - if v != ABI_VERSION { - return Err(Error::Abi(format!("vc_abi_version returned {v}; this host implements version {ABI_VERSION}"))); - } - let manifest: TypedFunc<(), i64> = live.func("vc_manifest")?; - let packed = p.call(&mut live, &manifest, (), p.limits.fuel_base, &deadline)?; - let text = live.read_packed(packed, "vc_manifest", MAX_MANIFEST_BYTES).map_err(|e| match e { - Error::Limit(_) => Error::Manifest(format!("manifest is too long (limit {MAX_MANIFEST_BYTES} bytes)")), - e => e, - })?; - p.manifest = Manifest::parse(&text)?; + let live = match section_manifest(&p.module)? { + Some(manifest) => { + p.manifest = manifest; + None + } + None => { + let deadline = Deadline::new(p.limits.wall_time_ms); + // The manifest isn't read yet: every host import is linked, what it reports is + // dropped and there is no storage to reach. + let mut live = p.instantiate(Run::new("", false, false, deadline), &crate::permissions::ALL, &mut Report::default())?; + let version: TypedFunc<(), i32> = live.func("vc_abi_version")?; + let v = p.call(&mut live, &version, (), p.limits.fuel_base, &deadline)?; + if v != ABI_VERSION { + return Err(Error::Abi(format!("vc_abi_version returned {v}; this host implements version {ABI_VERSION}"))); + } + let manifest: TypedFunc<(), i64> = live.func("vc_manifest")?; + let packed = p.call(&mut live, &manifest, (), p.limits.fuel_base, &deadline)?; + let text = live.read_packed(packed, "vc_manifest", MAX_MANIFEST_BYTES).map_err(|e| match e { + Error::Limit(_) => Error::Manifest(format!("manifest is too long (limit {MAX_MANIFEST_BYTES} bytes)")), + e => e, + })?; + p.manifest = Manifest::parse(&text)?; + Some(live) + } + }; host::check_granted(&p.manifest, &imports)?; // A heavy filter's runs get the larger budget the host allows for one, which the host // lets the user allow or refuse before installing it. @@ -246,8 +341,16 @@ impl Plugin { p.limits.wall_time_ms = p.limits.wall_time_ms.max(p.limits.heavy_wall_time_ms); } // The other exports must exist with the right types. - live.func::("vc_alloc")?; - live.func::("vc_run")?; + match live { + Some(live) => { + live.func::("vc_alloc")?; + live.func::("vc_run")?; + } + None => { + check_exports(&p.module, p.limits.max_memory_bytes)?; + check_tables(bytes)?; + } + } Ok(p) } @@ -294,8 +397,13 @@ impl Plugin { /// A new instance for `run`, with the host imports of the permissions `granted` linked. When the /// module's start function fails, what it reported through the host imports goes to `report`. fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result { - let limits = - StoreLimitsBuilder::new().memory_size(self.limits.max_memory_bytes).memories(1).tables(4).table_elements(100_000).instances(1).build(); + let limits = StoreLimitsBuilder::new() + .memory_size(self.limits.max_memory_bytes) + .memories(1) + .tables(MAX_TABLES as usize) + .table_elements(MAX_TABLE_ELEMENTS as usize) + .instances(1) + .build(); let mut store = Store::new(&self.engine, Host { limits, run }); store.limiter(|h| &mut h.limits); // The start function (if any) runs on one slice of fuel: it runs before `call` can check diff --git a/crates/plugins/src/wat.rs b/crates/plugins/src/wat.rs index 936d5d9e53..fbb93f6e51 100644 --- a/crates/plugins/src/wat.rs +++ b/crates/plugins/src/wat.rs @@ -7,12 +7,25 @@ const OUTPUT_AT: usize = 0x1_0000; /// `s` as the body of a WAT string literal (every byte that isn't a letter, digit or space /// escaped). pub fn string(s: &str) -> String { - s.bytes().map(|b| if b.is_ascii_alphanumeric() || b == b' ' { char::from(b).to_string() } else { format!("\\{b:02x}") }).collect() + bytes(s.as_bytes()) } +/// `data` as the body of a WAT string literal, every byte that isn't an ASCII letter, digit or +/// space escaped (so it may hold any bytes, UTF-8 or not). +pub fn bytes(data: &[u8]) -> String { + data.iter().map(|&b| if b.is_ascii_alphanumeric() || b == b' ' { char::from(b).to_string() } else { format!("\\{b:02x}") }).collect() +} + +/// `vc_alloc`, which grows memory by whole pages, so its blocks never overlap data segments. +const ALLOC: &str = r#"(func (export "vc_alloc") (param $n i32) (result i32) (local $old i32) + (local.set $old (memory.grow (i32.shr_u (i32.add (local.get $n) (i32.const 65535)) (i32.const 16)))) + (if (result i32) (i32.eq (local.get $old) (i32.const -1)) (then (i32.const 0)) (else (i32.mul (local.get $old) (i32.const 65536)))))"#; + /// A plug-in module: `manifest` (JSON), a `vc_run` whose body is `run` (parameters `$in $il $pp /// $pl`, result i64), extra module fields `extra` and `pages` of initial memory. `vc_alloc` grows -/// memory by whole pages, so its blocks never overlap data segments. +/// memory by whole pages, so its blocks never overlap data segments. The manifest comes from the +/// `vc_manifest` export, which the host calls when it loads the module ([`sectioned`] carries it in +/// a custom section instead). pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String { format!( r#"(module @@ -21,9 +34,7 @@ pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String { (data (i32.const 16) "{data}") (func (export "vc_abi_version") (result i32) (i32.const 1)) (func (export "vc_manifest") (result i64) (i64.or (i64.shl (i64.const {len}) (i64.const 32)) (i64.const 16))) - (func (export "vc_alloc") (param $n i32) (result i32) (local $old i32) - (local.set $old (memory.grow (i32.shr_u (i32.add (local.get $n) (i32.const 65535)) (i32.const 16)))) - (if (result i32) (i32.eq (local.get $old) (i32.const -1)) (then (i32.const 0)) (else (i32.mul (local.get $old) (i32.const 65536))))) + {ALLOC} (func (export "vc_run") (param $in i32) (param $il i32) (param $pp i32) (param $pl i32) (result i64) {run}))"#, data = string(manifest), @@ -31,6 +42,36 @@ pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String { ) } +/// A custom section named `name` holding `data`, as a module field. +pub fn custom_section(name: &str, data: &[u8]) -> String { + format!(r#"(@custom "{}" "{}")"#, string(name), bytes(data)) +} + +/// A plug-in module like [`module`] that carries `manifest` in its `vc_manifest` custom section +/// ([`crate::manifest::MANIFEST_SECTION`]) and exports only `memory`, `vc_alloc` and `vc_run`: the +/// host reads the manifest without running any of its code. The host loads it only when `manifest` +/// gives `"abi": 1`. +pub fn sectioned(manifest: &str, run: &str, extra: &str, pages: u32) -> String { + format!( + r#"(module + {section} + {extra} + (memory (export "memory") {pages}) + {ALLOC} + (func (export "vc_run") (param $in i32) (param $il i32) (param $pp i32) (param $pl i32) (result i64) + {run}))"#, + section = custom_section(crate::manifest::MANIFEST_SECTION, manifest.as_bytes()), + ) +} + +/// `module` (a module in WebAssembly text that starts with `(module`, after any white space) with +/// the module field `field` added first, such as a [`custom_section`]; `None` when `module` does not +/// start with `(module`. +pub fn with_field(module: &str, field: &str) -> Option { + let rest = module.trim_start().strip_prefix("(module")?; + Some(format!("(module\n {field}{rest}")) +} + /// A `vc_run` body returning the input unchanged. pub const ECHO: &str = "(i64.or (i64.shl (i64.extend_i32_u (local.get $il)) (i64.const 32)) (i64.extend_i32_u (local.get $in)))"; diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index ae99846c69..aa6c3ad2f0 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -6,6 +6,7 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; +use vectorcraft_plugins::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES}; use vectorcraft_plugins::storage::{Meter, Storage, StorageError}; use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; @@ -488,6 +489,131 @@ fn host_imports_are_checked_when_a_module_is_loaded() { assert_eq!(plain.run_reporting(INPUT.as_bytes(), b"{}", plain.limits()), (Ok(INPUT.as_bytes().to_vec()), Report::default())); } +/// A start function that traps: a load that instantiates the module fails with it. +const TRAPPING_START: &str = "(func $trap unreachable) (start $trap)"; + +/// [`MANIFEST`] with the ABI version, as a `vc_manifest` section must give it. +const SECTION: &str = r#"{"id":"test.plugin","name":"Test","version":"1","kind":"filter","abi":1}"#; + +/// `module` with a `vc_manifest` custom section holding `data`. +fn with_section(module: &str, data: &[u8]) -> String { + tpl::with_field(module, &tpl::custom_section(MANIFEST_SECTION, data)).expect("module text") +} + +/// Asserts that each case's module is refused with an error that contains its text, and lists every +/// case that is not. +fn assert_refused(cases: &[(&str, String, &str)]) { + let wrong: Vec = cases + .iter() + .filter_map(|(name, src, says)| match Plugin::load(&build(src), Limits::default()) { + Err(e) if e.to_string().contains(says) => None, + other => Some(format!("{name}: {other:?}")), + }) + .collect(); + assert!(wrong.is_empty(), "not refused as expected:\n{}", wrong.join("\n")); +} + +/// A module that carries its manifest in a `vc_manifest` custom section loads without any of its +/// code running: not its start function, not `vc_abi_version` and not `vc_manifest`. Its runs +/// instantiate it as before. +#[test] +fn a_manifest_section_is_read_without_running_the_module() { + let exports = r#"(func (export "vc_abi_version") (result i32) unreachable) + (func (export "vc_manifest") (result i64) (loop $l (br $l)) (i64.const 0))"#; + let p = Plugin::load(&build(&tpl::sectioned(SECTION, tpl::ECHO, &format!("{exports} {TRAPPING_START}"), 1)), Limits::default()).unwrap(); + assert_eq!(p.id(), "test.plugin"); + assert!(matches!(p.run(INPUT.as_bytes(), b"{}"), Err(Error::Trap(_))), "a run still runs the start function"); + let p = Plugin::load(&build(&tpl::sectioned(SECTION, tpl::ECHO, exports, 1)), Limits::default()).unwrap(); + assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); +} + +/// A module with the section needs neither `vc_abi_version` nor `vc_manifest`, and when it also +/// has a `vc_manifest` export that says otherwise, the section is the manifest. +#[test] +fn the_manifest_section_needs_no_manifest_export_and_wins_over_one() { + let p = Plugin::load(&build(&tpl::sectioned(SECTION, tpl::ECHO, "", 1)), Limits::default()).unwrap(); + assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); + let exported = r#"{"id":"test.exported","name":"Exported","version":"1","kind":"effect"}"#; + let p = Plugin::load(&build(&with_section(&tpl::module(exported, tpl::ECHO, "", 1), SECTION.as_bytes())), Limits::default()).unwrap(); + assert_eq!((p.id(), p.manifest().kind), ("test.plugin", Kind::Filter)); +} + +/// The section's manifest gives the ABI version as `abi`, which the host checks in place of the +/// `vc_abi_version` export: left out or another version, the module is refused, whatever its +/// export returns. +#[test] +fn a_manifest_section_must_give_the_abi_version() { + let says = "must give `abi` as 1"; + let version_1 = tpl::module(MANIFEST, tpl::ECHO, "", 1); + let version_2 = version_1.replace("(result i32) (i32.const 1)", "(result i32) (i32.const 2)"); + assert!(load_err(&build(&version_2)).contains("vc_abi_version returned 2")); + assert_refused(&[ + ("left out", with_section(&version_1, MANIFEST.as_bytes()), says), + ("2", with_section(&version_1, SECTION.replace(r#""abi":1"#, r#""abi":2"#).as_bytes()), says), + ("a string", with_section(&version_1, SECTION.replace(r#""abi":1"#, r#""abi":"1""#).as_bytes()), says), + ("a fraction", with_section(&version_1, SECTION.replace(r#""abi":1"#, r#""abi":1.5"#).as_bytes()), says), + ]); + // The section's version is the one the host checks. + let p = Plugin::load(&build(&with_section(&version_2, SECTION.as_bytes())), Limits::default()).unwrap(); + assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); +} + +/// A `vc_manifest` section that is repeated, too long, not UTF-8, not JSON or not a valid manifest +/// is refused, even when the module's `vc_manifest` export returns a valid one. +#[test] +fn hostile_manifest_sections_are_refused() { + let base = tpl::module(MANIFEST, tpl::ECHO, "", 1); + let with = |data: &[u8]| with_section(&base, data); + let long = format!(r#"{{"id":"test.long","name":"Long","kind":"filter","abi":1,"description":"{}"}}"#, " ".repeat(MAX_MANIFEST_BYTES)); + for (name, src, says) in [ + ("repeated", with_section(&with(SECTION.as_bytes()), SECTION.as_bytes()), "more than one"), + ("too long", with(long.as_bytes()), "(limit "), + ("not UTF-8", with(b"{\"id\":\"\xff\xfe\"}"), "not UTF-8"), + ("not JSON", with(br#"{"id":"test.plugin","#), "manifest"), + ("empty", with(b""), "manifest"), + ("a bad id", with(br#"{"id":"a b","name":"x","kind":"filter","abi":1}"#), "invalid id"), + ("an unknown kind", with(br#"{"id":"a","name":"x","kind":"panel","abi":1}"#), "manifest"), + ] { + match Plugin::load(&build(&src), Limits::default()) { + Err(Error::Manifest(e)) => assert!(e.contains(says), "{name}: {e}"), + other => panic!("{name}: {other:?}"), + } + } +} + +/// A module with the section has its imports checked against its manifest, its exports by type, +/// and its initial memory and tables against the limits its runs have, before any of its code runs +/// (its start function would trap). +#[test] +fn a_sectioned_module_s_imports_and_exports_are_checked_before_it_runs() { + let call = r#"(import "env" "vc_call" (func (param i32 i32 i32 i32) (result i32)))"#; + let level2 = LEVEL2.replace(r#""api":2"#, r#""api":2,"abi":1"#); + let e = load_err(&build(&tpl::sectioned(&level2, tpl::ECHO, &format!("{call} {TRAPPING_START}"), 1))); + assert!(e.contains("imports `env.vc_call`") && e.contains("the permission `commands`"), "{e}"); + let sectioned = tpl::sectioned(SECTION, tpl::ECHO, TRAPPING_START, 1); + let tables = |t: &str| tpl::sectioned(SECTION, tpl::ECHO, &format!("{t} {TRAPPING_START}"), 1); + assert_refused(&[ + ("no memory", sectioned.replace(r#"(memory (export "memory") 1)"#, "(memory 1)"), "export its linear memory as `memory`"), + ( + "initial memory past the cap", + tpl::sectioned(SECTION, tpl::ECHO, TRAPPING_START, 60_000), + "exceeded its memory budget (the module's initial memory", + ), + ("no vc_alloc", sectioned.replace(r#"(export "vc_alloc")"#, ""), "must export `vc_alloc` with the type (param i32) (result i32)"), + ( + "vc_run of another type", + tpl::sectioned(SECTION, "(i32.const 0)", TRAPPING_START, 1).replace("(param $pl i32) (result i64)", "(param $pl i32) (result i32)"), + "must export `vc_run` with the type (param i32 i32 i32 i32) (result i64)", + ), + ("five tables", tables(&"(table 0 funcref) ".repeat(5)), "exceeded its table budget (the module defines 5 tables"), + ("a table too large", tables("(table 1 funcref) (table 100001 200000 externref)"), "the largest with 100001 elements"), + ]); + // At the limits, it loads and runs. + let at_limits = tpl::sectioned(SECTION, tpl::ECHO, "(table 100000 funcref) (table 0 funcref) (table 0 externref) (table 2 3 funcref)", 1); + let p = Plugin::load(&build(&at_limits), Limits::default()).unwrap(); + assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); +} + /// Progress is clamped and passed on to the caller's sink as a share; the run's last report is kept. #[test] fn progress_reports_are_clamped_and_reach_the_caller() { diff --git a/crates/plugins/tests/fixtures/desaturate.wasm b/crates/plugins/tests/fixtures/desaturate.wasm index a8b4cdf0726ecffd2ce24d0e00768e44e4672d5d..730ec3554581ea4f7691a5fac5b5f9d5ea922d7c 100644 GIT binary patch literal 63851 zcmdqK3!Gn7dGEc~zWnbq^A8LVNPs>6rZ|y=1cfAAD%m4)m5TLpwCyPj$pD!Nxy(!= z)R+tqF>Pr}t*vO$qM{%|#g?8@i#2W0m$tO!wAR`dE48-uRBJh>dg?i%Ip5#2*8X26 zA!xPl`+iO)Gkfo~*X3EyZ9VH*&ssa0oV&qAQRF`CmR;@kMOVlB_PKpmC;RNeLqsYG zQAmugPI+bd_K2?zQq<_D0FCxsSLst0akw5`OrXRQPpqC8_W~sV22bHL18tz0piaB&ju& z)P|z8Iy_QMTzd)shTG(e(j?B(V~!n7D%GJVQkAibhK@Vl#ns_q=c=jw8y$7dolxPO zi(C>ftyH2)mQ||yH(YT^GOT8!YIQV81P>{dYLvtjAc21;#wVqj+u`y&1L!4{I;brc z77j+u>JMa<8>Vj9K6_If4e#D`)#No>uG&2{JGW)~w&=2&61HyLzA3uA$?Xl3+qPUg zH8&rr+c4k{QNiLkGON3+Z%7pqt#JV9C8;AMMX5y%%hcYH0IhjFDxuX zooFIjAGh)-ckAOcr=@jqlt;}=T)gl5$gmIdUy ziH|EWqW+>i9SXSS&0w^w>B(rOlY}=(5v_}t=1Cr}i$}T8ZaYtk1$S<=oGUL|c`~79 z+XfhE>2&+nvR&V!i-sbKMk|x{`ed!YtF2GQ{av&^$tiXIv@g2f7X|2Kb##6qY~;y! zym2gUxu(*7KxvN5$FGYov@-m8EShe=StZ9}b?gw}fgS;!@;0At-=>$8A6Ej{Xum}X zyn8YVNNE1m(zv=W*&ERLq?_r)0SR$&pPSBIy9-;q@jLs;d(`XsF8dAGoS3U*Q^a{VLal>o>U8xL!F;r*{^O zONZ)tTr}3j8*;}_Txc`j-#IYI^RvI_v;){mb)FWoGq$gbaPM~qprnc50?Oer5giCn0b^;n zb+cm`w;L?6;_pbS7J#0>g#GMYvg$=cjUIQVo>lL60-{qZJ`2}Hq$P#hiG0?IRTo2i z*UuhDsC1~+tFfkA>icXY0gsF04&%U7ND$BV3kMXllT=-yvER(O80PHj8vD;~s3S6p4{4 zk(lJ_2Z&fq##_~sq*w9rC=UeMaJICuen*C9_Y}|;z z_vFt|lZY9U9y3y0fNl^g3awpM+}M7nZ&t7GbDgxvG?L3v}kNX zxkH#*7tgmW1t|9Lg3COY?A&NaDEW{x4&%jE|9&&&&?*msVU;(Gr|W2$*Uv=4xKQy+ zB`Vb69W>~nhURhc1APwoh}m#k0jwA=Cc%60MGx~+PxBM2VXb7h?=o;+O{Gsau%+#+<=Hn&Kk z(Y}wgJ;7T{+E#>+894di;oaVW0NTiBG!X>ZYYf z2lP_BQD`0(uPdgePE_F$ zG+ffE=*76k6z4}IwY4%CpV;?9v;$Gb!%YbYDlnCtsUwRne zu0$UQHTwb*d1WV&k^XPruJS;O%6DTB#pO<8Z^<#@)IRG^+`(vXrYRK#!KRy}f5NAi zT=PkBjg6K^=Ngbpn}b{fNB5@zs+3_D4z-3NuL`v#x7w{ArH?YQCSI8zfqV1n%Z#xf z04E-&8W@Vh`KnYuS3(!qfv)Fh_w%_Rpc_C%#oGrZ-BBTd?C6z1c9c!zA$cycTjS+R z>PNs|rW$)R2fEdfD5t>;NyNN=E<+b$Q`F`lZGUGrfu+e#XsJ)dx4}NprDw3h@2Rvp z)r`k^pRB5~CtW$WxW&0_pAoo&K`54bCn+E`jnNb@vINSRH^R0a&Gc?~7KiDlG$ zX(U-NdC>fJICIX$iA_J5D0&U8$*v}5{0S2?rD!5)g4t|K7a~|_$^T+1eJPce(`9Mo zD9rDg$J>iypCuwIHp^=^R~$Ki*^04x^J-?mC8XmqQ*QnY$B`4gZT>9TFgOLs&zi~+ zc2`Gfkr>e|m(gc4L?Vqt%XVbQ|GUl5Y17M_zIhCX1 z`=*uLKIDrsg&B)9M3#7|6-xtNcHj>1s4n(Qs}D(W<4$b7w9p(e+1W{!} zcL9CWsTOzY5i~N>qfAqP38*hT(hn3SR?*su{Ex@Cqd1B?V$nC4gL=7i>$GQ(LZcXy zn7r&{71s#}qAL!OlG<4WKP)D|4UOa}y+X}@NnBD=Gw;_IngAPj4SGbRi(B1cvEAq6 z7z(MYqhYvFmccif_en!Vnx&iOMU%?G6c?kVE5}q<@Z{LQEtg68qY+w+;;Uo+iAo%t z9@)%jzlaJo1ezEgVxZ)_o>tY^9ll28=m*ou5hLM~&4=+(ED?NCh&>3U`^|*Ij5^Xg z%oeYMp@%agMpodFa%%jSmQF)|tnJWde~V+z*QkydO3Z{o|1L(|qHNS36$|E4iJNeU zjacfxhN*no%W3m8VM@GggNn2xD)hI6L73QiEtW^khg{EB2wx<=v`1sIkt$+&FyT6Y zvk7X{{-`RE_pT-HRlu|(EBClGR!8OrK(9*E#S%cd`&7Ih5GJv}kQP?L|*&v^iS7xY(f)jZQuVT))iKzXkFyb*pPuip=NM7ioY?X<9a$dmT z46eS%Lw))Dbb}#tAe#Z16|eBlz&eVaTKkK63?5#rANo#(VWEO)Qbh}2IsM?oA$RK- zt}x-DF8b2hYMyF{t#^CqaeOJ{M>9^$@Nkij>TzmK(@bSwAYx6S08gYDsWzj)(#5`OPP)irgak8 z&va$tf&&zg(5@|o_FtQEy=T|;IJ*RX@TyTjW{NRt+R4yuWd^981 zYTnePkvCUj+qNd&``Ce>({Ja^6NkR}jeq->&wc#R-aUD1;^~hc`j(!r+Owahrylw5 zpZ~;9z5Q37iu$wZ&AvC^I6 z)5EnYTEFJ%jfmX5c{gd9jQI-KGcFOdYqTm6m_@*}1WbVArvwMhj*5Ld?c1&Ubv-;4 zg(u_eHQ~X$CbjTj!)z-&nCqeu9&7|03J=gWF6!aIMuAaj_n%f2`;_|#2o(zz3;01i?2UOutJ{_7f>|PZ zr~OvLH#ou97#ZJy_xrd3Rew(&%DF>pt(nF)3)4h~f^*vGe_N&L{u*q+K6ZplBj5L4=va(1Zd7**t z(cd_TRx8y*YH44#w7(51gQ@rth+#I*kzSbEQO!>b)Z%M?Y9P&{&c=Wqwghk2Qrp?H z%$a8e3ycgJVcNf9%7aRntqb*d7Z^_P&1;g5vBB^!s{)$k%wEb%j-t!sXB*On3|2-i znIyqBe5K8fZ5oFQL-SXg^0q&z#;imT1Dhc;%rRL3vtbR!?t;ICG0%V_Cjl59!1Rjt9WICF2VZd0KdmsjK9Lyr3Pq64Y1e| zbw*@WaSwXb-pIXj964$>j1)}`0cmkN-5ln62iGdgg6eCl$n+9}*ihXn-Z(uR#|}Yg z6*mbhX|X>PW08ttm9aWdp`i|cm5tS#?VAlvHO+_Lny{b>&<8M}!S24fK%jWK)3mon zw@yQtN60GR1=>_rLe&xVlXM9m%b$qZMpC##^fvfA49>MBiv&h#7A@I*st{|#{0xi& z70h4&fkpCW`z->Gs?E>9%Nl71LR#H`V&=LsS-U=F?Z<96td9?d+l}kBNMwZAAFj9S z71U*k$%uVGS7^VWtJp{jji^SuyOFYMr}^`BmIPB&5+02G*0@@VA7<%+^(ni5l>58G z{bSs-=0v)d*laCwNCbug`N;bC)m)ewU1~S!o4XX`)`iD=#agd0C+ig9QFrX&h%p*Gihu zLae2V157Rbu$cil*$pC3&663_7a#s=R~6cyX7_V*XqsWdsumzT#8nIs99n zX38p_@0d@gB4?wK9Ae53nYa9akArwxD!ODi5f-ug4#mp^1s0K1o3|iufMwK$iAmnZ zA@CEW+w?@2Iq6Zt!|O-Mu8w3Rj< zU*gA*AnIC}giFDw=1EPEa2QyvmN3{Xn#JuO1-tEl!QuhKac~b8&zh-LK0TqF#oFRo zD^b$nE=$de+s(0DrrvHeJG*$y=u@VOW{X+`U#9Q!L3Jl@k!jKXaV(5o{Ue&jF$>{v zV=YSH51|Q@ak!WBv8_P^Qad%Oeyg?uob@uj)bYxSHTO zU8S7x+EJ}>G5CB1lm0r0b<@WFy0wu@urV({A>nS2+({wntyf4Tlm@TCWp`#gc1KXLw;xKj+Mu4nt9UZCHiaZzr`;R;@#B+VijWm-m)8#mIz zn)z#1N8C9xM@&vp^0nY7I+Alop!*7X4j)$BJZgh;M^t9qI6Y~%-z^cAzrw~5?}BUp zvL(u@lvM}aCA!?V&_-Gbx?AsM)3nB9%E-7WqfiFTN^gHcu&WUT#z%sbG%CH$6qm}% z4)jY1Um2YhBHqU1tJg&r__XsB`$pHuFdp9pOiWdRDQs2y^*{|7u{dp&zpUVbiMZ5b zM2-}p15xIZcG6|*80#$>NvqXNd|vL0DO>?@y0}9-7y1kveFoOCRlR~7cy|_0D=fCi z5E9D(iHozQ+wUnc-R`8eZjPjZ3y%a?+p9w#0_a&w-FjU&BIrk%9jGe^f&MIS|Aep5 z@FcDvSud`ZX&kzk+^f(n#ey0-my-=eZQW8x)`CR{bjh?JGKC1D{Z4eslY6}hEiUe# zWaOD&j9mw=(b7)W&H7^l z)5hM6+dD%-oTsfoEngQAB8`rXM`34>U{RhpK~_eYc;4<>dX@C1b(?$DGocR?IxvFk z26STZK4!cDSFunRW7Wf6VI@NMt@bAZYM8O`Xp*B~93Fdf_-A64XT^z1_!pqFg|TBbC;X;bp=7N~g9bikfTS+0Xq&-mNkIBVwxz5#zdTetIyf@-KN;v+ zAWT%0$*=cCfl3*&wgzkQowRIoVc_ogwOEV{<~>+xpv0lKI2yZ|c{ZW&kPiqM z6L7(q(G~RP%;@E}q6L$UENJZ!(_o$|2EeLXSa|0L{^`Si=Uzoch|WYb@y>FcjD^C7 z;11F;(K^}0?!9@s#~OvD(|h4*tOG1$MG&OajaZ6h4aGnrB=fJfAC}I5)Pp6L)fEzn z)zQnD%X(N0x-s*t`(7;k?q94~pee0xjojM4mwH6jjD&X>xUcE3%Vb0?t7E|vg78eJ z5{R=#6wRXy!qDKZohM_R~#O|G}I~xq)8ecMcuq$O11z}Q14Z+XMF_I z7PzGH+A_%EAD0x&E_ke>v0;f~3GNJ{FLo}Yw9FrTMDa#2l}#7N$#WyFr|*QhV877@ z>n9}U6;@j${Fir{3g}IWQ+IVLbMl2$iuz?NAW`Wz#&8BdqSa2MZkvw^}Y4)o1twPJxZLWUv zm}%14D^n!kC$G(PSeg?Cpy}GY>MM|d5n@d>9ydV;06f~!w?gz45$;{o2tNJ%qXcb?1RcgBU&innQ5NhjnQwoRe6gCO>w#Q{h>NpF#TGplMH#} zsi&xRTeUOsH7Gu`2nw=8Y}|9i$~2+-(ye2#3F8pO9T*h{ffZ}|!~IQ5#E#H*9R#}e z`_u|m^CYtv;SG6fGM4e}S@edmsOUXS__oMIU>lQhlMdi572=k1MXM) zf$O%{LpRWfXB0)%tNMY%u^~)&?6cyDGQy*xwo(QNZx1v0VGql)SW8Xb28SP_i#yzp z^M(v7e1_a-Sk4pgmV(t_Iy0oa$2ZM7WGB*+FdAUgb2X^isYSY@VO=$K#}JX+kYIr7 zPt7xuy*R?4(=AXubOfv&UN@}QC8>xex^HBOi!j!HC}21!BgQC6cLbhCzt+@4>vK2b zVnRUU6i+;Xbq_p+7U`}+A=^H#^P#6qtzcS8w9T(vWC zR!2V}^{VDjiHy0cBh$A^s65CJW8+u==Z-(NAd9&8Vh@&1^-7wu7O`ikq9dyhhx0-Q zN8H{w-HW~tZR6;hU*oKL>FbOIT%3Oao{HeiEICl>L&#UBw(oE2|=@3C7Yc#tbm%W^zbiiL$6G2M32_P)9HgJytumlQrXRt50Y zXmdbP{K8-VkLp(YJ6*JQLmg_YPCs~C`&U94d9YNbI&to8R&1hjV1I{Mz(k{K+L%Y* z(H)RG^WcF_JmC&>YHu3I16vT`@mjppF0Z{>+u5j=#hsN&PHo?kjiP_ip4`3q!9BM5 zKp`w_@6(?)c?c%yy}~xg8$>uUd;(Bje{heViihq$SI^Bu`|b5y&93d#2D%*&bO}{! z{k5J=xLfyhz=3rVg_FmxRVQnLt|I8L5vZ}IKg?4mv@OE^?c0-A)nkg5Ne81>(lZ%O zM1i-spsX25a~!LZaJ0IdLfJ5?Z4^X z86tY*^CPO-6(2NBo(8)hcs8295fgRa3wST5Us3VP{fa-?$Do%c5&@9h$!y+hE8{{M z`tTk=G<#~G80@c+K(qK-Ii1mt-L6n(2&K93Q)^vYcXtzv0f4Zm zc;sl>PKeIA5x!IcR@4F2M~0yIrMS*_3P-2w|65(RG1a^d3Ks~Nk$Vfx3w&Mkk9`VV zf_$VO!`MMWl|{h2;@wAlbydF`rx(Qrtjv|!V=fy)xV}XYX|BwSQDAGrto`YFYS~k} z_}>fQf@eAE+E1!L)Z9#$daMveF_exREEa9>m~|CHq$b~|ERx`0p^JkK7CrhoKA?e* zF3Fo))QK{VuosvSZ=^!wC1!>XsU7)VE{wuIKP6(sZhypJAYif9eW?JBhi%E_^wA}p)O+z+@N!om?t`Am8=kx10G?7j?R82^NMkkBJ^kEQ>Lmh#bpHtRqo zu#%aQUtV}E@A2DR!nc%}yuOV6ztLrwF^iV)HI>050@DxdS|GJtm$yv|Mb!L}Skaaf z_=#vrPWD23UW6n=6h=(fhpt$Wk76Up-OcT9nzfV5Ij#sxXsp0aXPf@>7#-34gGSug zmzE^ZNd|$`-Rhb7MU2wDogG>mkuhUa4RFcC28$J=?^iuFWVG|zOnC`MSyKSlo5xlh z*X(1)+*zQq2{pzEh8jJDQlUDYhqYGwxq>p`T+C5|7Bl_2fiPBM*!Yl z4*+jf3;=J<^nh<&_~Kb;?w;3UTM&_}Bja0LNw;w*&Rk+(K|I;*P=A!kV-v%AuE)G{RO(morNuf;kY;h!#8KLO@@WM}u4YU)8FXg3IBuxvke8mPNLL3=1d^ z?}g927ao12c5uDO&d7>emB)PYEUN}9BkS|jXEHq6#XD|2sH$j-<xr=--Fa08OGyrTj``woOc-VaK8Jn zHKmNQE~25*N6di{3oc}>M+H}u3xC?;Riv|ihwsE*jh?Q%(8X?up z=4SG2wothKjl^2(g2U%%^+0e=OJP5OENu3*I1N}p0BtS-G;2dfb|)@w)W$fb?`1=k z#SPhVS4I!Cw3(5g(W(dJ(aUNz9#vrAeA$+p{#JYfyQ%fDxa@<#9l%9w8}JNI2;jgw z`HXTmV?!BZledbfFJ(5ZASttxsF)UBfucF!3^hcIj+ zWVZc#CR$pp7)!c4g;}F+Q4`G)9As0`BkdG^d&~yqxLnDl_CCeXE^8XgzZ+zioe$t{9@8!CRXGZ693Be6SY5Pu%a`fq1f*VDc}5d_l>s&Wi1=z zw%ZE6!Fa`KG69m`#B4lz{ZPc7AM9v!mbBAHKc;D||F>_y8BFwlQ7yowDg9WY%FLKm z%nc@(?AU(w#j{pHkiMHMR|kQidnfDI|En2))x(W-|xJRUVgd9qw#sA{ma ztJ9P(l9dcLZ86Rn<_L+j`6^>yI8mztWo@DZXuLG@Ft1DHYWo*Rr6ZZP<2_F~aPJE+ zQ022m8blGc5IKl-{5be3qg_Ih(SiEajXasSvs@N?9gQcw-DKK6MnrDdK89O7pv0S- zETa+kZja7<2WK&_Jm9k2q{e^5zaF}gXV+gRcHLr_L`v`v}p@_dzlD!*Se_Nbt z{ysQ|FU2kSsP~hqN#Oz5Q!Nix>6rTYum(vwm&~7@JfyfkCR#*5Tn2>@z4y^R!%gMF zDEynWO{10pR8d-{X63@WAOF&u|MiK#-KYG5H!FrESdx-VBKcbaS`-C&RQujeS<$iqZU>uIxF#B8t z0l(fOu?UyHqmw^`=z{(s(kwJ^8SO|mgf_rcSUqF6E#Y2}r$9%eC-7<{V z%5y@5d8co^I2u59uQdT-~m-h?4`1*{Pj&FPL~PwQB$ z4EHI6mYL(?ROEvSSWh!^vN#PZvbOuWPBgO{j}Nch{7mr@)DbdUwy3MBxyPzORapH6 z`zLjC=`!r@WOv8yrYngZNkfX!{= z0tY~8WqA(;>Obag#4Gq5(8N=aTE>AaT!lyL3EB-g1rZp0upJeO&lv@ls#>8d1cLxL zK&a4C>l46{nYJw(yYqUSZjj!UqzB7=q^GaQqF}^s7M`$7 zMS87fgQUHA?F~EEd4@A7ERtEIlC~A%3XNrf(GH6as8k%-dMgGomg&gi*VDsdpfM*1 zd;E*KWy+H5p6}EM@1QwGQi>aM^MW~P$*eXCTM``Z6XmY$bwetG^*X5y`mS!2;ew`` z;DykeN?&grcf~KZNySKJ%CFK8Zt`g66g=u&jlhGgs5p^)Zubm-PrYc_ygw)?QSqz;s-<8$&|28#GQ+*o zw2IXgJmZX>UMur#X=Zp!s5R7Rmtv(jd3TZSM69s{E?%b8Wn_gTX(|UKi_?PSvjIAm zB)bxobAl7nigF*+d}F8u(w&^$#!5oIfDuCRhJ;HsMWsoSUV)WFpU4dyz|YO7 ztOkw$6)8e9*6j=s^~9XzQVL#-yo@1xLW85mc!seAjnc0yd62TKN?BIDI_p!GSx;G# zk=VwP7vOtiA&MxRPg=33EVISRGV3YJ%qvU5S}IF=h`I!5qd)f6pu&Wn{R-12HGK+G z4o*Sk6{e<8dIDEMHJuI$lS;uM&5#7}I#`ozC`?|A2Jf)n$?9Ji_x4M$pc<6mQhvpe zUVgcgqA2CpYe9gahpt#KI*``>(9H|Xp<`16YN8yk9l0dE6)(N;VOM%x@pU4ug2LnM zD2cD7brmVkO%Qe#lD4#Kr;0C{^<&>?)4{N zP3lY%JRuAjeHmv^Wr;Mg*jt-K3?6C+h(}7$%n@Ku>UGer6bNLK!p1+RY6iw4UuU%# zv94)k52{SJCS9Pg)PLL!;;*a!EGG~ey2}9r>V)A?bs$6HS#o%gL|hFb)K0_>3-dbe zBD$DW^tTYF@{)N2B*;B?8LG|&zN5%nsRUxYrPN9xm~LWE*$f!pqV@M zIkAJ5;E6r>w}(x%Hp|#D4acHnqj=1WI@4&K%CvSHk%G01YuUW89KGquAe)5j9HJt# z29+m`3^_oqim>%jMul1m1(Z9_E(I=2;1M!a%f?Fp0m48)Y05(FHjXd1S8W&IIOGoP zN`q1YCvKIQniZ(|g+(=OYQ)~tvdo%{NNNqEH_DnRxrfM(GLf00iIkbPU7QIg@Oxk_ z&Rzisvf>ji(MZ|r9Iv+D87N=ib;yZ#$nt(C2sTA-D znODZ1){2^70fpzciCJ~xWkpTl59J;hux9Si8-cUV7vh$lSbi}gyQr0ca?4rlPBtQK z-kQb5Lp^W|V;E+oJ_W#!%nnZ=tT2`e=(RWF%z%m@5j`o#;xGpILw$NALM4z(B+5LA z;HWN%qW&>JGapD`X|xnxOxQ=Bs4) z8n~NX1--fKH7{_P-VmB(aGJe-M5=r2VVrw@@ED|5;n8r*#3MXDpeubC%xtM(@nQe= z;9zD;0`O-aZiC+7*@gh#usi$62? z_^I${*LCsJgO5*zN4u_zzc~2#h45%s=o=ottSbZ^d~2y-Lti&E)?Qg``M zhmA#ONUzQ`(s%`)9eFHbgu}B}Dnv$v_zIc8=%Me*5|w|qiA{u-ZvTn*SFXcfNn&BweX!F-RT^(&yj18MTK%0zvepwb`aaK01)!P0^0nAvyG>?_oD;08McLd}RH?A}S za&$tFKeB3rzvCo=wf>HM1>*t0v>2Z*-t%*Gi$L4oSG^&aGd(@Igb5TLxs3vn?AQ+X zTE?o+*s=Be^kNalj8$fqWV$f2f6rVHZX){YIh@v`z$ZHZ$RqkdAPW^f1Ig3kS^LZRNnx|OC)xqyGF27t;J^rh z0pvGgU8y`9&aEDmdPF&Kd8CD&Zu8}!Q}>qhRxQ=S0v6#X>meud$VokN4tjJLa+q`K z$)DScRq!0hDL!NL&i&a9UEcivGe+e55M9H;>XNEHF_JiX;X$BW$it3%iv=)xT*x@< zx)EkZfe>Q$kZ{osA!eR<&z<@4!OX?o<+lI4(mVkR)$sa##qDoZogw@xD7Xi1URYp3 z=Hi}`VkJKbN-7ZxYnMJ8Owfxy7RBex?$W(tKJXsMdPYKB#?XxRQ!<33w+O?)IAi>;O|^(Db4K!inE<|#-hzLlcJVpihU zW!Y&&I{Hh{M$L~@!uEaD;(w@P50e~Cl!;`L%T-6cXUzUsM!;xgA_3vdo6p1{9QCet z`j(A4wQ}JoVWovthlHggD$^CuVVyRJk!qApmi4iRhB-4ELiOir^EFsMnG4m9K$=1E6-#f(A zJayRIs2oeH?Y|JxwbD_y2@zAZynY26F$pcUd(92q{1rnrHe1pNx?yo6i)v*mqjC5F z4e4E|tHOn<7QAxdP!$uDop{x{z%Hr>oXgW}-Zgbj*?XBo&wM{Z&ul{2KluX?%_koY z)&=hkDk(1m1#iI>;Ql#k$9oSN6*?|*bj^=SKpD%OrMVHhiC0Xss_)=q07q`xSVa4$ zt#|Z+*}9oQ+|mc*8BVeFK2wtldfx`u|!zLQUFAxKP(A%?gns-+9%@1!Qnw(mLl2VRA!{DNN+GR4%C1%mosd@tm zpMcsnV^3r;k_!mpNn zj&M@F8Vf><66!W>pCSaxK0gvQV!C!65sn9egQn`18iY}lrHayxQG(blD2Ic57+?YG z(frt^ry|w&gz-E9l{8`Z^1;U@n^KLX{Y_49U<gI)y|V zQAe81<7`Mp<^iC$L+q`IqMm@Yr4U^IL+8Wd$~a*FCbSR|)|WK;HF^q+c4EKw96i#m8i)Lm9Aoq=WM;JE6v9LrW3ekM#^VN?$qcX!N&*ii zqVfI+0CAXB)X@_xTFGf`HqB@r4{1wz?!2ywiQ?9@$6gXZZmXrfUxL~KjsQTW5zCLp z8BK6rpUY_<(%kSr`~k+m?xQtyQwc}tOzrg%kF-zR3GYHs@$ z!yZnF0i&NHySl7S%bGwiyu$K|lQc<|_*6M^PRX!JjR8d}(Auv!A%|y3+YC`EPMQfE z2^)cFI!09kiqk5hbyJtI;O?qRd$I=o#t!@RPAIKZ*@L>we#@Ti#?I{ya<X zL`_^)Y3T7>;;HsLPTJ-ucod&R#w_i>lul{BujZPzt3io1Xh`b8u*1!>7AW;0W|peG zlzgqGE780~Lbc!xcL=T1#h#rVPX5HwBkFUf54uKYrXr0+-{>KC_VEKYTdj(s;^X@+ zQ=BI|va}aXVSk;9^cY3#Y!)ruJQ3HMypD>%dhHg~CLb%RV~;xo8?Y3`2Fu;d zaxJ!6Dn+3P1am0X;Gm*54zm8=X$r!Y2~d+T2##TXrnwwT84Fn$ z0yIqe+V0}e&CgbMa%82?A_oUMM=+z~)LeV>QRxVTe`&vatKTf>8I45o4rLV6Y!uhtI+&zhT>T15(!t#tPyo6}NZx)qCkQd8p&K)*T}L;U z90HIQ`&FCKv=Xn)8rSMHtRA+A*t|p-s(2|t1_)6}b`Ga;x zM-R~Eh8Qnp-~JRArW33LVxFjsUjmEuC3JmjtNl*zgZOGXuz@4><+|whbAZ)QJTq;R zX>697Nx-&j!+vyx01a6w6^K@a;bN(Tny*fO^X#DF&Y3OB?+F_%u#o6rl7q}-z@m7^f2sT93?6FuGs7V>>fNG5>DDX%%Xi1gwZ3}Qs&@UD{ z0mjz2)T-xY9$uoMBrV~kIU6|pnRAJA&T!WW_v} zl-N5T_~%Jt7|(6)9gksT+JM2?EPdk?Vy{4hhO`jF3|bEdOt(hBkP_l#;7Bddb!)>g zkKUgdV}H6G(n%M zBSCHTV5lr^UdOE+-aNyEwSkc^P;-nQ4AB(C{aS%IkQRfbZ%t#mGbI`NO=L_@Nglo1 z3anAzd@BGp(24^kL#T?b#x)d>Diknu_Msrk<;7zI|6mnf&0Z8iQg%UVu7WH|$Mp{h z;JjZIQ|J)?i)DkLx_s-U?Lg^=i?OS4Om9az!0!@kIqxSTZS)A}%VNtcU5v zP)}GVFccgTwGGpN%T_t{OnARQlH7%T=R4V%e9*f10{MKdf%oD3Cl;I@_-;pm+1V6R|Ka3jKgr-_3%p>ND-n ziZMZqW|dxKBg(_;UoXfY zoOd%EL%{Yc(UwzGT`qM?XjVN~&4kKWL=_&?F{v(9ggi~7&5DM+O;8-^>}Z;;quLva z7inFNsSqC_JIb^_yV^n*s*I@-?Y#9Hd^uX2I>i}7-R;3cY!B8BWo`D?o2dIHnhkrC z!$tkjH_JMx9b5`#v^R1cBw^h{E31A!#lc4v@H5Yt*$Jc5x1nC&P>G9yRdkq2(pAPC z?aD-TGM>|M1w-~QLsOzfUZas3yhK4n&S0TYg4DcXs|p5cGeYU~5%Eo0eBdJo7wDy& z1A{`XW~&}t%IHCI>3|vK?McG$MnV-BVb~^Hfpb0^hJ0h4F0N0GTRNY!j`mQ`|l*tEKD`}QOs!r zSrBhK(LhK7W|2)j5KHv`P?beVGJk;rs#w9W@(=0FE4VC_ZvCmGFwA7rVzW9K9Uk?u&lq+bQZZ4>b8_#&C<9>^nuG4Yt6F z*Mh>bJ?m&o-Iy-#BJ1V0OI-nfqHu|Euw+iUa#kqhc4TCA5$@ocLjjIc ziHjhX@K7^+>#2(X4bqXK=>f#&JYFfdPGqKrp1Ez_u%OH@#7(S zp6Z_qJ>O3CGQPX^Z`%A_ZO%S?0^uwkPAKf8#S4T>;un~rbX=c5#4spjC4*A-cKaX1 zN`^?LXwsNqn*XO523{Lm@A^g z6*t55WBzvG;2w@VdQo^-xNuq%cK?*?ORTJ~Eo|&dd^0FxYTo`w;nKgaT&e?}+h6p8 zTC-Eq`HX}E^Tkt-5V;fa;if$5COu_In!b0FzGz80UcH<21xvy)(@T2VK1PqL6!o3; zrT?*|GkrB6@VbCYSRZp(Yd@-Q7Ky6TdGB z>F$2L!l|sJ;pXnsH8Oi$(HcmT7newbfi!09n(v{5X0KyKfQexzF1}%kL>3z-hf1ed z9vdZ5YdZc@<5arR;Q-XjZ<3;q2)cd!PNwkfXuro#_3_b<{5f{^HUEDq< zgt5%POQxKlIA=o^bD*3rq0pVK1U7GVEbozr!L$50@FHrnN-tqy%gMpa$_4WyPeH{(kZb5f+Z&HYyZ%@Qf+8Q z%4)M*7?xQ?AR^$yRK`>th7YgPqrZ-i{@U!^=dS!{ulwL>vbG1zT+)j$G15y}Le`nl zEb+vJfvlwy6p#o1xZPuM@lzGQp`8KdR2hhJ^y2Vi0K?h>E13@Kg1X+DX2S`ZN{7&T zv&PNXsHB5yL0iQ9R^9lo?*c#5t0UX1W_FPZsT+PVhx?t)5B1?1A7HWYtb%xiYq4t= z*N;E67}o>n_|9G%wtSJJV#~4wZ29blt?%n1tMR=<)>H5M4w03CtdG5?WXu6%ef{Xj z`p#Y(vV4)FBFnM_Wclodtkb*5@(!=>31=Ppc96A|QLu1clYpzQGispP7;Q!rQ-rEo z*kI;&@${jKr;DfM5+!xvTRc2t!!!@w;mKZ=;aW=3e`OO_m#lL zBmHdrsRtLcarNl0+5OcMg2PKA*++XlAR~)P8(n?cQR!+~0$qJ}qwB9XyM#UWdnW~V zDQx%oR0d(bhaM0fUtB!!H(X2S&eEv3)A0MR>`}8b_Jh~w51!L29HXhssACM`afE0Yjk|aL19?>R4!h~kTAIRW3V*4#6C(SBN8MS;Y{ z{l1MdMT>0@90B~p?DHS%chB|CPZBQzg%2*JN!&Mr%oTiIMca#>GK6}@E`#OyP?jQ2 zvjK6XagtyPK;>dHApC@Vc0f zA5Pp&Di$FXlfDY9Y>1)Xcm89|4WGC)a{7j5rCO^unysPXk@k{fjvYPj_!E{gRrNnY zKsuZ%Ba;pA!JK_ve2D?@cmxE3`8L4vXR^ixiQWwy7jNk$D+#|0F#GNle`;O`VXXa> zvJEY7Ez<;Q6*I2YQPz>AG#)=?td*>e9@0(wYnF3a>m=pm2wnlx(X3Q6-_*ww4V~0F zkujnB#xm;l;8NDmi7lev44`MUd5RBo`r4PaP6+7-{zB=?Li!1<<3sxUEd8XAethe= zkp3}CKQW{q*WxHatN+uM-U{iXtz$#_=Pmu%kbZ3In2`Rpf%IcqOG5gA&j_C3kbg<5 z9nybsAidpEh?)?6kENIGj_7O9mj2K{{^1rgL`(nef%G9w-YoqIOE2LhIi!Ei(n~xv zHUG2x|I5-}65wnoqTkYg<1YpOXh^SXH-M%8p{1V{(rrD;(hphss*qllU)s_?^jE59 zMM$@^LoNMJEWN~!%?K_1vzA`MZ_Xr3f5y_6hk9(PWa+m{-b#K5s!T7$RQTQDtWX4# z96211&+^)dk7=&rh){qux48e_l8%qkaoOEO`|OhKW6}4qY}1ssv`~?SWr~^Q*C_sO zk$^}!=p}zre_$}hd!GqXsLfLb_aqwC@NtIOiqTq?w5~(DPi#*P32L$9W6)(CkG2}DCTncku^Tz!e~OZw+cvnUh7Cy-&W?=aW}1Lf7O3Q4k-rqaHd?I;7-d8tM#tS5s3y_Mi4JFE zjkkDI16%3e_b3gHGEOKG=M9kCjw0X%G+?Q*zgptvt+X5vEMUMs!$u?ezF?;t$Cgke zEP2Yy#N25N)r2!cfpUwAig;EuQWcwA%RKgWf4iHPqm9y5gAK#SUu(GJqVKGspoK zy^9jt+_R{9I!w@ZQHGH)!)iQO*A{54_+Vzcww?7T-e&(qH|7PzcXtx?sHD(kPI{0^ zrQX=vEX}XRan_4GWEH)#0>!!z35fuJMW~5kA}PS%CIS!`2!=*OSYVz#Skw>$BET+U z%an0JhhUC*Vs;cz6l>3us?n7*H=E(i&1Ub+%~WS@T5EM{MKs~;660X;k=m1)y&M_O zw&HTC=zA#))daO-yje+NmX^acK+N4zf*tXB3sdl~KcQ3U#GZ)CI`2m5eix-}o0Dkt zWwd~|4C%9WN2!XhA`rwlhOQy}R~94HwFL@$D!hx*`L%F3gLwg;MIqV=I@u%va#@k0 zdm3;@keX#3hy9x{2E^5r0_u>v`ATJBb9gkd@0Ii>Dte!FXO}q6M0=@Yz2o*FQOrV_ zI2~Odf>&KS`QHxx=8oOuQS()XDnl3cX*4XSyqUyWrtx3sX3K=hr^%!jQl;qqPpgf- zmp`Lt)~4)x43LSBtb~PUr|+xCo)EX{{C5*mLjexx;_-yfrEm~#_?W_F1FRo;?xRUI zk?XrE-SbstwD|8mDD`o*E+Oj8R~)C&cjqNY(W0szKVns+9G;5bglXt`SpTf1yNX2Yn7w_CK+r=;b8UrQ8FDE%@FF8Zvd)K%;TgkvM_ZHZ9^Wb-k@h=h zD5DQbQ#Q7%D?hMhj}la{>`lRh$YUJ$&8wcf)}?*5>Pt7O)xLPstCdI98o1K#j4SQV zxbhsh5;!$%>81;+O_i-8%)+lea&RFk#*4dtlWY6WJ@FTpEWvsHlAm_A9m}v^e%1<` z3<7ph50V8{Ks~BfaqqZ=Fqx{r$(CbVzSpHDOhdaF=6n9IK1K1dIRH%)+conDDIWvf zDn?C2!K+6brQ&%E0sG33Gd|<38IPXN;=pH2rQtJ$fsc7=6U@TIyg9YVACLrTN~8*1 z_<#b$;2VM1OqhdKiraOc?orY_euo3CHgN*r48L(_NjnTE4HubHTW zZ8|MuCTjng=^EoN=@WP#mS<%0Bk8}n-V!|n*Z?>vCPq$^HnT}sbiGF-VEbnzQt?Je zNncxqjqo7Dc)#Gnxwhg4#<}*-Dyz&XVTF|p*aFOxlftQta)oJr=8vgWk612x{8Juh zf2XL;D-AU`e?~~tGs;BIDl!X17Eq4_9=TNpUY5K7Cp}L~Q*mz;SsMWXoeL&59O%an zSOf4hAOI>qY5Q-z#C-Ssp_NT)Jt}`ZhcN@JJ!+(~!RVP^BqW_NQr=n&Cd0HyU_&AO z)!-x&^qZXD16G$6_IzFWj93f6BPIgEG9nkOO+bbd#9f%2i7^tH%(O&9V{HbrvWQDN zR*PQ7W_r(>tG6B@kL8x7Dsz&}Um;R~bj-$Q%*I@tODe-E=@ny|D|+LQGzo#~_Nm** zEK#e(_#tZFZn*s6upyN()uah6O<_)qr(&ofmpsE9%q8_hPeq(g?5DD^U#}M{+5!k@ zL3=6&(6rD8vw_g*)T;+SbZQw8vLit^*%1rOZgdc=*67&smd6~7Nk;7MWTSAZAG+i} zE0P_=u#7H&44fl7!!{xy!sGca+ zL-!+zMB)r5I0>2B*ycHGdIc$B&WGvfW$bJ%Uoy|q(G*y?dg)KFU{HA4;;^#fpABvG z;#BVlXz4)xIy)|lZ5Olr-zb=nSzV3d>Yc^i#H!mC+D7rqr~>oi7zEY`UX}hv3?l@S z18nA^C}M=BW}Ld3cM}j8YS;M+w8LRH_F^q`Qg}h5_*u1}9x`xQ4^@A!hnfen0=Vc6 z;2Kl_{)0A??3RxDN?S;wor_-%HJSoKT`p{z2_ufhjPg;PVgwZht!W*8kcpqnc$TQ@ zP|vn}WoAOz!7svx-z!EwbVr~#xEDuA%^Aijj29xYYJ=L`B$}!Mr3~<3j`sx#`~?

kfXKelHy}_(CETV3h%PhH7Y5dw41gdZl0g+Xx=0eLhn`r-{WIJj` z&4j;o)3BOLoMLwzD*0I&({?P%apa_biugLW@4{yUBuFE7`$*woI;GMJE( z=r9cU{n7}v#spClS`Yyt?d`&hsQ8qe0xH2Ibu~dN{HeEp!8f4ph&C?la4ViUO6L7u z9h(do04N^m1MYP$sf89W59TZhM(9G_)T!3X&|dJrfEJwSG&`(D!A|}}4{a3x4$dNZ zbrkyVC)_r82?Fb(Ss8<#59wWSV{eqFCDaLggFDQ_zsY{cfq8f^V`xf+i+!?$xND)H zW38~@dM#I2v?{^LUymB*Y)Ya(enG)jCQd?1AKqkAQ!E^@9;6R=+31eJShjCprk9(%f zd%n}|oSF>+#*229){HqH{&i#r4k<<|~{d5@$4T0^*SC=7Ra93XhFJ`u;|U1i3Ai`SxO zm)|S^3mdvs)BhL8NZoRnfJ)*d9RKf$XQ}M&8Blh2mCEjiZH^Id1Vu&`1F!V1Njt>t zyG0B^jVzcoiklf_QFaAO6~v$_Q(VD{H1*J8&k1a_=08sK-Wy+- zL7GyUxOrfLR|ZovHOMIx?9t%iWcs<-!-?}i?nh3d3a04udN{3wmdMS+siU@f9!`6Q zQRzLLdgojAO$>TC=~VD=f=yYY;KrPfUPFPqp!8OlN;6d39}2=MgW9wCa)xM2*WiLQ z$=WVz1B$2CuXy~>gIrT(@x?)v*x;A&) z1ysp`umbiO47>A(Zvc?=dItpAw`lC_D1Ss8u<7d(0JVFDzxH*B1RF{E!G9FO2N}b| zsBl2nD1vI&0M2lkt165o9yMDwa1ajZZ@`hpx4sER=}QJQebKAz1XDF-=<7t&xYxDc z;m7zdx;WjJmb=^gr|7`_VL4KY<=dDC^EHZWW%9`9K~|?SAz4g|+ca7ZLci;&p?OwhxCm-mZPA#v$`a#_<-P5U0M6Uw4`h>eJuT5NV zV86D!>4E9NUVCOqm-iYQHP3Lx`+-kq(%9Jw}Llvrw z4CbV$0DP_sy9`iEin~e7?tu^7bBXqJocG)^JOMdLwLJnT?KKoWyoo57UWzwDY&ms1 zh>$Lva=}O;qnUfwZuN=3$~TL^fj3vCiBq9t@1*ax0StYK2Gr1 zgG26dbn=d;`rbYIc-C!uI*k%hb-ospS6=PEYD=E|dvMQJU;Q9wc;;>|q>T6Op%b-c z^RwHM2%UE@YTkbR+|=xr$*o&{eCn#*lUsL9<(nqAZk^hkUo&;>_Svbt_jYFLrsLc)I-esXqxE}xvw4-Vzm?3&M~wr%#0(Q((@G(VNkPHwx73Z6S#sAxN7 zw_lrIvwas8oSV;IKb3Et+Lmvb%MTu76)VNJskCT`Rhe5GKKbAalzX6_9O!9#cFVTw zR5=x1H-9~aM}YF*S@f8`4h47)cFI=$J8RT%)Zb>?zf{Ws-fyee!T4MNUNgIEZhq66 zwNuxgdCjI5Z&~qdOXWiz>&669hy=L9n*POlftQVaCrY6_Dc>Uy>ty`{{ zot(XC4OHB|Y0cd1rZta7Pt(m)N+om@%qX>PLOhLJNi%}&lw&7HAj`|2~#IqRHF*KXLf?i%`b_WEnrz=4~mu9}|PzHRlH zXRJNr%(Kt3a>lHB`Q7xPha}G`-_TJ!~B{X zwr~D!;Oy1~O26B>di0r{e8W|{r#5vf{EuQQF|PG~5v#uF>`j|D!;X_v=Ult?taUG1 zvw7>=o-?r`Z`DDK7`pH?Z zN>Kvm|$@~PQbbnrp9GOD~x zx8nzEtMaW|woRed8mn@oWY-PbxF^Gp#qDS+ilX~n6rIX-*Ve7GyQU_$&P~0kbFD7( zJZ>ZPN8Y&V-2WU!?W7%DMZSqRia6UPf@P<+&R%!TrW-jx{-#Wi(_*Hrs>#qKxskvQS=g&QN*S0szPVN|Ad3C;hTRyohzZ$@=&P~;H+x%6^ zt>E{KjXdvc+1xod?`)sF?hKf7e)}wX?ArM=rf!_PVaL{~Gd54nP0sIU>w=f=WpPln%fMV0^mK_=Zl=+J7yWs$hsZe11u2}}oYwdAvO2Y(0|BlJ|>&dbG z4U@Bs=-16o!AKw@^s3ChW9zQ#R&Uvs7ZaDB;Tzg9IXij79Bl|Sba(OwhV*$ocjj-} zVLjir>xOI8m%MYs7D2OCcat}Acjj8%Z=Sk#5=!{zH&M--8gKH|Y`jmHZrU<`Qw~06uid)+4V2lOwxcV#p3HB? zZxmP3DpUGV7rE2i26s+nSz2jE?)-Ra_`LYcc*HG_oon*xxPNvvzHffKBX^RM{mr7DHJAw$P5D#{y6kfRD;|QKe+zGB7tM;@S^B1V%M)i10Z>T>1CQ}*OZK=eI z`K_ew_$02!BujzK#Z@wBGhwaLh?Ca2>B--(HZ!-BzbC{BVyLDfh%Q}LX)*aiGTRt8q3CsmrsOPFV!95=}`9CI+T`#|mdWF&b>c6!{bot{Cr_%wcP zdn2u%8lMeJ!*RtO3pMI)imha?Y>tiGo<_%WTxc9+s}0%>)p&Smy-IKTfA+@d@{`=_ zTc1AZO846My6klKWA3%}wJu85*Q3!#YJZcu;q#M5Wkc;EzKt{AJSF)-*G$LU`ucF( zh_73^yioy`iq-p)crQJRS|_Aurcpe7TD6sBC)wUi@kW%tu<~MetV`3(5t!wEJF$|G z7I+#N=VhJ5TbLsr?z}Ne($&f9+)(1yoN>#^$(bX|(-rkoveUCu-1n!$FMK!ctVma+ zgC}HY!8Mo(pG;E?*Xpq$m95 z`I}$Ws)1f&=G`gCK&#%ks1~0QHpqDs{Ko4L43^o^-q$zEsk< zDp7NFdRF23{rpydepL!Vzj9)A386tJzs8NcXehciYB8D&G1#CsaJ*Dcb&d3uu2DH9 zt~4%cG{F9G*|E{NpZt;R#Q4Njm#61cmu$?M)q1p|bJg5XH2mTyH3~&_cQXAQ&Zi-%O&)367Wnpgy5KfBye$M2#1{WVAKf`cL%}-|`xFv9yYG4lB2k#RA!? zab50G@fO?@Ik?LDv$La)5Lr)(by0I z>W;6)Pgkh{esiCQ+bdt5D$j*4|AF64-7-@3zrlO{Rs4mfLb?+5Pr1~y)G{>O5_C=G zmYfwwtJ2M_5j5zC`~Jp<*PlGJDy<`Zm3Kz*l4K}(3VC0iZUFP+wNp55E*`GGAgT>> z(Cx)EatvJG%6{H4#OJh9VUghTEV<1}e=glUXo8$lgK>2k#Klz1asq+s?Y3{8Ez z;*Q&`L5bnwuK@sPC2`0D+T5)zM$)y7G&!x_!tEGWHt>Q%*#@NW&V&<>8Kf$R^Cve( z?)S!`>dZUWtOIJMKgVfw#ve9W&%ktDV?Hog`~P4qmE#P%o)W`oj+Z)+#5;y(x;GrZrlxM5 zAYA)&xaCX0j53Uu=`ES34NFt{iyR@E@z)UR)ZIb*DRIH$72}agoSXp>81Sg^_p6}G z{m}6yUGa}sNP-&9U83gP>kz|cd{&kvC(!T82rH#Yl$}?N+y$tMW(*dP@F+e%ODeTm zTsj3*3VcV=`t(ILH|&l_ilb^Nznk6Nl>UJS$GC z<@k65$APRSO*gKU%Vx*a>@;KwVcHeuQ zlC%D`2uVYWh77`p;R)ci6rFIelm+w$Q@|3UmJJ3bP~>DLP%48BCcxK0nY=V^jDVK} zloFrKXALf&k&Ie;>F`nuRD_TRn_$RRoW>I;13`o`8FGV)$ri}ouG7JeVqkvD{dOQz z1dGELrK1Dd@VLq87>Zp1_JX3A z$q>QLU~ZJDN)xbwn9E=Zcw8QsfAVz+;XRloWU-P^qesj|k5K)|c9A0Hi5Q@ySQd-P zV#;O}@pzbI;Bi=R0>FF#J}^csOlL`0v0~A0{bXfKPzb8XSOHHcv|+MRQSwl>BiOWn zg<3=CU>pWFT~;hqtQnmLt%X^{95`W63m1%RVjegC>&aqsVWR>uAFd8qx0uhDT_|EM zOTw31GAQK+)(tw|AUnumad?7sxNP_W9#}R)P{QB}U|6pF%*ixq2OUs_%FGKMm`eir zp_m&B_FOzq0E{V9UIg|A*bS)N@dWHwJ&+2!(pP46{n4(((0zDZ)}UPp4~75H1grfg z6Z&-jegdoHcS-gO4?|{Th~PHiqh}Xxu2ht!h)I`Sp+hP_ow4F%P`k`d6|guAlr#D=R{p>x-(cD6Mw8 z&RD(cHe+pbD`QjP-Lg%{!}d+Z9rc@AI+eDiysY1b^eimD+qZCE$j7pS2+~p6w$rI< zVogld!7Jre?Oh#JQLoIZk@qpxCLb47Bgl^Gxw;M28N^4`NXw*Sj-Q;54Sb0OlpKSv zeq^yK23b9fjzsE85gkL!L`@8RVz)JBniW<$jkl9-t-QO<+N8hD1{uJRw|$|LKP$D9 zl}4IU%ty6T_GvL_c4OOVZ%j<*IuhIGn=niRdlJh6eR-xqTkFb#kgH|EQ?IoLBX=1g zNSkT+!H%+smz|8LmS^oz7=%mjQTjsng*A*kUu|N*zs(UA5Z8z$OibZ;uVKsa8dd2M6>;PX)J+nTtFHR zD0Xgaf`WBRfG0M}{G%iX%B+A(B$mNNzdquihDM`dEW}jHzo!q*l_={I4E$9HtlJAV zf$n3-Z3emTCuQKpAjv?V!t^LII3*nOW(p0orNhB$uo*^HiI<`Lm}Ih=bq|J?pt`unOnMgI$f{T2DkgL&;ip1T>wo(lMydS=Ow%^l@3R4yHhP|srdC52qNXN&e*m97?CgkTr0?R_-Eq5f z++3G6x4hM^_T;+sdA2ty+f=($ZT&gjS@ObVwX%h^)e4L&NdS(FDem!Ok0Sev>e*4oo|~E3KWQ1y^E~tULF#ozz9%+oo!*? z2g%7*J)T!C=q)X1H=jHElTqSxqp-Pq9Q-k8Q)_xtQ} ze(-ML_zs`dB{#+8I}CiQPk89A@bdBg&lMfLq={kMJ#0*4(_3b&fa32YeC zE}_qBvLXf22+Y|2jiHt!Mkj6e zpK#{{>v{PNe{&y;(>qqE&p*KU+rh$vGv{k&1^;SjBb@IWao}0x`(5*6kKTz9_dS?z z!f%WmQL7U$*^5@aB4JK|?e>E5gHBliSq&wV4|p62i0J*m9ee*tfH0+Ixyjn`fzRBI z8oaqTFR*+p{eHLqlE8~5k{kP;o(!C&JB@jX|2k0X4#{Dld2*1B&*EkW$MB#_+Sj*F zQC}T2P;!0_*7K(z2m6}Py3&t9apt-;Z_BX3xxX4t5nf~lw>{h1J^J&e;KItYZ!KrG z1b0UggjL?EAxR{p*pxvF`N;|CWuM@MoV3iPcHGzzVnvjmzuR;tgf!b-GNxZEwBEv| z>qUff=xf3IipfMt=z*ft(RQ;BhBh1RWuJQ15jsn%ckX4mVVG}|(c4`syuSp0PrrVX2E)NPX969}jvrS?6h9~FddzRLR zJ7A7Ii%{tc_ul=;jF>kq0_$;QofOZA$hFf)Qt|W>r7w7caIiyMULH3m>oU!sD1Zi!=ur! zqemn?eDE~-*W;I5gKtfs_xf*N5mez%ubf(7yWgh(?hXt4V6#(nCJ)mcJ^yV>OvSSol->AYu~*9cKabDkZd*T(nm2A|;Hn|4g~aN=k5d8Hm|7u`D6%)~Wvd_*)5;o(D4G z>qoK=`Rw1{R^!MHi)n2g`&7h!ZGU;xL(E?GZ5L_6ihwq@W>AyULAG9EQBuYYqdbp9 zp<1Xr=5bD<`VSNvV)xO+kt_45N?p$qy?S;osh>PC2^(b5yD@Ek(#a$|E+=ql(q6Tk z&%Y%8m}JG|MO{*UlSFdRAZIsBO#Vw0B^}zl)Y2p?dt+B#$zru?^_UEvgN}KM zYt~_2vjOMw`qEBbPDE2~U4s$-DlMxeaGW3Cd1b; zTsHi4j9^)B$+8RF4T62Rk6jBqFAFrHGleUCl!cd5!&|T&WZ}X9f$FKv$-)*U)qPo-G=iAqu>5T`bzR@!E@pbM}d1znsNaYPO4J zoEGLh@YNS<9P)d3bBCump0h@SwKG?IMm^1E;A)ll^+mmo&nhp(w+FlqWIJI}3uj70 zOy&oq+W9oSdK|wj^&}%B@nQYxRQ;^N@@YT6NewHtTakLzB8|Ve-zGpMI&BL6RH-5H>E{vdrEZl7)bkYR@=1cSG=U=O@O8So_I+GcJI-pYqv_`qdfVf%25o(QG#@brZv;I7w=5>&PW^CNW7oU-@iQWlXOf*VX#f^ z^bu|uyaQDF@)Zj*Sjm$z$&|{BoH^FUs`-yIqC(%9x;`1V;NAv%QrA_#1=k&xDL+xk zU*NWK+Tw>UwF|tc{goO?Jqx1MGPYgGH_z-V80+S=D>U>cyE=o7ojrx%J{&jKOem}dc=^MtKNm>(|HPXTKuv*&2EU!Y#h^CS&S%=?kqJ18(l3glB zmd@y;WUH)2_Rf94$?gbu^z_|Zo_$x)GX7COYj$ywYNxT)sGQoL7jfs=JLOmwPrCTH zDK&>6+CO9Bg8eztrmp-q&Fwj8DBpi)LM=jYn*uvK3{2_aK<17>em~zx_$w4m@R4gF zqyJFz`*z>U{j>eQH|}5M{}mbl>j%MrHRT8q3v}>#J719sFmldG>ACM^Nw?}4ia$~zvzkn!8!DCc72Q7_-98Vuh0R*fuN={E|T zZcqPuYz=`;0t`L!&qY~Zi-3a#UR^<<|6w#Ux`L#Ks3HdcH}8Wyut)y+yO>x-b1|14 z3%miiaNvW_1L|HDsl-c`g{(0k@JN8Mh!A5T*`NaFW-0eC{YhE!ur&xr#&94s76O$) zf$}oNT(UI-ccIt=+7|d_S#H9~;doK-7R!_o#0ah`2sV&G6(kx1r3DxbP$VTd&;~FtE^Hw`nURiRqXB8C zFGcR=60jgHjSCJ8G_DJ!Lc#H)P*-v~at`A0P+s*gkf!L^GPV??f{(0&V|0!&0CX+r zI&=Ui2Zj1S(1bb{(QLR4fgL#o=&x905nfk#J-j1xLlv@K`(!kH-`6 z5ciEI<0*J5o<_hDa0EPoKp+xG1PB8sPzf|5mWU(bi3B2%NFtJn6e5*KBVkE65}rgL z5lJKxnM5H`A(k9V#*y)40+~oAk;!BVnM$TnuoN5xPa#l<6cU9@p-`w48Wl^$QSnp) zl}IH~$y5rJN~O_Yi8PoVVzyx*8Z@HO(0xM6m3<B2Pxjq#Y>hHAXUL5XBi~y zLCSt@zG8g#hBQylkufhcuc^YQ_(TP-!hSTScWTk4D?H;>7TN);4&C+cj5^r!a=2&z z_TG(CT`ISx&3<@w%;inPyEo-)%o;eNzqjiClU);+#QqqjrcqH>wRe7!IAi#)qt#Da zTLv<7jyd0|H1ukkKCXXyH~VaXTaDAMSB}2(A|1LObo#lC)2Y?%1UI(#n>8;ESsd%0 z(s8no960jbGSy|H>6eB*uQ_(g^g{i~g6BxU`smGhl6ys`i7lrDs{R{)nYw(N6nX|8^^q4@$B6Qiyxb!B_TJpB-92WFec30DU$^&m@@h)C#aXL+ z;RV&?vXOnA%J{&2O1YXNE}gd?e&h7p0}*A#>bjH!mCM?N84U%y?~!f0hwGd@qI|Wk zS0$=5{zFM)ek+^%UhSHH?T<>WWI}tUbUbmltM-j~(h)ji+Eczv;Uv?acEz2kv7>4uqmMC#PW$~&Gv*O^HUF7&62okjK;>4-i!;C^;QFy``g zBbvFoO^YVBc}0!x!?vQ&5Hx-I^6v5-rA6Fpvo1R-O=jL3h2FI0s(Oypl=)Q?B(8cP&^9L{w5DO3j76aA;b_1#b4S+jo06O~G zh&jLxfS`XghiEjbpo;n{{a@FB67mIoE0}$!3r^~D<-a1<|3wk&$XjKN)YxbUY+=W- NgrdLn{x8z|zX1V{_bdPa delta 29513 zcmcJ231Ah~)&Ja?dHZ|GBqSjrfy{es31k7mgjF*Lfd~p#P*fBG#3d|&Bp_PLJQfud z1-!Pku3#yv3lSZGGnA3#FHGBW+TFREFAh>>Mze$CJVM$pXer1^b@krOcdn$U&j%gqyh zGvG!dLI}Un*&hr90zrR7^9KTcVHgoV8b(5(ut1GK4!R?1(MLctbbuKHBVR8tePW&{ zF7^S-EPsLF3MZM|rA1uL`Q}sgPW~S6z~q2`PQ#q0=4*54)J4gtGG@4OoTr?s&5pw5UyThYu1uvGN~m*Oml)r zEv1weu|>pvzn31waOgGkpRGAxim@?GrSuv{E7A9Vx{GQ$7BVA^&M{*?ebf~ubjMhj z!2dMIm><(@oeCeI!so<%wiXkVev2z>qX=@PqqjOcK0$%T5?xD}CA#S>a_8InthiyD zabXYwfLaL+&EX@5KSYV1ANP6qArVbzwit~P!pQ+rfS_EVYLYsQYf&APmFU5QX=_z_ z)J9`fdN3*gb#fZ<$7-~-!noh4vHfm5V4ENTaE;;AoQX^%sd+QiGPo6R&>Y@Aki*;p zdrS19cCv^jt(Mql`#^^+@NI+gDm@1b(W61sr4(2h6VX7#Hf@)hw246x;OVQ<^HCYC zS_yL$Dl_W9f@?Cf2Z1B@I>WB^lO$bmC7q%8Rqgo{5jkDY0 zi21hRHYWUz(FzXi{T+==LI>gd`I838U^WsNrmYh%^%O518i2*N|LXZwN<<>)6{65w zrBnZC3D^@(LP4BhW2V=)ZL~T%{-9IMwY6Ez^RG+<2ni#F1X@T#0?h;yenP@ey+?tI zUk#{-L?8_b5=4arz8Vt(xPT?PhlXYwjYJ5BNQtWpqM6l{JVeqOH;6-&RFdy^z(0t3 zYa#$KM~{9x0FpQp8H?t(AszRVj1eeddO*mL*-lB^jG(pw+-ZD>62m1@@Mg9~h@L8i z20no&&nK{znCGB#Z$^RfBzZ(O&oE{z1jlf!I_qBo7|>_-dq%xg~DfP54Kt zsj7$vW73HafOyCUi1#Vt1GcY?cz+u4{&;|hClCZm$r7fPKaF@lW)R775In$(=4GHN zhu_|C0&$F1V?q{8D|Ru`j1m|Dj2T&)z(EKWFs3<9`Uo$YgQs)8-$2J?EofafEzWCW?0nl z<~A6F^2GCTT^Bm$d|+TD#OOi-7oseL5q;Ufi6%0jX0wN$Zu@vb(R{Ll^NC5Ag`Uop zL#GtFg7AR&kqFi$(3}q)>2;*)AdW}}s73A&nBpTRjuADWvizh+P=r2Ag)<>wlZw)7 zi1$1^32>4KM!)E4e2gYTyYhBxC`H=aB<*b~^_r%=MZ5M!!62rtCncB?ti4gC5%tov zHzZ7)sJunH@)k;Y6SwSutF$+0g#HHF^dE>qSLqrYW0$VM%@Z^@Ca{mtQW~5_jZ)wi zL^4f*qfrc-QsBTID}k-Ktih3!LpcD@RL`LtWMJ-eoZf_1$LXD#+$4TV!QqRvtdXwU zXmW!t!%6Z`AlF)lwI6Gu%SwUVtEmmCYn$4Jb4;`;HX|-*ZZoV+N5`pl z+d>gfu_8#LuO>Ihqd5+Yc=TK-A4a$h`xDj(Qk^ur!AUhb>Td_}!W>cpcTgD?w$9cH zSn^2Hgr;+>g*8~U92X+yXrwbSX`mHb6T%%8!vapN9ih7DESbCx^Te6gNMqq(5NFjE zCIY~qN);gxmH&+UBB?gU7FMZbJ8p+nE~%Xzv~I>VqlRV=mK9zA6MmQ+wJ{wl9Z5B8 z8_f2$vG`Ka;fcyQpdGz}a||b$I9^<(AEQEm2deaEsS8zvdqW9Uwpa*MjvA9H{h*ih za`*p^6dFn&Ab6F2xMOLCBKMHW{mjet3NsYBM^x^YUanV|p~yX|a=-R+y}}Gd?lD(o zFF&mC@Jb)^N+$_irLXjI8C<0^6qS*)+bg(26}-bM=+$E=3VOM#yGx0)^WX8( zcY4|UuF}_cOs@5k{I1d;?3mo-CHY;YKh`n1%}eqdqm`B%}^wdsN65TT(2-g zk$Y6-e(mLYg&B(6V=8yKl3Xh65}FJ~c9P&2ZZF#_%~0g7P`P(_xn5z0B6qdQy~oS- z3NsYBcdFd=UanUdQ1p-NwJQ5TFWW24P~>h>xsQ3dUSWnJcbm$6*30z@GZeWyRPJss z*DK6WE<{t*t%l1m|Qc0TetVg&c7u@UR1f0o@q>)(R(Q4sodwexIB`~&81>PJQ zI7&6h$ADQuwg&Vqlp|@KC~ScU$v?h5g+ndbq7Lee0Z0ZKVdU(fSr*rnb~8LZ1{=1P z7Oa%|(y{cbR-vuhYOwJGFzG$+m`nzwNiEmK^oY`b@Xla4CIFqf=GO78+$u2!v+0YyuU9l|$|IHf|h!ELI50&R*1 z^@v6Dc z3D{5LhNTM}=H*zZ^(A4kRp!O%V{c#ItY?aMKc0t#engF9^wM$`sc zpe{(hCoeO^JsKm7J|Qh+*7O_~Z(gX`FDIGdfvSZ)3FdlUQf#^IHe31Q*jDD zX&a|bFkJLg7%o67jZ-jO;PMiuQihAGJY8T#oMH!o?AZj8JPFl2VxB+(h&FHX63g32 zN*QV7yFuvvkogV{CK!)4O(zp`R0-N4HRByxC=Sp!Vf61DYBm_jY2=a+Wwx!L1-KOq zV4LF&JwfHTgldgUIdUk00(@B-_zonwP9{w*SW%c>DcaBjT9`#dC`|-A$!Mg>ggzAn zV$()FvQD9!44U|$E~V<)8Z*#Xsu_d?JT594Q9i{Pl=m3J<<&RPO6!&e4Z=@;qO$(l zFiwC&=Mb-nRo^w5Fw_~re>nId-{-zPGhI8LbsA9m>nFVg{T=+VUs+-YQ&*m}9P7nl)8^%DJc z!EO_f0{qn!yj*)tM$ECb6F>@xp{^{((UOd*Xh#$zn$ZHNCkJ6cDxX%GJabSa?=idP z?OL@f2|Z!0rUuBjL=XX4`_1CKmrl$A1CZtS^~u}AS!R1Jl{MN|k$*R{K`%A(M;PbD zvLQ0Mliz5qlehZ1HEbiQohXt1fGSs_KPI5&LGm`?=(RBm#fdiz+99l;t75iZs_zxm z+WFKToKR7vU4oJZjS3*8+JtHiG}70F((?CrcOW$abz$68qiNMD1Pe3$dm`3DN9uZRw&+mnE9E)kt`M`7jp;F}Y{w@tC z)sGrQvRglPSO>gqMA{|Mm; zZ4x?>nc(A4WkwozNMnUc>P6A=|6GU-0-Nf4Q(- zE_fYkVz%rDEz|;Y6iXO$bPzF=n6gpfriOly!;xi0q3(Q*ky3={&Y(tX6BPx3rs-zy zdxdC(@yAjKFnuD}Xt*S9G|ne6{yUk@9Q+?M9i5ScQX{V3f$4_@%wZth#`GiLw8uC4 zgh9(pr}!4e;WL3yS~~vBBZWESltp7ANQO=8X-ShpK5Cdy(Lbawh6T$U&0k|$B2;Z0 zpfNyVaw1%9@PHsOArYxI_R6MkkvpNLNTo(8M03#+vn5>2cciWwxO=*HSY5<)RSQLg1<>I~8Hk>jlsl&3_F7l{#V ztAs(;I3}T5BOptv)N2A$@f*@dSdq%e0n?ql4jM+j66x-qxG-QVl+Y<5EiEio<?ni5&S`nibigN{P9ibQvQ+2H4-WQh36T2`~7Z{fbHbs@0lWL(gX)EfK z3zo^!;b0I?Y>wp!2o55tnZPVIYO0ON>T683F%4g+cO~cuZ6rm_Qx+*BrpXU8ie09d zmv=5m>jO<#Uf&rZ5^*S4%HU$gs2F`8L7}ZoG)bd|0Rt-uSfrG{HamY zH>5A4r+W%1O9V*9Qi8>wukk|nT`QKMlx{~!Q$5)Mid*Z>>mXaPjg+{<5^{nZq;$iT z7&?q9jV09ZM7%JeCV*Z)1#)Qs0m9g0+QV#Mby00#U8OH52;R!|#_SYB%iXJSA4u(E zLQ)_#ZD4_4xrWi9l?SN9(o46qT7n~@LCk}bK?FcC}Nr|G565XZ_)g&S|92F^} z@dg|!kVi7R4KQkGWYx|OER{x}0uccW!bkJk&%%6lBX&PKlN*R2jI6eLWYg@UKCn+S zL=%w(x-K6cSJ)SU9CFqzcrtj=+MIxHKtZFf(7KJrh}ag4o7O7%s5Q1qsUz}M$il@R z&%z}LmMs!ps4I)Qg6Kh8JWqh_tIsYGffcXpN@~_8a_87}VvPJ^OP4O#eX;&T1@szj ziw_eJaH*WH=g3F%28cEC)4Wmc?NlhPlN=djx?=AeA32RyDgz9JZDEmBZom#t8Pt){ z!l1(n*n-KyHZ)$KlsC=5U1f&=2K$TohzW@B%McCDJ8LVX6u)qaVv0O;Z=Q6mKsGEE z>t4b~amD~=-XB*!uon?Qjghzr_JoCp9@5qwTtkbHpMq^F)7lMy^q zcd?$_D&IbDGD=napb~#C`@sX9xNSujH*KQnPUmk$?#}az19#(W4LmM6ttnT!o&6ZM z8#>SH{$s`meC1KIfE2~mJhl+KK}kV=QN+{qoUX|)i>P6RfFb|t{08x3`9b~^agQ8Q z&=piqE+~;7p1-W;$rv#&Pr&hpiKE1A^7V-&;|stQ7%;n%m=?-UB%#H`h;Ys=oMWCM zN1m$AUb&>8qNhRIyte3T;AqHmBaWy3Y0FaI|2VEqlCKt&>Pwc$FAK(+M1Ig%U8c5@F{UnhMOH6%WAafRcpGLLN!L4&jvum1V zE7s7HxPHX(Z@&7+7a#3BzW6#jGUCwAUGQQi0oTfa9(7Dd;PKz$t6pduUNen zfy-ry$OH;A3L6p4S$5>wjffLMX;65IWzgqrV*GXxeq1n&0FE7m?H+_UC*_X|Ps<7+ z)B^r&-9&|V<5Ue_!(t*0R%|=SiQh@{X3U`VFK|#F+>@#hjnv?-Y z=MD_2B5R6l{oACRUUY+djM~I`fE-eb3G1KSMTimyH7`Z$s8i`B$oz4FUV_*1sFz@4 zBJ3r2$&GmlT40=zmtaLgCwr`ap)Yww*P-q=)TwQhYfzK5AP--;@RkJ4dW=5nlOV?D zAbdCM&GWe+tG!Zs4b!7D#L*H8zO;3P9x6pnj8r;4@)98jXTKVqFb!mtS=26=@%KE8k98rZs;AEMb zWG|viwUteMTgQ@eUU5N*k}ULqBO}h<4)RGy34G2mhJ7L*EzTX45*gM$ojWw9WQpaR zY8_Cuh*^+y)zT5KrHEZCUX)$p6XgawU%VoB+JoiKa=IfF^jyvb(7HLfb@;w4_rk8M z!w7p8x6~p9kplj=$lv6aqV(6feerjEUalOTm&IR0%>`JZ0lcw3+h%m3ak2g0}uue?*HH&`}FNnVKZuskJfkUN-h`#9}iQ zK0GSVOx!PiAwNp==~DtGM62{3cm=C;o91VgUIeEa%_bM&Yyk-Yq{q5dR(3C+)Q^Jr zReG5!N0reVRfhYcB{HjxeENpiP+OTBRV(m5Ac#J!E(VVNK^9GCHKK_bc;AV4P(IYX z$_>H@4#7Htkl=`xv)n5HcR3z(d=MP#Golp6jy4nxVNL*#70{KK4sMHTJ%Mm~gmXa# z;Q6z0KCRS%M>hy);R|jasUUp8_ZveBDfQnK>cfsWQPNL7XC>MSqm3xHp_}nc8~Za_ zJZ2LVD$P$>m`{F0^?(h^+Y#&k5RT~EPkkdZ0NCdq3@ace<-iqa=O1~2VVEc!P)%1># zAVe+sQm@|nokD)rYXTv1M(;k@i%PZZV=*9}+4zJUFjMgfK{z7pC=GiMqff)$$s2ZG zDGxgiW5Q9g35sF&@vvvxzFCQE;6uY6^@bg%dwAFZ2Mohr2U!3DERkSVDWV#*i^!jc z@EKH}NAPLcewrU>9*m8mA>b3Tv+U3;J32ZRmY0>3xH!7xw__=;64@*%-#OMN4KkFDW4^fozahOEP3^Gay9r>ymueNJ$F@z63ZRj)wPY z3IaiX;EEHG{8d9V@)yM2qAvveNU5|*8C2P1h#!cKVe&`7u9Gl{X3)k@#ECd}zP1Z? zl=}(cr$wAydnx&>m)ieodMZgNr=PQpq5D#0sD@)ZyE;I3P_xeI&QWeYRaS#gq`FM? zNU*5uY~q3`;34j+#95JE9qi<}iAYNN)TA&5&-rxK>8Z-RY3dGS^I^vXtuP7py( zR%Qve39aHpJr7HRX`y_tNEdis*2~lg^@43E{57pT1c-br=k?u^_b`2X-V^X(Z_au| z_A4tE+vJ3@+$izIdT6vVJKe6bM#|ga8nC$?*zu_HkJIAfaak~6*qOYG3OE{U z%T{f{0@iD6t*>D{moQVFBsO9KPoa94wxc8wXCp-){!K zr?38S`+?JOviW{$Hih$_s|v(&8L5sJu3}rJNDIQP?y5h>3yZ@dljY)Du~{f zj@}KZ*h2i^)1i^bHu|C=%{- zI632iB&K|$Nm7x!cVWoKiY^ky~YtWXsr}ne<&IxFB(SnJ;z<{(MLU|W$Vs$ zIFn%e(FyOyfM*9b0T;`QX*k!N2=NrMhR_I*(9WX+*g8m56bnUxvC-+*OhF@CN2Ce7 za1O-Mo4rR~G;B1K)w*E=uo}EQtS4sYSHrsFZ}IT%-BSUgNu)fn zH-%%s6lAD{QP|A&4QmPdN4A)ea^NH<#ap9w^-V{;;#_=$RIg(VL5+f z|BNt&Bd`&T6+yGZa@)xAz#Y_#^{hNRvS;@QWg~1yssv$?)dosNFtD_J{pD?{T-m66 zH%tZv?iY|t;M`+0#;FI`R`H-wV@JrO2s?KY*oMW8<`O}yxv(&)3OQ%OdWMKY1;Y_I zV}(4&wgAEu4WpFlY-g;VV+dceaUN@jWRNFF2T5}9dMqj59MwzTo|OL_Rdm(k?WJJK zQ%g^zLFiD7={%VR$#D9qet|I>?12V3n|$cDF1QK048RZ*ug8;eaqYybcBHkWdV4Aj zqIyfiJAR7ZIJ-k{+(d`ob|mG{(K9X}f68p7fg@c4PSf25iVbNAT#UdM!lQ9ae}qD8 zj4;_C}3*$t1y z2|AYAZ-6F+$MQ>g$(U}Z?Ir1O`f>}-4o+-hf!RrQwMZw;x&LRXh-R_nD_?bbiKpdJ zr%>#Y(GjKcFJmqfN91{Rv$HoXLrI7Vrk|2*Ca6UU+CqvLYqVkZO}X@x^J(k7>Sad%C}c$8}}^Jss_v*Ia6PWv@m zWo`CZ{og?EbhF{`equz0bH|%_D`vo>T2CoJ-)e_SJ-fH~tL&3q7~l<_$VKvvNxe({ zNbR6IAdXuJ?WX~t`=MT}S1B8MQ^-F~yhi*<&YW~{?otJ_{zJV@%<)JS8Y`@@UL+9L z#BdY+9#geQmgc-hhUG&eP$ap(@AAka(wNn=(+aM^K5GKvhS0|fIdoQWvA-6JIB4g+ zF*1ZP;YltLv4BbTlKkPU@uzLP9S!0L+EdhqwM(_s*BApu123y4PIS>lA?G137_gp_ zU(cEe&00UZOK*iL$_0TcUQt|b)k-ujTBQ;8NNu}aJ}|qqOIv;J=pofnxmE)Q;@F(w zo`tP2+bsLdDed_J6@iL29mKtq6Nc}S_D}4ntdxuAq@kfHG)#rYZo=3@1Lw)GVKb*k z&Os)_wjTK}5pcg30@RFhWQnIMDG3`EOl#vh*kHZH#lU~z6&c}Taey#$1Y#tGx17|B zWqL7X&ja?(V}!2d&DrlNO@&|YSlC&c+DEnhk>C4;DG#>PcI6YG&&tMIIfObKw2)saBLZ=~OG-Z%UnN6<{r&b_SD4z!Ywv zi25QTYKRy7&DhbDM=3tjpTN0Q9QyLkVbje%PVuQ*7;~j{F*>*}KUz?MGpOVlo^)PT zVWQ5{Mf6|L-9MQBy~J z9h~81)KA6NT@58bN&+RS!qYyXWm!?g=AjT^Ixr5fn zv2?$UofsVRx5YW?H4BSD5Tir;2)NgZJwKjCC_pi2M7Y}y&kJgZ(mXh%-2)J17;0cw z(Du0`pNKjmDs788Kwz7xWAvy85N?pFyS?z-Nohfv<~KXUVTwk=Hlht6buEzaKr4I~ zK^?G1p7k4^%zWn@+Udjw{BqU&+|EisQaH4cBA=OGF#M!eF*=|}ML!5B#63^ONcA6- zS7J{I_@4xuaL$6|LL z2lqQHk?wb`kyz+X**9J40Pk^jnh=2eW=?@W;mtIpqnsL!J@jBAj=uJrzt9h1Dcn=85 zk@%5))-I^z(6);yW-%rN-3GAUlpkHwL3d(6(M9&P11?zynweNNla)%)p%MsxoNi3r z)1YDGOk||pXc4fiXqh1xRzXiez-c7~vG&@ExhJVs68MyA<>}4x!78&|xhuumQLoaa z0MdCUsYul#OQnooo0FRviFDSSuX*9^?yQz*20q-{rs|CSG`{K%4hCD6Jv}l=3IYT9 zfSlZPuJJ>}O!rU9m8~sy*SDywUPFcvr@JeC z{97Cd#U+!wfhMV8KE(;P;C?ogf|HBu>$WJgeK>!hR1L}|)kPTQBBo>*9jb#+a1xDp z#HhiJSD;MOoSp93jc|=D<1Qd0JNl+ja%!+{0vjqga)yT#rf)Q%=wl!zQw{gwu5o#3Bj@XaY6K% za9Q!v7)dw48{`yOL2*Pa9Fc~sjpGkE5|qW$3pC?i1+LQi=q{R#s{+A925(j#zh*vs z+GLVcBb-JwK^2-vFn#2m)nDqmavuL;K;Vy|QBhD`SK zZophS16wz3jWH8&F@Ts5>3}H|8DknL>DHl*I5zgfkva|N=`4@(tL2*zq?Ehv?nbXe zcV9rSt~d12*L*1JZaB?%D2fX%vbIZaT!#o}+X5S&!ux0V1T4AuJ2`HMAOYw-!RJtX zq%*O&`e|1g13o{7B}zDU9S%*v?f^r=Q95#f>mLH)FX!MPY#wWTf2|F4L=XroaC@o4 z48rQt4m!vn7a^>6*bavAS(2oVU>+S}N_F%GcLX68*2gq-6zYS(4AC;^HB^wNj^C4M zzZ#Rt0CQpb{h3Y-3%0{tG?2}}Xgd(FEQVPfU}Tcu#666c<|`b1A?=MLbcezeO>-M@ z9ECo)3@+6n@YM*G5(vOj5v}ITZve^V#`#*0yJZ&z`1nj7j;;*V=!P2@PjSHc7-qVv znZ|_O#DoYUqOe(^Ud;C8gWO=c{Rs460@aa=j9HF}jriNc_eN@C5K89|0h~j>4pUNh z?mHTGRmSQ~2>Hw#%Y~Aw@%_PUFOfvz-d2^^_FhY)bFG*0?dV45pTD1|Qb(5!g4IiF zyat~Sp8G;_7dcR^V-D*GHezO@&vNar>p*b=r}W8`)7^6IFAPAek&H0B#==1eqLl#R zj{)a(90($t-qUC>&4|dLa}WK}0R7?xU7&jY0knzLmR2nvXFAD^09l`qq-dmZ(KGP| zSkcu`oir}(i@H#`Cac_zUD8R{QxU@vnsjo0b$2>BxK70BbZRJum!gJ_H_>5~Hfmgt zoVVy_o>Js&xThmIZ(&ToCpjlmLtRpo4zxpy^RZ}(>8W86ZpuW~%d~&pOQb+YjR7j) zKDdb?3g9QEXk@SoKz4$3pXDnmNQc*&IWmv2rLxXy#?jk7rg4}Ba~h2ipG6B_&^Sh0 zmCRa!H1@gamY#=78YaJ8e`-wD^D*5tOx~x0-yai-T6mbO*O@IiIRYi8>_u{>5O@)o zTuA|vplevcVAGHkOdikLGzC+@fQ|~LE5p(h3?_FG!#e7hLWWrjak;boc3&5Cl=nRp z49c8B!Q{0om||`{t>tbubWo+}2K^Fo!f+jt7IdAk6Q$W#E{sEo`sfBIWY}Sg^{mVLnlzssh!B4Ve5ZXMfV6TR7O#G~yuf#>HxL*Z! z;Rt$GAJns-tUY)oq-Ff1p)e9{+2s7_6k=y7#YExL%|7g{CMj}f-+&)5@*zI@(DG`- z##BR!KJ%SjONa)<z7<497Vi9C5Po(++|tJr%oA zoETQ7;kQP>Z(Z>lW)krmuhB8Sf`)Ie%W-t&4{bu<|F5#!`7VBcUv}5_*>LMASZ$`x zD|t+(Dfl~*3AY z73nB`boH64xR>fGXRpaL_mZLQt{GAYX&|HDS)yBqXcjBkFV|uTL%z4BYd`eNcYUDS z$XJOc5DYZ%8%Xrih3UQo2AYe?!rObu33t!^w=TfUdj`of?z4isskcbvO1XLCpn<&0 zpmr*O3UaWULduJ_Fx&PR^tSzi$T3|vWv@+VRskzGHCh5k_7Ffo3ctMs^&52H?%+r_ zetwcB5McU4ixc4y_KJ;YH!Sbo6z|SQoKe|?wSZU`orVqBzS&UMIO2p=A4ihqN1J-} z`4b^ZaWdFTwD`i-gQhnu<>32hj-xsNf0C7(&-O9)^4iUPa_LJ`iyG7roCaFS<+?42 z&fKI9-Ab;z0Ox|(!Srs({QSY5nJ1hylkYy*x6=tQYFo;!y{x}6dgR^Ft;@eB<*QqJ z$j`Uf*o?{Cnk)F)P1S5+x{x2*CdCA!1BkqX3OmSC00>>phxP|$n7CjW@3zYNtvRs0 z&GFc&@KIi!bhqZo&JT6U({k**Y zks@l~xktwOm8C8}f5<)&r(xSx>bS}9+P2CQa{`Z^BmPrPdUU7$&!o)z<$hVWtHW{0keESe8jhL&lH zBtz#$W%l;$oFJS8-ZWj@m|iw>yEOMAB($clyOP|$A-NhaKI4& z`T+-@lSv_Km<&8|C`8AuJD-~6S?GOX@_}1eCp~hhBd|k>F!1(~VUHjPl>(_82BPbE zXj;c@1T0@qBR5?u)vl*hwMG{(kox9bP5~LZ z8!-m00=bbYh4FK4KzD3d;d>aHM!5gz+?WR4r7@U}BH4|uLe=>@uShzE*g8mM*`9zd ztx-Q0i?5O7VDN=Cu)v6QjTXYaC;NjYKK-8SfscS0<3gKh$&WcjC^30t>*2dY=jgjD zN;wZM!(U{kI*%1ayHM<)Os>7Zvs*~NRl#}>%~G*4tS3+u9b;y(E>ZlBEs^AG`xP~s zZ(Wa$wOB#4vj^YH@InusAI%qTaxLe?5QwLEGo*V7t zRd|5mojiC>G~0te-T~ezn&rXwGCad8pUpR>iGX*~;chG|%14ZlahNkw9a}j5tSCO3 zULlsLej5VizwH3eh~ls?b7(w|r#Ryb57P)m&bY!q z7@p(7!+edI%HQ$^buiF_hxj5o!FMve%!3EjEg8W7#PA*-JfK2HfUnxeKd+WzkzXAY zL&m+Ny4xu5(Rp1p_6#rb8Zv41W%%n1_hbTIa;gFembc_6aiI!iMBrD3XmaVLu5Q!S z5M8+}wB}Q|(85Hf^PlX;&{+)vMggSR#wQTSo1iJbOQW;aY;({b)4B0BppJ}`w8xRa zM58|=)w+kw_S1TkX%`joz?4zr93b7|RHM*7tphy!-fdiL zR9;U>M~l2D4?i#-{xU5iaj2HKw*9Q1cM`BhOzV)mWPOiuzzMf4paby{!g50|)`|2| zE)J}iP@BokQ5FiGb45~~s1FmI+$FhvegACmmQMB|GVkozLmmjQ2gcV-cyeBgZ zho#!k2V5Dhd>4%nokr)0_9{$?YfyY-x25b^>=~xpvuN1wB#sQ$uB*}y*Kw$7A zgd|9|fQ0Y@5IH8}j~BX+eF7+=Uvy!BzX?4w%<(XdKFK9|kV+A&9mHZdK_?DM^i2fk zy6Ov{ZC-~DE1gFmCmmb&8LslnQm((Ed&Uj;t3I{WE(`f@mHz-IvsbS%P4^3I+RM$6>UY$ z*Pmu1A7%iGTWeH9tL2C%M!GAhD3477EI|EoEo9xIN)Y4m52qW6rRXmT$fob8kif|; zuoVo_uu&-}aLJkp-`<)VnXGvQRMT?WlV{g0(RDh++nqY&GiSOoOi+^LjFEsrL#ZeX zd7Wr4v)gQy9)R>{biUjtzj(4ZyNrG;%_gl?s`p5k2*XHw$LW)x(rhFU=Ej-_`XCSj zgKZ+k>W@5n(q6ba1U-k!xI_iIHD^8BF)2SrLtm-0YLQ>atxp#F7(Mygj)bl-kg=zF z=<5&2)jJC0xTi`_f0a5Ta|0Hs;tkX+DQxsY?i(cCW>?K2YbHoe8}6fTd8!b{-u65- z`4l^>w9!?U&JK`iP&%>SwBPsCMm!9J%b7J{7jkKg|aBmQ9mc z_#HSKbYi0Zgam=W_}K){u`%WTXLb^$Yo0xOcsd_(lhz{?Zr=J--t=5$lsEGEXA1$?{oFHRl}tWAaQK1WqAbo*LxsSM zE1C_vzqQmjO06dXBQ$FRV@s-v?!fKm(m|BwJo)G6XXv{=kQeM6lA{W$Xe07y; zJX-$C=|Xe(|Dj^j^dBWIub5oayz~OsQyI(9*hK-jvp+rr9&DtiNh*%aoSZ`suS9$`=i) znp!omeBO-mtFM|nv+3%V@;NOFXH1!W)$~fLL+_U68T^f(X?UrJlrQF#)X%6Iba{RK zY5iuLK4`}D88c?~>)+5&eOkXk(=Q(|y{cjGfcom0)t3*hlKWn)>~RtiIu zRYHu-O{c^YKzdcV!Sb#F{f#6%bWkc zP%c0Ahl=_+O$+9>HcfAAn9$1g{{xmRZXrf0-w_=7<`(9OKV zkafQqu>H%o`wCa{3t>X`#Kfnh+Mt1UJxttbqyAa9-`5l zrO(wLF&@>Q)%WRd>TgBg4!xtltN&IU@_nrTUi`s4qJM55HIM24@_i+uy@#H0?)X*r z-FN>FZ;?NF;FnL|@Tfl!sv3UA1%KWDrkRspRegbbp}XbbN1i+VQ1*>C-FBZD%gD+u z?LTnHsM@--&mBLr;pUaMu6p8ymv-;@)jLz3c(Sl45DZ6hI#&%IvT5^y_d?aH*K7)e zhn{iyRjY2#YMQ$9^Di!*{?yZ7etrD>iFe&yQQ5m>(!Fcf{e1n#O%FZ&>~4P~n%i~A znWN6zu<`X@uMHG*N%TD9%#YkZeD=lhm-m=<_ny5<1`HZ9=In73&YyI_lI2!z?#0H$-Jca%oqie`b-{Bh<~;*EiD4 z=#$*y?_u^ZOM(L<=Nbc}OR7V8;b8vIQG<;c!BD?EU)(7474{lrj`dZV;eZ-278g5l(b%Mzm^VSlXC5P#U8Q&eVlPChkk z=K0Yvp>XY}!ZE?~V{Tm_d_iz>A|vdt4RMOS}@8C%*FR3Zc8sZa6 z_V-D?)7KQqT~%P$q2xbG$C+VMUzRm;-0;|>L^Dmx$jZPnO?$+nU=q zKl=1DFYkHvwGR(}dR#MkVpI^uCa);4X1(!9BBX2bF| zci;Q!8~b8er9*~}s=M%#%cjn3xOL5D)Oh*Tj}Cu&G?q20Ze~Mr`7fV!pWpfRyGQ@L z?D|{QZ+L#^%dhPF?fYZyeD2qK-q=@n?)VEYx@_uAx2<~gi6?iyu;-O`v+_D$GUf08 z`1W{m&ioHQ$|#=ORMd6qj}|}t$cG=D^USk(ox2s+jy`uhO`XN=<1fGU_Q9in{#$d) zs@4U)Dk?WV^5o7}_PzVjU0Tgg@9ej#_>JS|j=%VlK+w&!dRKn_#oVUq;b)E*b^a9# z_P)CR%>(cK;oIYyJvFiPBXjA;HTJm5UT0{%c&ctU1& zU{b&^i^3rzXao!$|4(31(}(}hFp-h#J2y}mxGXvy5`6x-5TYbcort=Tv)+ z+35C6?)5F*W_0l{{l>T`kQd4ik=!+6zI5?l6zJ=#4VU4E@`TYpQf79+E^YEbWR1&7 zeiXC`mAUc(n-E zSNDj;2W`z*H@GrCKIE_6;$v$Dt~BH8$reTei8L+4srnnx-YB{5ox+|#3%8{-&Gg>1P-oyt z{X;=5Q(p7=(BWTW`Ja!}OjMx~DN3HjH1ny{U{~4egS_%o?!K zdT<}lAM7LZ2kWc1N5EuDun89k}|b@=YFJ@#3(?xxr`7exvHw(z8wmxb?a zJTxryFNlYjnu8}7PadAmc=GX3J<6jtXqXG}ko_~~(qFw(HsMb*7C9R(oL_j$Q+=0Q zBA&b9yw9SKy?D>zS6{)F>$ora#eNMT>4Vab5+O|9eP48IgFXppOuqL;v2{8I>{67Y z-plZ8-~XF^y4%!xWka*gw%CHXGhifM(bRm^wGA^BsA*mU49BaQ=GrX_X3S`4X}NsC zY*eLxDT2D%|6`VYWqpf1x2e^h-q0}DCJ36nys6nHOBY^=rk$>5E1XDJ zX%Oh&_M=DF>ayhMUYD9p@sYmiA$}5HQ-Vp<5YI_)>6@NRJS37-mL}aGJj7e#Hk7xWgr!z!J>w#6Z)ot^i2 i32` | Must return `1`. | -| `vc_manifest` | `() -> i64` | `(len << 32) \| ptr` of the UTF-8 manifest JSON (≤ 64 KiB). | +| `vc_abi_version` | `() -> i32` | Must return `1`. Needed only by a module without a `vc_manifest` custom section. | +| `vc_manifest` | `() -> i64` | `(len << 32) \| ptr` of the UTF-8 manifest JSON (≤ 64 KiB). Needed only by a module without a `vc_manifest` custom section. | | `vc_alloc` | `(size) -> ptr` | A block of `size` bytes the host may write, or `0` on failure. Never freed: each run gets a fresh instance. | | `vc_run` | `(input, input_len, params, params_len) -> i64` | Runs the plug-in on the input JSON with the parameters JSON; returns `(len << 32) \| ptr` of the output JSON, or a negative error code. | +### Manifest section + +A module may carry its [manifest](#manifest) in a [custom +section](https://webassembly.github.io/spec/core/binary/modules.html#custom-section) named `vc_manifest`, holding the +same UTF-8 JSON that the `vc_manifest` export returns, plus `"abi": 1`, the ABI version that `vc_abi_version` returns. +The host then reads the manifest from the section and loads the module without instantiating it: no start function, +`vc_abi_version`, `vc_manifest` or data segment initialization runs when the module is installed, inspected or loaded at +startup. The host checks the imports against the manifest's permissions, the exports `memory`, `vc_alloc` and `vc_run` +by their types, that the initial memory fits in the [linear memory limit](#the-sandbox), and that the module defines at +most 4 tables of at most 100,000 elements each. The module is instantiated for the first time when it runs, and a start +function then runs at the start of each run. + +- A module with more than one `vc_manifest` section, or one longer than 64 KiB, is refused before the section's contents + are decoded. A section that is not UTF-8, not JSON or not a valid manifest is refused too, and so is one whose + manifest does not give `"abi": 1`. +- When a module has both the section and a `vc_manifest` export, the section is the manifest and the export is never + called. Keep both to load in versions of VectorCraft that read only the export. +- A module without the section is loaded as before: the host instantiates it and calls `vc_abi_version` and + `vc_manifest`. + ### Host imports (API level 2) A plug-in whose manifest gives `"api": 2` and lists the [permission](#permissions) an import needs may import these @@ -860,10 +880,15 @@ crates/plugins/example/build.sh # cargo build --release --target wasm32-unk ``` The script also refreshes `crates/plugins/tests/fixtures/desaturate.wasm`, the test fixture built from that source. -The crate is not a workspace member. Any language that targets core WebAssembly works (C, Zig, AssemblyScript, +The crate is not a workspace member. It puts its manifest in the [manifest section](#manifest-section) with a byte +array static marked `#[unsafe(link_section = "vc_manifest")]` (the Rust Reference's +[`link_section`](https://doc.rust-lang.org/reference/abi.html#the-link_section-attribute)), and keeps the +`vc_manifest` export for older hosts. Any language that targets core WebAssembly works (C, Zig, AssemblyScript, WAT…), as long as the module imports nothing but the host imports: in Rust, `std` on `wasm32-unknown-unknown` is fine as long as it never touches WASI. `vectorcraft_plugins::wat::module` is the skeleton of a plug-in in WebAssembly text, -which the tests build their plug-ins from; `wat::echo_exporter` is an exporter whose file is its input or its parameters +which the tests build their plug-ins from, and `wat::sectioned` the same plug-in with its manifest in the [manifest +section](#manifest-section) and no `vc_abi_version` or `vc_manifest` export (in WebAssembly text, a custom section is +written `(@custom "vc_manifest" "…")`); `wat::echo_exporter` is an exporter whose file is its input or its parameters (with a base64 encoder written out in WebAssembly text), which the tests read back what the host hands a plug-in with, and `wat::when_given` a plug-in whose output depends on whether its input or parameters hold a given text, which shows in a live effect's geometry. `wat::reporting` and `wat::cooperating` build level 2 plug-ins that import the host diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..f79103b179 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2655,6 +2655,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `` dialog cannot set protected field ``"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged. - **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user, the unsigned `grants.json`). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **A refused plug-in install writes nothing (G17):** `plugin.install` checks the plug-in installed under the module's id and its grant again while it records the grant and installs the module (`registry::install_checked`), and only then writes the module and its grant to the `Plug-ins` folder, attaches its settings and cache and turns a disabled plug-in on. When another session installed a plug-in with the id that would need `replace: true`, or changed the grant the checks relied on, the install is refused and the folder, `grants.json`, the disabled list and the installed plug-in stay as they were. Without a plug-in store, the approval comes from the grant the install checks again. A `plugin.remove`, or a load of the folder or of a plug-ins folder, in another session waits until the install has written the folder. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **A plug-in's manifest from a custom section (G17):** a module that carries its manifest in a `vc_manifest` custom section, with `"abi": 1`, is inspected, installed and loaded at startup without being instantiated, so none of its code runs (its start function, data segments, `vc_abi_version` and `vc_manifest`); the host checks its imports against the manifest's permissions, its `memory`, `vc_alloc` and `vc_run` exports by type, and its initial memory and tables against the limits its runs have. A repeated section, one over 64 KiB, or one that is not a valid manifest or gives another `abi` is refused. Such a module whose start function traps installs and fails at each run. Modules without the section load as before. The example plug-in carries the section. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Windows and processes take turns on the Plug-ins folder:** each one locks `disabled.lock` in the `Plug-ins` folder while it reads and changes the stored modules, `grants.json`, `disabled.json` and the plug-ins' settings and caches, so two installs of one id keep each module with its own grant, and grants or settings written by two processes are all kept. When the file can't be locked, `plugin.install` and `plugin.remove` fail and change nothing. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval waits before OK (G17):** the approval dialog's OK stays disabled until its question has been on screen in the focused window for half a second, VectorCraft's own value; a click, Enter, Space, or a press begun before then installs nothing, and the dialog stays open. The wait starts over for every new question, even one that reads the same, and when the window gets the focus back, so a question swapped in just before a click is not approved by it. Cancel works at once. Regressions: `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **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. From 5caea7ad329bd1332fd1ebadb2b7b182db6f116b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 22:16:00 -0800 Subject: [PATCH 045/178] 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 046/178] 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 5a2eae86a7fb9bae02a417dfb81bc4215bef5199 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 23:43:00 -0800 Subject: [PATCH 047/178] Smooth: a drag over a long path measures only the anchors and segments near it A Smooth drag measured every anchor of each path against every stretch of the drag, and every curved segment's box against every stretch twice, so a release on a path of 100,000 anchors made tens of millions of measures however short the drag was. - The drag's stretches are listed once per release in a grid over the drag's bounds grown past the reach. An anchor outside those bounds is out of reach without measuring, and a point or box is measured only against the stretches listed in the cells it covers. Every query gives at least the stretches the whole-drag measure finds in reach, so the marks, the cuts and the smoothed path are the same as before. - The refitted runs of a path are put back from its end without moving the rest of the anchor list for each run. On a curved path of 100,000 anchors, a drag of 200 points over 200 pt of it makes 7,533 measures to find the curved segments in its reach, where it made 19,899,801. --- crates/engine/src/cmd/draw2/smooth.rs | 344 ++++++++++++++++++++++++-- docs/target-app-parity.md | 1 + 2 files changed, 325 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..5667922907 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use vectorcraft_pathops::addons::pathtools as pt; use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths}; @@ -421,6 +423,8 @@ fn drag_stretches(pts: &[Point]) -> Vec { /// The stretches of the drag `pts` among `of` whose bounds come within `radius` of `r` on both /// axes: every stretch within `radius` of a point in `r`, and perhaps a few more. fn stretches_near(pts: &[Point], of: &[usize], r: Rect, radius: f64) -> Vec { + #[cfg(test)] + STRETCH_TESTS.with(|c| c.set(c.get() + of.len())); let r = r.inflate(radius, radius); of.iter() .copied() @@ -432,8 +436,115 @@ fn stretches_near(pts: &[Point], of: &[usize], r: Rect, radius: f64) -> Vec = const { std::cell::Cell::new(0) }; +} + +/// Most grid cells [`DragReach`] lists one stretch of the drag in. A stretch whose reach covers more +/// is measured against every point and box instead. +const MAX_STRETCH_CELLS: usize = 64; + +/// Most grid cells across the drag's bounds on each axis in [`DragReach`]. +const MAX_DRAG_CELLS: f64 = 1024.0; + +/// The stretches of a Smooth drag listed by the cells of a grid that their reach covers, so that a +/// point or a piece of path is measured only against the stretches whose reach it is in. Each query +/// gives at least every stretch that measuring against the whole drag finds in reach, so the results +/// are the same as measuring against the whole drag. +struct DragReach<'a> { + pts: &'a [Point], + radius: f64, + /// Every stretch of the drag, in order. + all: Vec, + /// The drag's bounds grown by more than `radius`, with the cell size; `None` when the drag or + /// the reach is not a finite number, and then every query gives every stretch. + grid: Option<(Rect, f64)>, + cells: HashMap<(i64, i64), Vec>, + /// The stretches whose reach covers more than [`MAX_STRETCH_CELLS`] cells. + wide: Vec, +} + +impl<'a> DragReach<'a> { + fn new(pts: &'a [Point], radius: f64) -> Self { + let all = drag_stretches(pts); + let mut reach = DragReach { pts, radius, all, grid: None, cells: HashMap::new(), wide: vec![] }; + if pts.is_empty() || !radius.is_finite() || pts.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) { + return reach; + } + // Enough more than the reach to cover the rounding of each distance and box measured. + let size = pts.iter().fold(0.0_f64, |m, p| m.max(p.x.abs()).max(p.y.abs())); + let pad = radius + 1e-6 * radius.max(1.0) + 1e-9 * size; + let area = poly_bounds(pts, pad); + let cell = pad.max(area.width().max(area.height()) / MAX_DRAG_CELLS); + if !(cell.is_finite() && cell > 0.0 && area.width().is_finite() && area.height().is_finite()) { + return reach; + } + reach.grid = Some((area, cell)); + for &k in &reach.all { + let Some(&a) = pts.get(k) else { continue }; + let b = pts.get(k + 1).copied().unwrap_or(a); + let r = Rect::from_points(a, b).inflate(pad, pad); + let ((x0, y0), (x1, y1)) = (reach.cell_of(Point::new(r.x0, r.y0)), reach.cell_of(Point::new(r.x1, r.y1))); + if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > MAX_STRETCH_CELLS as i64 { + reach.wide.push(k); + continue; + } + for x in x0..=x1 { + for y in y0..=y1 { + reach.cells.entry((x, y)).or_default().push(k); + } + } + } + reach + } + + /// The cell `q` is in, counted from the corner of the grid. + fn cell_of(&self, q: Point) -> (i64, i64) { + let Some((area, cell)) = self.grid else { return (0, 0) }; + (((q.x - area.x0) / cell).floor() as i64, ((q.y - area.y0) / cell).floor() as i64) + } + + /// Whether `q` is within the reach of the drag, and `slack` more. + fn in_reach(&self, q: Point, slack: f64) -> bool { + let limit = self.radius + slack; + let Some((area, _)) = self.grid else { return dist_to_stretches(self.pts, &self.all, q) <= limit }; + if !(q.x >= area.x0 && q.x <= area.x1 && q.y >= area.y0 && q.y <= area.y1) { + return false; + } + let listed = self.cells.get(&self.cell_of(q)).map_or(&[][..], Vec::as_slice); + dist_to_stretches(self.pts, listed, q).min(dist_to_stretches(self.pts, &self.wide, q)) <= limit + } + + /// The stretches, in order, that may come within the reach of `r`: at least every one that + /// [`stretches_near`] gives for `r` from the whole drag. + fn near_rect(&self, r: Rect) -> Vec { + let Some((area, _)) = self.grid else { return self.all.clone() }; + let (x0, x1, y0, y1) = (r.x0.max(area.x0), r.x1.min(area.x1), r.y0.max(area.y0), r.y1.min(area.y1)); + if !(x0 <= x1 && y0 <= y1) { + return vec![]; + } + let ((cx0, cy0), (cx1, cy1)) = (self.cell_of(Point::new(x0, y0)), self.cell_of(Point::new(x1, y1))); + if (cx1 - cx0 + 1).saturating_mul(cy1 - cy0 + 1) > self.all.len() as i64 { + return self.all.clone(); + } + let mut out = self.wide.clone(); + for x in cx0..=cx1 { + for y in cy0..=cy1 { + out.extend(self.cells.get(&(x, y)).into_iter().flatten()); + } + } + out.sort_unstable(); + out.dedup(); + out + } +} + /// The distance from `q` to the nearest of the stretches `of` of the drag `pts`. fn dist_to_stretches(pts: &[Point], of: &[usize], q: Point) -> f64 { + #[cfg(test)] + STRETCH_TESTS.with(|c| c.set(c.get() + of.len())); of.iter() .filter_map(|&k| { let a = *pts.get(k)?; @@ -468,15 +579,18 @@ fn nearest_to_stretches(s: CubicBez, pts: &[Point], of: &[usize]) -> (f64, f64) best } -/// How many curved segments of `pd` may come within `radius` of the drag `pts`. -fn segments_in_reach(pd: &PathData, pts: &[Point], radius: f64) -> usize { - let all = drag_stretches(pts); +/// How many curved segments of `pd` may come within the reach of the drag. +fn segments_in_reach(pd: &PathData, reach: &DragReach) -> usize { pd.subpaths .iter() .map(|sp| { (0..sp.segment_count()) .filter(|&i| { - !vectorcraft_tools::draw2::segment_is_straight(sp, i) && !stretches_near(pts, &all, control_box(sp.segment(i)), radius).is_empty() + if vectorcraft_tools::draw2::segment_is_straight(sp, i) { + return false; + } + let b = control_box(sp.segment(i)); + !stretches_near(reach.pts, &reach.near_rect(b), b, reach.radius).is_empty() }) .count() }) @@ -516,26 +630,26 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz reach_samples(c, (mid, t1), (pts, &near), radius, budget, out); } -/// `sp` cut where the reach `radius` of the drag `pts` crosses its curved segments, and whether each +/// `sp` cut where the reach of the drag crosses its curved segments, and whether each /// anchor of the result is in reach. An anchor in reach is added in the middle of each stretch of a /// segment in reach that does not run on from one of the segment's anchors in reach, and an anchor /// out of reach in the middle of each stretch out of reach between two stretches in reach, so that a /// stretch in reach is smoothed even when the segment's anchors are not, and the stretches between /// stay as they are. A segment is searched no more than half the reach apart where it comes within /// the reach of the drag ([`reach_samples`]), measuring up to `share` pieces of each segment. -fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubPath, Vec) { - let near = |q: Point| dist_to_polyline(pts, q) <= radius; +fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec) { + let (pts, radius) = (reach.pts, reach.radius); let n = sp.anchors.len(); - let marked: Vec = sp.anchors.iter().map(|a| near(a.p)).collect(); + let marked: Vec = sp.anchors.iter().map(|a| reach.in_reach(a.p, 0.0)).collect(); let mut places = vec![]; - let all = drag_stretches(pts); for i in 0..sp.segment_count() { if vectorcraft_tools::draw2::segment_is_straight(sp, i) { continue; } let c = sp.segment(i); let (mut samples, mut budget) = (vec![], share); - reach_samples(c, (0.0, 1.0), (pts, &all), radius, &mut budget, &mut samples); + let near = reach.near_rect(control_box(c.subsegment(0.0..1.0))); + reach_samples(c, (0.0, 1.0), (pts, &near), radius, &mut budget, &mut samples); // Stretches of samples alike, in order: (in reach, first, last). let mut runs: Vec<(bool, usize, usize)> = vec![]; for (k, s) in samples.iter().enumerate() { @@ -573,7 +687,7 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP .anchors .iter() .enumerate() - .map(|(j, a)| if added.contains(&j) { dist_to_polyline(pts, a.p) <= radius + 1e-9 * radius.max(1.0) } else { kept.next().unwrap_or(false) }) + .map(|(j, a)| if added.contains(&j) { reach.in_reach(a.p, 1e-9 * radius.max(1.0)) } else { kept.next().unwrap_or(false) }) .collect(); (out, marked) } @@ -581,13 +695,14 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP /// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach. /// A closed path whose first anchor is in reach starts at the point of the refitted path nearest /// that anchor's place (VectorCraft's own rule). -fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f64, sigma: f64) -> Option { +fn smooth_subpath(sp: &SubPath, reach: &DragReach, share: usize, tol: f64, sigma: f64) -> Option { if sp.anchors.len() < 2 { return None; } - let near = &|q: Point| dist_to_polyline(pts, q) <= radius; + let radius = reach.radius; + let near = &|q: Point| reach.in_reach(q, 0.0); // A drag along a segment smooths it even when its anchors are out of reach. - let (sp, marked) = mark_reached(sp, pts, radius, share); + let (sp, marked) = mark_reached(sp, reach, share); let sp = &sp; if !marked.iter().any(|m| *m) { return None; @@ -693,14 +808,15 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool } i += 1; } - let mut out = anchors.to_vec(); + let mut out = EditsFromEnd::new(anchors.to_vec()); for (a, b) in runs.into_iter().rev() { let lo = a.saturating_sub(1); let hi = (b + 1).min(n - 1); if hi == lo { continue; } - let mut piece = out[lo..=hi].to_vec(); + let Some(piece) = out.get(lo, hi) else { continue }; + let mut piece = piece.to_vec(); // The anchors outside the reach, kept with the part of their segment that is outside. let (mut head, mut tail) = (None, None); if hi > b @@ -725,9 +841,49 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool if same_anchors(&new, &piece) { continue; } - out.splice(lo..=hi, head.into_iter().chain(new).chain(tail)); + out.replace(lo, hi, head.into_iter().chain(new).chain(tail)); + } + out.finish() +} + +/// A list edited by replacing stretches of it, each one ending no later than where the one before +/// started, in time proportional to the items replaced and moved rather than to the list's length +/// for each edit. +struct EditsFromEnd { + /// The start of the list. + head: Vec, + /// The rest of the list, last item first. + rest: Vec, +} + +impl EditsFromEnd { + fn new(items: Vec) -> Self { + EditsFromEnd { head: items, rest: vec![] } + } + + /// The items `lo` to `hi` of the list, `None` when it is shorter. + fn get(&mut self, lo: usize, hi: usize) -> Option<&[T]> { + while self.head.len() <= hi { + self.head.push(self.rest.pop()?); + } + self.head.get(lo..=hi) + } + + /// The list with the items `lo` to `hi` replaced by `with`, as [`Vec::splice`] gives it. Leaves + /// the list as it is when it is shorter. + fn replace(&mut self, lo: usize, hi: usize, with: impl IntoIterator) { + if lo > hi || self.get(lo, hi).is_none() { + return; + } + self.rest.extend(self.head.drain(hi + 1..).rev()); + self.head.truncate(lo); + self.head.extend(with); + } + + fn finish(mut self) -> Vec { + self.head.extend(self.rest.into_iter().rev()); + self.head } - out } pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { @@ -743,15 +899,16 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, radius)) { paths.push((id, path_of(&st.doc, id)?.0)); } + let reach = DragReach::new(&pts, radius); // Each curved segment in reach gets the same share of the search, whatever order they come in. - let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &pts, radius)).sum(); + let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &reach)).sum(); let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1); for (id, pd) in paths { let mut changed = false; let subs: Vec = pd .subpaths .iter() - .map(|sp| match smooth_subpath(sp, &pts, radius, share, tol, sigma) { + .map(|sp| match smooth_subpath(sp, &reach, share, tol, sigma) { Some(n) if n != *sp && n.anchors.len() >= 2 => { changed = true; n @@ -1127,6 +1284,153 @@ mod tests { pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect() } + /// A path of `n` smooth anchors 1 pt apart, along x and up and down by 3 pt, every segment + /// curved; closed, the anchors go round a circle `n` pt long instead. + fn wave(n: usize, closed: bool) -> SubPath { + let anchors = (0..n) + .map(|i| { + let f = i as f64; + if closed { + let r = n as f64 / std::f64::consts::TAU + f64::from(u8::from(i % 2 == 1)) * 3.0; + let a = f / n as f64 * std::f64::consts::TAU; + let (p, t) = (Point::new(r * a.cos(), r * a.sin()), kurbo::Vec2::new(-a.sin(), a.cos()) * 0.4); + Anchor::with_handles(p, p - t, p + t) + } else { + let p = Point::new(f, f64::from(u8::from(i % 2 == 1)) * 3.0); + Anchor::with_handles(p, p - kurbo::Vec2::new(0.4, 0.0), p + kurbo::Vec2::new(0.4, 0.0)) + } + }) + .collect(); + SubPath::new(anchors, closed) + } + + /// The same drag measured against all of its stretches for every point and box. + fn linear<'a>(pts: &'a [Point], radius: f64) -> DragReach<'a> { + DragReach { grid: None, ..DragReach::new(pts, radius) } + } + + /// How many stretch measures `f` made on this thread. + fn stretch_tests(f: impl FnOnce()) -> usize { + STRETCH_TESTS.with(|c| c.set(0)); + f(); + STRETCH_TESTS.with(std::cell::Cell::get) + } + + /// A drag of 200 points over 200 pt of a curved path of 100,000 anchors measures the anchors + /// and segments near the drag against the stretches near them, not every anchor and segment + /// against every stretch (about 40 million measures), and smooths the path as measuring + /// everything does. + #[test] + fn a_drag_over_a_long_path_measures_only_what_is_near_it() { + let sp = wave(100_000, false); + let pts: Vec = (0..200).map(|i| Point::new(50_000.0 + f64::from(i), 1.5)).collect(); + let reach = DragReach::new(&pts, 12.0); + let pd = PathData::single(sp.clone()); + let mut in_reach = 0; + let boxes = stretch_tests(|| in_reach = segments_in_reach(&pd, &reach)); + assert!(in_reach > 0 && boxes < 100_000, "{in_reach} segments in reach, {boxes} measures"); + let share = (MAX_REACH_PIECES / in_reach).max(1); + let mut got = None; + let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, share))); + assert!(marks < 100_000, "{marks} measures"); + let smoothed = smooth_subpath(&sp, &reach, share, 2.5, 4.0); + assert!(smoothed.is_some()); + let all = linear(&pts, 12.0); + assert_eq!(segments_in_reach(&pd, &all), in_reach); + assert_eq!(Some(mark_reached(&sp, &all, share)), got); + assert_eq!(smooth_subpath(&sp, &all, share, 2.5, 4.0), smoothed); + } + + /// Paths and drags of many shapes, a drag of one point, one far away, one with a stretch longer + /// than the grid lists by cell, one with a point that is not a number, and reaches of 0 to 50 pt: + /// the grid gives the same segments in reach, the same marks and the same smoothed path as + /// measuring against the whole drag. + #[test] + fn the_drag_grid_gives_the_results_of_measuring_the_whole_drag() { + let far = Point::new(1e7, -1e7); + let paths = [ + ring(), + wave(1500, false), + wave(1500, true), + SubPath::polyline(&(0..500).map(|i| Point::new(f64::from(i) * 2.0, f64::from(i % 3) * 4.0)).collect::>(), false), + SubPath::new( + vec![Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(3e5, 4e5)), Anchor::corner(Point::new(1e6, 0.0))], + false, + ), + SubPath::new( + wave(200, true) + .anchors + .iter() + .map(|a| Anchor::with_handles(a.p + far.to_vec2(), a.h_in + far.to_vec2(), a.h_out + far.to_vec2())) + .collect(), + true, + ), + ]; + let line = |from: (f64, f64), to: (f64, f64), n: u32| -> Vec { + (0..=n).map(|i| Point::new(from.0, from.1).lerp(Point::new(to.0, to.1), f64::from(i) / f64::from(n))).collect() + }; + let mut loop_drag: Vec = + (0..400).map(|i| Point::new(100.0 + 120.0 * (f64::from(i) * 0.05).cos(), 120.0 * (f64::from(i) * 0.05).sin())).collect(); + loop_drag.extend(line((0.0, 0.0), (1500.0, 2.0), 50)); + let drags = [ + vec![Point::new(150.0, 100.0)], + line((40.0, 90.0), (160.0, 110.0), 30), + line((-100.0, 1.0), (1600.0, 2.0), 1500), + loop_drag, + line((5e6, 5e6), (5e6 + 10.0, 5e6), 5), + vec![Point::new(0.0, 0.0), Point::new(1500.0, 3.0), Point::new(1500.0, 3.2), Point::new(10.0, 0.5)], + vec![Point::new(10.0, 1.0), Point::new(f64::NAN, 0.0), Point::new(12.0, 1.0)], + (0..1000).map(|i| Point::new(f64::from(i) * 0.01, 1.0)).collect(), + line((far.x, far.y), (far.x + 300.0, far.y + 40.0), 80), + ]; + for pts in &drags { + for radius in [0.0, 0.5, 12.0, 50.0] { + let (grid, all) = (DragReach::new(pts, radius), linear(pts, radius)); + for (k, sp) in paths.iter().enumerate() { + let pd = PathData::single(sp.clone()); + let in_reach = segments_in_reach(&pd, &all); + assert_eq!(segments_in_reach(&pd, &grid), in_reach, "path {k}, reach {radius}, drag {:?}", pts.first()); + let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1); + assert_eq!(mark_reached(sp, &grid, share), mark_reached(sp, &all, share), "path {k}, reach {radius}, drag {:?}", pts.first()); + let sigma = radius * SMOOTH_SPREAD; + let want = smooth_subpath(sp, &all, share, 2.5, sigma); + assert_eq!(smooth_subpath(sp, &grid, share, 2.5, sigma), want, "path {k}, reach {radius}, drag {:?}", pts.first()); + } + } + } + } + + /// Replacing stretches of a list from its end, each one ending no later than where the one + /// before started (sometimes on that item, sometimes with nothing or with more items), gives the + /// list that [`Vec::splice`] gives. + #[test] + fn edits_from_the_end_match_splicing() { + let mut seed = 0x2545_f491_u64; + let mut next = |m: usize| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 33) as usize % m.max(1) + }; + for round in 0..200 { + let items: Vec = (0..next(60) + 1).collect(); + let (mut want, mut got) = (items.clone(), EditsFromEnd::new(items.clone())); + let mut end = items.len() - 1; + loop { + let hi = end.saturating_sub(next(3)); + let lo = hi.saturating_sub(next(6)); + let with: Vec = (0..next(5)).map(|j| 1000 * (round + 1) + j).collect(); + let Some(stretch) = want.get(lo..=hi).map(<[usize]>::to_vec) else { break }; + assert_eq!(got.get(lo, hi).map(<[usize]>::to_vec), Some(stretch), "round {round}"); + want.splice(lo..=hi, with.clone()); + got.replace(lo, hi, with); + if lo == 0 { + break; + } + end = lo; + } + assert_eq!(got.finish(), want, "round {round}"); + } + } + /// Anchors on one point, anchors that are not numbers or are too far out to measure, and a /// zigzag of 100,001 anchors 1 pt high give no corner and do not fail; a square's four anchors /// are its corners, and an open path's ends never are. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..bfa156bd1c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1552,6 +1552,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a Smooth tool drag reaches the first or last anchor of an open path, that anchor stays where it is and the curve there leaves or arrives along the smoothed path within the reach, so a jagged first or last segment no longer sets the end's direction; an end where the smoothed path turns back by 90° or more keeps its segment's direction, and where the refitted stretch ends inside the path the curve keeps the direction of the part outside the drag. This rule is VectorCraft's own (`tests/draw2.rs`, `smoothing_an_open_path_turns_its_jagged_ends_with_the_path` and `a_smooth_drag_turns_only_the_end_it_reaches`). A Smooth tool drag keeps a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) and rounds a wider one. An anchor is kept as a corner when the path turns by that much at the anchor and also over the drag's reach and over twice the reach on either side of it, so a jag or a bump smaller than the reach is still smoothed; [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes the tool as reducing irregularities in a path. The stretches on either side of a kept corner are smoothed and refitted on their own, and the corner keeps its place and the directions the path arrives and leaves along, on every drag, on open and closed paths, the anchor a closed path starts at included. A drag that changes no anchor adds no undo step. The threshold and the two distances are VectorCraft's own values, the same on every drag and at any Fidelity (`tests/draw2.rs`, `the_smooth_tool_keeps_corners_sharper_than_its_threshold`, `smoothing_a_closed_path_keeps_its_corners` and `a_smooth_drag_that_only_meets_corners_adds_no_undo_step`). A Smooth drag along a curved segment smooths the stretch of it in the drag's reach even when neither of the segment's anchors is in reach, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes dragging along the path segment; the segment is cut where the drag enters and leaves the reach, and the parts outside keep their shape (`path.smoothRegion`). Paths of two anchors are smoothed too, and Alt with the Paintbrush smooths a selected two-anchor curve; a two-anchor straight line still gets the closed stroke. How the reach is found on a segment (samples no more than half the reach apart) is VectorCraft's own, and a straight segment is left as it is. + A Smooth drag measures only the anchors and curved segments near the drag, and each against only the stretches of the drag near it, so the work of a release on a long path follows the part of the path under the drag rather than the whole path's length. On a curved path of 100,000 anchors, a drag of 200 points over 200 pt of it makes 7,533 measures to find the curved segments in its reach, where it made 19,899,801 (99,999 segments times 199 stretches). The smoothed path is the same as before (engine tests `a_drag_over_a_long_path_measures_only_what_is_near_it` and `the_drag_grid_gives_the_results_of_measuring_the_whole_drag` in `crates/engine/src/cmd/draw2/smooth.rs`). Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). From 5a26a9abd58acd69b6f21afbf1fc04752f3f2248 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:32:14 -0800 Subject: [PATCH 048/178] Dimension tool: Alt over a path places its overall width or height With the Linear Dimension tool and Alt (Option on macOS) held, hovering a path shows a box through its outermost points (a Smart Guide when Smart Guides are on), with its width and height beside the pointer when Measurement Labels are on. A click on the path, then a placing click, or a drag out from it, places a dimension of the whole path. With the pointer above or below the path it measures the width, between the leftmost and rightmost points; beside the path it measures the height, between the topmost and bottommost points. The linear dimensions help page describes the Alt hover; which side gives which measure is VectorCraft's own rule. dimension.create takes a new source, {kind: extent, node}, for linear dimensions. Its points are the outermost points of the segments the path draws, curves included, and are read again whenever the path changes, so a turned path shows its new overall width or height. The line keeps its distance from the whole path when the path changes or is reflected, and when dimension.update changes the orientation, which now reads the other pair of points. When the box through the path's outermost points stays where it was, as after Reverse Path Direction, the line stays on its side. A version without the extent source does not open a file that holds one. The measurement label beside the pointer while two points are picked now keeps its distance in screen pixels at any zoom. The Help Bar hint names Alt+Click. Docs: docs/dimensions.md and docs/target-app-parity.md. --- crates/doc/src/dimension.rs | 185 +++++++++++++++++++++--- crates/engine/src/cmd/dimension.rs | 19 ++- crates/engine/tests/it/dimensions.rs | 132 +++++++++++++++++ crates/tools/src/dimension.rs | 204 +++++++++++++++++++++++++-- crates/ui-egui/src/chrome/hints.rs | 2 + docs/dimensions.md | 29 +++- docs/target-app-parity.md | 1 + 7 files changed, 530 insertions(+), 42 deletions(-) diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 4d66f5d74c..0b50358622 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -389,6 +389,12 @@ pub enum DimensionSource { #[serde(default, rename = "freeB", skip_serializing_if = "Option::is_none")] free_b: Option, }, + /// A whole path, measured between its outermost points ([`extent`]): the leftmost and the + /// rightmost while the dimension is horizontal or aligned, the topmost and the bottommost while + /// it is vertical. Versions without this source do not open the file. + Extent { + node: NodeId, + }, } impl DimensionSource { @@ -396,7 +402,7 @@ impl DimensionSource { match self { Self::Segment { edge } | Self::Arc { edge } => vec![edge.node], Self::Angle { first, second } => vec![first.node, second.node], - Self::Circle { node } => vec![*node], + Self::Circle { node } | Self::Extent { node } => vec![*node], Self::Points { a, b, vertex, free_a, free_b } => [a, b, vertex] .into_iter() .filter_map(|p| p.as_ref().map(|r| r.node)) @@ -407,7 +413,7 @@ impl DimensionSource { /// Anchor indexes cannot safely follow a topology replacement. Ordinary moves and handle /// edits keep their topology and remain linked. pub fn topology_changed(&self, before: &Document, after: &Document) -> bool { - if matches!(self, Self::Circle { .. }) { + if matches!(self, Self::Circle { .. } | Self::Extent { .. }) { return false; } self.nodes().iter().any(|id| { @@ -418,9 +424,18 @@ impl DimensionSource { old.is_some() && old != counts(after) }) } + /// Whether a path it measures differs between `before` and `after`, or is in only one of them. + pub fn art_changed(&self, before: &Document, after: &Document) -> bool { + self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) { + (Some(old), Some(new)) => !std::ptr::eq(old, new) && old.path_data() != new.path_data(), + (old, new) => old.is_some() != new.is_some(), + }) + } /// The map that took the measured art from `before` to `after`, when every path it measures /// went through one [`art_transform`] that reflects it (a negative determinant). None when a - /// measured path is unchanged, or when two of them went through different maps. + /// measured path is unchanged, or when two of them went through different maps. None for a + /// dimension of a whole path whose path's box through its outermost points stays where it + /// was, as after its direction is reversed. pub fn reflection(&self, before: &Document, after: &Document) -> Option { let mut first: Option = None; for id in self.nodes() { @@ -429,6 +444,9 @@ impl DimensionSource { return None; } let xf = fitted(before, after, id, |xf| xf.determinant() < 0.0)?; + if matches!(self, Self::Extent { .. }) && same_extents(before, after, id) { + return None; + } match first { None => first = Some(xf), Some(f) => { @@ -759,19 +777,22 @@ impl Dimension { /// outside them as it was, on the same side: the gap is measured from the outermost point /// on the line's side, so the line stays clear of art that turns. A line that lay between /// the two points keeps its distance from the first point. - pub fn keep_gap(&mut self, old: &Dimension) { + /// With `docs`, the documents `old` and this dimension were read from, the gap of a dimension of + /// a whole path is measured from the whole path ([`Self::span`]), also when only parts of the + /// path other than its measured points moved, and also when the dimension is aligned (each + /// along its own normal). + pub fn keep_gap(&mut self, old: &Dimension, docs: Option<(&Document, &Document)>) { + let whole = docs.is_some() && matches!(self.source, Some(DimensionSource::Extent { .. })); if self.mode != DimensionMode::Linear - || self.orientation == Orientation::Aligned + || (self.orientation == Orientation::Aligned && !whole) || old.orientation != self.orientation - || (self.a, self.b) == (old.a, old.b) + || ((self.a, self.b) == (old.a, old.b) && !whole) { return; } - let n = self.normal(); - let across = |p: Point| p.to_vec2().dot(n); - let line = across(old.a) + old.offset; - let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b))); - let (new_low, new_high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b))); + let line = old.a.to_vec2().dot(old.normal()) + old.offset; + let (low, high) = old.span(docs.map(|(before, _)| before)); + let (new_low, new_high) = self.span(docs.map(|(_, after)| after)); let at = if line >= high { new_high + (line - high) } else if line <= low { @@ -779,7 +800,7 @@ impl Dimension { } else { return; }; - let offset = at - across(self.a); + let offset = at - self.a.to_vec2().dot(self.normal()); if offset.is_finite() && offset.abs() <= 1e6 { self.offset = offset; } @@ -787,8 +808,9 @@ impl Dimension { /// A linear dimension whose art was reflected, its points now moved from `old`'s: its line goes /// to the side of the points that `image` (where the reflection put `old`'s line) is on, as far /// past the outermost point on that side as `old`'s line was. A line that lay between the two - /// points is left as it is. - pub fn mirror_line(&mut self, old: &Dimension, image: Point) { + /// points is left as it is. With `docs`, as in [`Self::keep_gap`], a dimension of a whole path + /// measures from the whole path. + pub fn mirror_line(&mut self, old: &Dimension, image: Point, docs: Option<(&Document, &Document)>) { if self.mode != DimensionMode::Linear || old.mode != DimensionMode::Linear { return; } @@ -796,7 +818,7 @@ impl Dimension { let n = old.normal(); let across = |p: Point| p.to_vec2().dot(n); let line = across(old.a) + old.offset; - let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b))); + let (low, high) = old.span(docs.map(|(before, _)| before)); if line >= high { line - high } else if line <= low { @@ -807,13 +829,25 @@ impl Dimension { }; let n = self.normal(); let across = |p: Point| p.to_vec2().dot(n); - let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b))); + let (low, high) = self.span(docs.map(|(_, after)| after)); let at = if 2.0 * across(image) >= low + high { high + gap } else { low - gap }; let offset = at - across(self.a); if offset.is_finite() && offset.abs() <= 1e6 { self.offset = offset; } } + /// Where a linear dimension's art lies along its normal, lowest and highest: its two points, + /// or, for a dimension of a whole path read from `doc`, the whole path ([`reach`]), so that + /// the whole path is on one side of a line outside the span. + fn span(&self, doc: Option<&Document>) -> (f64, f64) { + let n = self.normal(); + let (a, b) = (self.a.to_vec2().dot(n), self.b.to_vec2().dot(n)); + let (low, high) = (a.min(b), a.max(b)); + match (doc, &self.source) { + (Some(doc), Some(DimensionSource::Extent { node })) => reach(doc, *node, n).map_or((low, high), |(l, h)| (low.min(l), high.max(h))), + _ => (low, high), + } + } /// Whether a linear dimension's line lies strictly between its two points along the normal. fn line_between_points(&self) -> bool { let n = self.normal(); @@ -824,19 +858,36 @@ impl Dimension { /// Makes a linear dimension measure in `orientation`, with its line on the side of the points /// it was on. The line goes through the middle of the old line when that point lies outside /// the two points along the new normal; otherwise it lies as far past the outermost point on - /// that side as the old line lay from its points. - pub fn set_orientation(&mut self, orientation: Orientation) { + /// that side as the old line lay from its points. A dimension of a whole path + /// ([`DimensionSource::Extent`]) first reads from `doc` the outermost points it measures in the + /// new orientation, and its line keeps its distance from the whole path ([`Self::span`]), on + /// the side the middle of the old line is on. + pub fn set_orientation(&mut self, orientation: Orientation, doc: &Document) -> Result<(), String> { if self.mode != DimensionMode::Linear || self.orientation == orientation { self.orientation = orientation; - return; + return Ok(()); + } + let (handle, mut gap) = (self.handle(), self.offset.abs()); + if let Some(DimensionSource::Extent { .. }) = &self.source { + // Measured from the whole path. + let (low, high) = self.span(Some(doc)); + let line = self.a.to_vec2().dot(self.normal()) + self.offset; + gap = if line >= high { line - high } else { (low - line).max(0.0) }; } - let (handle, gap) = (self.handle(), self.offset.abs()); self.orientation = orientation; + if let Some(DimensionSource::Extent { node }) = &self.source { + (self.a, self.b) = extent(doc, *node, orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?; + } let n = self.normal(); let across = |p: Point| p.to_vec2().dot(n); - let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b))); + let (low, high) = self.span(Some(doc)); let h = across(handle); - let at = if h >= high || h <= low { + let whole = matches!(self.source, Some(DimensionSource::Extent { .. })); + let at = if whole && h >= high { + high + gap + } else if whole && h <= low { + low - gap + } else if h >= high || h <= low { h } else if 2.0 * h >= low + high { high + gap @@ -848,6 +899,7 @@ impl Dimension { self.offset = offset; } self.length = self.measured(); + Ok(()) } fn bisector(&self) -> Vec2 { let start = (self.a - self.vertex).atan2(); @@ -889,7 +941,7 @@ impl Dimension { self.offset = offset; } if self.line_between_points() && !old.line_between_points() { - self.keep_gap(&old); + self.keep_gap(&old, None); } } else if self.mode == DimensionMode::Linear && xf.determinant() < 0.0 && (self.b - self.a).hypot() > 1e-9 { // A reflection turns the left normal of a → b to the other side, so an aligned @@ -948,6 +1000,12 @@ impl Dimension { let (center, radius) = arc(doc, edge).ok_or("Choose a circle or a perfect arc")?; self.set_radial(center, radius); } + Some(DimensionSource::Extent { node }) => { + let (a, b) = extent(doc, *node, self.orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?; + self.a = a; + self.b = b; + self.length = self.measured(); + } None => {} } self.validate() @@ -1048,6 +1106,87 @@ pub fn arc(doc: &Document, edge: &SegmentRef) -> Option<(Point, f64)> { Some((center, radius)) } +/// The outermost points of a path's outline, read from its segments (an anchor that starts no +/// segment is not part of it): the leftmost and the rightmost, then the topmost and the +/// bottommost. Of points level with each other, the first point is the topmost or leftmost of +/// them and the second the bottommost or rightmost, so a straight vertical line has two points +/// across its width too. None for a node without a path or without segments. +pub fn extents(doc: &Document, id: NodeId) -> Option<[(Point, Point); 2]> { + use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveExtrema}; + let path = doc.node(id)?.path_data()?; + let before = |p: Point, q: Point, vertical: bool| { + let key = |p: Point| if vertical { (p.y, p.x) } else { (p.x, p.y) }; + let (a, b) = (key(p), key(q)); + a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)).is_lt() + }; + let mut ends: Option<[(Point, Point); 2]> = None; + let mut take = |p: Point| { + let ends = ends.get_or_insert([(p, p); 2]); + for (axis, (low, high)) in ends.iter_mut().enumerate() { + if before(p, *low, axis == 1) { + *low = p; + } + if before(*high, p, axis == 1) { + *high = p; + } + } + }; + for sp in &path.subpaths { + for i in 0..sp.segment_count() { + let seg = sp.segment(i); + take(seg.p0); + take(seg.p3); + for t in seg.extrema() { + take(seg.eval(t)); + } + } + } + ends +} + +/// Whether the box through a path's outermost points ([`extents`]) is where it was in `before`, +/// each side to within rounding against the larger coordinate on its axis. +fn same_extents(before: &Document, after: &Document, id: NodeId) -> bool { + let sides = |doc: &Document| extents(doc, id).map(|[(left, right), (top, bottom)]| [left.x, right.x, top.y, bottom.y]); + let (Some(old), Some(new)) = (sides(before), sides(after)) else { return false }; + [0, 2].into_iter().all(|i| { + let scale = old[i].abs().max(old[i + 1].abs()).max(1.0); + (i..i + 2).all(|j| (old[j] - new[j]).abs() <= 1e-12 * scale) + }) +} + +/// [`extents`] along one axis: the leftmost and the rightmost points, or with `vertical` the +/// topmost and the bottommost. +pub fn extent(doc: &Document, id: NodeId, vertical: bool) -> Option<(Point, Point)> { + extents(doc, id).map(|ends| ends[usize::from(vertical)]) +} + +/// How far a path's outline reaches along the unit direction `u`: the lowest and the highest +/// `p · u` over the points of its segments. None for a node without a path or without segments. +pub fn reach(doc: &Document, id: NodeId, u: Vec2) -> Option<(f64, f64)> { + use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveExtrema}; + let path = doc.node(id)?.path_data()?; + // Turns `u` onto the x axis, so the turned curve's extrema include those along `u`. + let turn = Affine::new([u.x, -u.y, u.y, u.x, 0.0, 0.0]); + let mut span: Option<(f64, f64)> = None; + let mut take = |p: Point| { + let v = p.to_vec2().dot(u); + let (low, high) = span.get_or_insert((v, v)); + (*low, *high) = (low.min(v), high.max(v)); + }; + for sp in &path.subpaths { + for i in 0..sp.segment_count() { + let seg = sp.segment(i); + take(seg.p0); + take(seg.p3); + for t in (turn * seg).extrema() { + take(seg.eval(t)); + } + } + } + span +} + /// The two straight segments that meet at a corner anchor, if both are straight. pub fn corner(doc: &Document, node: NodeId, subpath: usize, anchor: usize) -> Option<(SegmentRef, SegmentRef)> { let sp = doc.node(node)?.path_data()?.subpaths.get(subpath)?; diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index e38f8f99bb..27e1d81ae8 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -14,7 +14,7 @@ pub fn specs() -> Vec { "Create Dimension", [], None, - "{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits", + "{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: extent, node} (linear only: a whole path between its outermost points, leftmost and rightmost when horizontal or aligned, topmost and bottommost when vertical)|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits", has_doc, create ), @@ -80,6 +80,7 @@ fn recipe(s: &Session, p: &Value) -> Result { | (DimensionMode::Angular, DimensionSource::Angle { .. }) | (DimensionMode::Radius | DimensionMode::Diameter, DimensionSource::Circle { .. } | DimensionSource::Arc { .. }) | (DimensionMode::Linear | DimensionMode::Angular, DimensionSource::Points { .. }) + | (DimensionMode::Linear, DimensionSource::Extent { .. }) ); if !compatible { return Err(error("Dimension mode does not match its source")); @@ -174,7 +175,7 @@ fn update(s: &mut Session, p: &Value) -> Result { dim.options = o.clone(); } if let Some(orientation) = orientation(p, dim.mode)? { - dim.set_orientation(orientation); + dim.set_orientation(orientation, doc).map_err(error)?; } dim.offset = distance(p, dim.offset)?; dim.resolve(doc).map_err(error)?; @@ -452,7 +453,14 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result { for (id, old) in dimensions { let mut next = old.clone(); let moved = next.moved.take(); - if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || next.resolve(doc).is_err() { + // Whether the path a dimension of a whole path measures changed: when it did not, the + // dimension keeps its points without reading the path again, and is only checked. + let whole_changed = match &next.source { + Some(s @ DimensionSource::Extent { .. }) => Some(s.art_changed(before, doc)), + _ => None, + }; + let unreadable = if whole_changed == Some(false) { next.validate().is_err() } else { next.resolve(doc).is_err() }; + if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || unreadable { // The art it measured was deleted, or rebuilt with other anchors, or no longer fits // (an ellipse that was a circle): it stays where it was, no longer linked, in this // same undo step, rather than attaching to a different edge. @@ -465,13 +473,14 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result { changed = true; continue; } - next.keep_gap(&old); + next.keep_gap(&old, (whole_changed == Some(true)).then_some((before, doc))); if let Some(xf) = next.source.as_ref().and_then(|s| s.reflection(before, doc)) { - next.mirror_line(&old, xf * old.handle()); + next.mirror_line(&old, xf * old.handle(), Some((before, doc))); } // Moved on its own (the art it measures stayed put): it keeps its new place. if let Some(v) = moved && (next.a, next.b, next.vertex) == (old.a, old.b, old.vertex) + && whole_changed != Some(true) { next.place(old.handle() + v); if next.resolve(doc).is_err() { diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 30f3ce2665..2cbd61de92 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -466,6 +466,138 @@ fn turned_horizontal_dimensions_stay_horizontal() { assert_eq!(text(&s, id), "100.00 pt"); } +/// A dimension of a whole path measures the path's overall width, or its height when vertical, +/// between its outermost points, and follows the path when it turns. Turned 30°, a 100 × 60 +/// rectangle is 100 cos 30° + 60 sin 30° wide, more than either side; a turned ellipse is measured +/// at the outermost points of its curves, which are not anchors. +#[test] +fn a_dimension_of_a_whole_path_measures_its_overall_width_and_height() { + let value = |s: &Session, id: u64| text(s, id).trim_end_matches(" pt").parse::().unwrap(); + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + let source = json!({"kind":"extent","node":rect}); + let id = run(&mut s, "dimension.create", json!({"source":source,"orientation":"horizontal","offset":-30}))["id"].as_u64().unwrap(); + assert_eq!(text(&s, id), "100.00 pt"); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "object.rotate", json!({"angle":30})); + let wide = 100.0 * 30f64.to_radians().cos() + 60.0 * 30f64.to_radians().sin(); + assert!((value(&s, id) - wide).abs() < 0.01, "{} against {wide}", text(&s, id)); + // The rectangle's box: left, top, right, bottom. + let bounds = |s: &Session| { + let anchors = s.doc().unwrap().doc.node(NodeId(rect)).unwrap().path_data().unwrap().subpaths[0].anchors.clone(); + let (xs, ys): (Vec, Vec) = anchors.iter().map(|a| (a.p.x, a.p.y)).unzip(); + let low = |v: &[f64]| v.iter().copied().fold(f64::INFINITY, f64::min); + let high = |v: &[f64]| v.iter().copied().fold(f64::NEG_INFINITY, f64::max); + (low(&xs), low(&ys), high(&xs), high(&ys)) + }; + // The line stays 30 pt above the turned rectangle's topmost corner, clear of the art. + let (left, top, right, _) = bounds(&s); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - (top - 30.0)).abs() < 0.01, "line at y = {line}, top at {top}"); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"vertical"})); + let tall = 100.0 * 30f64.to_radians().sin() + 60.0 * 30f64.to_radians().cos(); + assert!((value(&s, id) - tall).abs() < 0.01, "{} against {tall}", text(&s, id)); + let d = recipe(&s, id); + let (top, bottom) = (d.a.y.min(d.b.y), d.a.y.max(d.b.y)); + assert!(((bottom - top) - tall).abs() < 0.01, "the points are the topmost and bottommost: {:?} {:?}", d.a, d.b); + // The line was 30 pt above the path; turned, it is 30 pt beside it. + let line = d.line_ends().0.x; + assert!((line - (left - 30.0)).abs() < 0.01 || (line - (right + 30.0)).abs() < 0.01, "line at x = {line}, path from {left} to {right}"); + run(&mut s, "edit.undo", json!({})); + assert!((value(&s, id) - wide).abs() < 0.01, "{}", text(&s, id)); + // A linear dimension only. + assert!(s.execute("dimension.create", &json!({"mode":"angular","source":source})).is_err()); + + let ellipse = run(&mut s, "shape.ellipse", json!({"x":300,"y":100,"width":100,"height":50}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":ellipse},"orientation":"horizontal"}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[ellipse]})); + run(&mut s, "object.rotate", json!({"angle":45})); + let anchors = s.doc().unwrap().doc.node(NodeId(ellipse)).unwrap().path_data().unwrap().subpaths[0].anchors.clone(); + let between_anchors = anchors.iter().map(|a| a.p.x).fold(f64::MIN, f64::max) - anchors.iter().map(|a| a.p.x).fold(f64::MAX, f64::min); + // 2 √(50² cos² 45° + 25² sin² 45°) + let across = 2.0 * (2500.0f64 * 0.5 + 625.0 * 0.5).sqrt(); + assert!(value(&s, id) > between_anchors + 1.0, "{} against the anchors' {between_anchors}", text(&s, id)); + assert!((value(&s, id) - across).abs() < 0.1, "{} against {across}", text(&s, id)); +} + +/// A dimension of a whole path measures the segments the path draws: an anchor that starts no +/// segment does not widen it. Its line stays clear of the whole path when only parts other than +/// its measured points move, also when it is aligned or is scaled together with the path, when the +/// path's direction is reversed or the path is reflected onto itself, and when it becomes aligned. +/// A reflection that moves the path puts the line on the reflected side. +#[test] +fn a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws() { + let mut s = session(); + let lone = run(&mut s, "path.create", json!({"d":"M100 300 L110 300 M200 400","closed":false}))["id"].as_u64().unwrap(); + assert_eq!(s.doc().unwrap().doc.node(NodeId(lone)).unwrap().path_data().unwrap().subpaths.len(), 2, "the lone anchor is kept"); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":lone},"orientation":"horizontal"}))["id"].as_u64().unwrap(); + assert_eq!(text(&s, id), "10.00 pt"); + + // A triangle whose top rises while its leftmost and rightmost points stay: the line stays + // 30 pt above the top. + let tri = run(&mut s, "path.create", json!({"d":"M100 200 L150 120 L200 200 Z","closed":true}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":tri},"orientation":"horizontal","offset":-110}))["id"] + .as_u64() + .unwrap(); + assert!((recipe(&s, id).line_ends().0.y - 90.0).abs() < 1e-6); + run(&mut s, "select.set", json!({"ids":[tri]})); + run(&mut s, "object.scale", json!({"sx":100,"sy":150,"origin":[150,200]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 50.0).abs() < 1e-6, "line at y = {line}"); + // The same for an aligned dimension, and for a dimension scaled together with its path. + for (x, orientation, with_dimension) in [(300.0, "aligned", false), (500.0, "horizontal", true)] { + let d = format!("M{x} 200 L{} 120 L{} 200 Z", x + 50.0, x + 100.0); + let tri = run(&mut s, "path.create", json!({"d":d,"closed":true}))["id"].as_u64().unwrap(); + let source = json!({"kind":"extent","node":tri}); + let id = run(&mut s, "dimension.create", json!({"source":source,"orientation":orientation,"offset":-110}))["id"].as_u64().unwrap(); + let ids = if with_dimension { vec![tri, id] } else { vec![tri] }; + run(&mut s, "select.set", json!({"ids":ids})); + run(&mut s, "object.scale", json!({"sx":100,"sy":150,"origin":[x + 50.0, 200]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 50.0).abs() < 1e-6, "{orientation}: line at y = {line}"); + } + // Reversing the path's direction draws the same outline: the line stays above it. + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":400,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-30}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "path.reverse", json!({"ids":[rect]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 370.0).abs() < 1e-6, "line at y = {line}"); + // So does a reflection onto itself whose coordinates do not come out exactly, while a + // reflection that moves the art puts the line on the reflected side. + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":500.2,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-30}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,530.2]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 470.2).abs() < 1e-6, "line at y = {line}"); + let tri = run(&mut s, "path.create", json!({"d":"M100 700 L150 620 L200 700 Z","closed":true}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":tri},"orientation":"horizontal","offset":-110}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "select.set", json!({"ids":[tri]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,700]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 810.0).abs() < 1e-6, "line at y = {line}"); + + // Made aligned, the line runs from the leftmost to the rightmost point, with every corner of + // the rectangle on one side of it and 40 pt from the nearest, as it was 40 pt above the top. + let rect = run(&mut s, "shape.rectangle", json!({"x":300,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-40}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"aligned"})); + let (a, b) = recipe(&s, id).line_ends(); + let side = |x: f64, y: f64| (b - a).cross(vectorcraft_geom::Point::new(x, y) - a) / (b - a).hypot(); + let sides = [side(300.0, 100.0), side(400.0, 100.0), side(400.0, 160.0), side(300.0, 160.0)]; + assert!(sides.iter().all(|v| *v > 1e-6) || sides.iter().all(|v| *v < -1e-6), "{a:?} to {b:?}: {sides:?}"); + let nearest = sides.iter().map(|v| v.abs()).fold(f64::INFINITY, f64::min); + assert!((nearest - 40.0).abs() < 1e-6, "nearest corner {nearest} pt from the line"); +} + /// The line of a linked horizontal dimension keeps its gap from the outermost point on its side /// when the art turns, so it stays clear of the art: after a half turn the line is still 50 pt /// above the upper point, which is now the other anchor. diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index dffe13a378..f5a9ca880c 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -1,7 +1,9 @@ //! The Dimension tool. Hover a segment (linear), a corner (angular) or a circle or perfect arc //! (radial) and drag outwards: releasing places the linked dimension. Plain clicks pick what to //! measure instead: two points (linear) or two straight lines (angular), then a click places it; -//! a click on a circle or arc gives its radius. Escape cancels without leaving any artwork. +//! a click on a circle or arc gives its radius. With Alt (Option on macOS) held, a Linear click or +//! drag on a path measures the whole path's width or height instead. Escape cancels without +//! leaving any artwork. use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; use serde_json::{Value, json}; use std::collections::HashMap; @@ -39,12 +41,26 @@ impl Kind { } } -/// What the pointer is over. +/// What the pointer is over. `Extent` is a path hovered with Alt held: its overall width or height. #[derive(Clone, Debug, PartialEq)] enum Target { Segment(SegmentRef), Corner { first: SegmentRef, second: SegmentRef, at: Point }, Radial { source: DimensionSource, center: Point, radius: f64 }, + Extent { node: NodeId }, +} + +/// A path and the document its outermost points ([`dimension::extents`]) were read from +/// ([`whole_box_source`]), with the points. +type WholeBox = ((NodeId, (u64, u64, usize)), Option<[(Point, Point); 2]>); + +/// The document a path's box is read from, with what identifies it: while an interaction is in +/// progress, the document as it began; otherwise the document `cx` shows, at its revision. +fn whole_box_source<'a>(cx: &ToolContext<'a>, node: NodeId) -> (&'a vectorcraft_doc::Document, (NodeId, (u64, u64, usize))) { + match cx.interaction_doc { + Some(began) => (began, (node, (cx.revision.0, 0, std::ptr::from_ref(began).addr()))), + None => (cx.doc, (node, (cx.revision.0, cx.revision.1, 0))), + } } #[derive(Default)] @@ -106,6 +122,9 @@ pub struct DimensionTool { /// The document's next object id at the dimension's first preview: the id its preview takes /// (`dimension.create` gives the dimension the next id). The preview is not a level. preview_id: u64, + /// A path's outermost points, for the path and the document they were read from: a path + /// hovered with Alt held, or a dimension of a whole path being placed. + whole_box: Option, } /// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is @@ -140,6 +159,37 @@ fn orientation_at(a: Point, b: Point, p: Point) -> Orientation { .map_or(Orientation::Aligned, |(_, orientation)| orientation) } +/// The box through a path's outermost points ([`dimension::extents`]): left, top, right and +/// bottom. +fn extent_box([(left, right), (top, bottom)]: [(Point, Point); 2]) -> Rect { + Rect::new(left.x, top.y, right.x, bottom.y) +} + +/// What a dimension of a whole path whose outermost points span `b` ([`extent_box`]) measures +/// with the pointer at `p` while it is placed (VectorCraft's own rule): above or below the box, +/// the path's width (horizontal); to the left or right of it, its height (vertical); past a +/// corner, the side the pointer is farther out on. Inside the box, or as far out on both sides, +/// it keeps `current`. A path with no height gives its width, and one with no width its height. +fn extent_orientation(b: Option, p: Point, current: Orientation) -> Orientation { + let current = if current == Orientation::Aligned { Orientation::Horizontal } else { current }; + let Some(b) = b else { return current }; + match (b.width() > 1e-9, b.height() > 1e-9) { + (true, false) => return Orientation::Horizontal, + (false, true) => return Orientation::Vertical, + (false, false) => return current, + (true, true) => {} + } + let out_x = (b.x0 - p.x).max(p.x - b.x1).max(0.0); + let out_y = (b.y0 - p.y).max(p.y - b.y1).max(0.0); + if out_x > out_y { + Orientation::Vertical + } else if out_y > out_x { + Orientation::Horizontal + } else { + current + } +} + /// How near an anchor (screen pixels) a pick snaps to it. const ANCHOR_REACH: f64 = 8.0; @@ -747,9 +797,27 @@ impl DimensionTool { }; Some(now.or(self.first_pick).unwrap_or(*at)) } - fn target(&self, cx: &ToolContext, p: Point) -> Option { + /// The outermost points of `node` ([`dimension::extents`]), read again only when the path or + /// the document changes. While an interaction is in progress they are read from the document + /// as the interaction began, which each preview starts again from (as the levels in + /// [`Self::preview`] are), so the previews themselves do not make the tool read the path again. + fn whole_box(&mut self, cx: &ToolContext, node: NodeId) -> Option<[(Point, Point); 2]> { + let (from, key) = whole_box_source(cx, node); + if let Some((kept, ends)) = self.whole_box + && kept == key + { + return ends; + } + let ends = dimension::extents(from, node); + self.whole_box = Some((key, ends)); + ends + } + /// What the pointer at `p` is over. A Linear path hovered with `alt` held, before any point + /// is picked, is the whole path. + fn target(&self, cx: &ToolContext, p: Point, alt: bool) -> Option { let edge = pick(cx, p)?; match self.kind { + Kind::Linear if alt && self.points.is_empty() => Some(Target::Extent { node: edge.node }), Kind::Linear => Some(Target::Segment(edge)), Kind::Angular => { let (anchor, at) = anchor_near(cx, &edge, p)?; @@ -801,6 +869,12 @@ impl DimensionTool { let mode = if p.distance(*center) >= *radius { DimensionMode::Radius } else { DimensionMode::Diameter }; self.recipe(mode, *center, p, Point::ZERO, Some(source.clone())) } + Target::Extent { node } => { + let mut d = + self.recipe(DimensionMode::Linear, Point::ZERO, Point::new(1.0, 0.0), Point::ZERO, Some(DimensionSource::Extent { node: *node })); + d.orientation = Orientation::Horizontal; + d + } }; d.offset = 30.0; Some(d) @@ -817,13 +891,19 @@ impl DimensionTool { } fn preview(&mut self, cx: &ToolContext, p: Point) -> Vec { self.level_guide = None; + let whole = match self.pending.as_ref().and_then(|d| d.source.as_ref()) { + Some(DimensionSource::Extent { node }) => Some(self.whole_box(cx, *node)), + _ => None, + }; let Some(d) = &mut self.pending else { return vec![] }; if matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter) && let Some(Target::Radial { center, radius, .. }) = self.press.as_ref().and_then(|(_, t)| t.as_ref()) { d.mode = if p.distance(*center) >= *radius { DimensionMode::Radius } else { DimensionMode::Diameter }; } - if d.mode == DimensionMode::Linear { + if let Some(ends) = whole { + d.orientation = extent_orientation(ends.map(extent_box), p, d.orientation); + } else if d.mode == DimensionMode::Linear { // The points the dimension measures: a dragged segment's ends, read from the art. let ends = match &d.source { Some(DimensionSource::Segment { edge }) => edge.endpoints(cx.doc), @@ -841,7 +921,17 @@ impl DimensionTool { if !matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter) { d.offset = 0.0; } - if d.resolve(cx.doc).is_err() { + // A dimension of a whole path takes the outermost points already read for it. + let read = match whole { + Some(Some(ends)) => { + (d.a, d.b) = ends[usize::from(d.orientation == Orientation::Vertical)]; + d.length = d.measured(); + d.validate() + } + Some(None) => Err(String::new()), + None => d.resolve(cx.doc), + }; + if read.is_err() { return vec![]; } // With Smart Guides on, a linear dimension's line lands on the level of a parallel @@ -906,11 +996,20 @@ impl DimensionTool { self.second = None; self.level_guide = None; self.levels.clear(); + // Alt may no longer be held: the box shows again only when the next move finds it is. + if matches!(self.hover, Some(Target::Extent { .. })) { + self.hover = None; + } } - /// A plain click: picks a point or a line, or measures a circle's radius. + /// A plain click: picks a point or a line, or measures a circle's radius. A click on a path + /// that Alt made the whole path starts placing its width or height. fn click(&mut self, cx: &ToolContext, p: Point, target: Option, mods: Mods) -> Vec { match self.kind { Kind::Linear => { + if let Some(target @ Target::Extent { .. }) = target { + self.pending = self.dimension_for(&target, p).filter(|d| d.clone().resolve(cx.doc).is_ok()); + return vec![]; + } let (mut at, mut reference) = self.snap_linear(cx, p); let mut corner = self.corner; if mods.shift @@ -1018,8 +1117,15 @@ impl Tool for DimensionTool { self.snapped = None; return self.preview(cx, ev.pos); } - self.hover = self.target(cx, ev.pos); - self.snapped = (self.kind == Kind::Linear && self.lines.is_empty()).then(|| self.snap_linear(cx, ev.pos)); + self.hover = self.target(cx, ev.pos, ev.mods.alt); + let whole = match self.hover { + Some(Target::Extent { node }) => { + self.whole_box(cx, node); + true + } + _ => false, + }; + self.snapped = (self.kind == Kind::Linear && self.lines.is_empty() && !whole).then(|| self.snap_linear(cx, ev.pos)); if self.snapped.is_none() { self.snap.clear(); } @@ -1038,7 +1144,7 @@ impl Tool for DimensionTool { && (anchor_under(cx, ev.pos).is_some() || preview_corner(cx, ev.pos, &mut self.preview_boxes).is_some() || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end)); - self.press = Some((ev.pos, self.target(cx, ev.pos))); + self.press = Some((ev.pos, self.target(cx, ev.pos, ev.mods.alt))); vec![] } PointerKind::Drag => { @@ -1122,7 +1228,7 @@ impl Tool for DimensionTool { if cx.measurement_labels && let Ok(text) = self.style.label(a.distance(b), false) { - out.push(Overlay::Measure { p: self.at + Vec2::new(12.0, 12.0), text }); + out.push(Overlay::Measure { p: self.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text }); } } } @@ -1138,6 +1244,29 @@ impl Tool for DimensionTool { out.push(Overlay::Line { a: *center, b: *center + toward / toward.hypot() * *radius, color, dashed: true }); } } + Some(Target::Extent { node }) => { + // The box through the path's outermost points: a Smart Guide, or with Smart + // Guides off a line in the tool's own color. + // Read again when the path changed since the pointer last moved. + let (from, at) = whole_box_source(cx, *node); + let b = match self.whole_box { + Some((key, ends)) if key == at => ends, + _ => dimension::extents(from, *node), + } + .map(extent_box); + if let Some(b) = b { + let line = if cx.smart_guides { cx.smart_guide_color } else { color }; + let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]; + for (i, a) in corners.iter().enumerate() { + out.push(Overlay::Line { a: *a, b: corners[(i + 1) % 4], color: line, dashed: false }); + } + if cx.measurement_labels + && let (Ok(w), Ok(h)) = (self.style.label(b.width(), false), self.style.label(b.height(), false)) + { + out.push(Overlay::Measure { p: self.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("W: {w}\nH: {h}") }); + } + } + } None => {} } } @@ -2201,6 +2330,61 @@ mod tests { } } + /// With Alt held, hovering a path shows the box through its outermost points as a Smart Guide, + /// and a click starts placing a dimension of the whole path: above or below it, its width; + /// beside it, its height. A drag places it on release. Without Alt the same click picks a point. + #[test] + fn an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let held = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y).with_mods(alt); + let preview = |acts: Vec| match acts.last() { + Some(Action::Preview(_, params)) => params.clone(), + other => panic!("{other:?}"), + }; + let mut t = DimensionTool::default(); + t.pointer(&c, &held(PointerKind::Move, 150.0, 100.0)); + assert_eq!(t.hover, Some(Target::Extent { node: id })); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color))); + // With Smart Guides off the box is not a Smart Guide, and at a high zoom the size stays by + // the pointer. + let mut zoomed = cx(&d, &s, &p); + (zoomed.smart_guides, zoomed.measurement_labels, zoomed.zoom) = (false, true, 16.0); + let o = t.overlays(&zoomed); + assert!( + o.iter().any(|o| matches!(o, Overlay::Line { .. })) + && !o.iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color)) + ); + let near = |o: &Overlay| matches!(o, Overlay::Measure { p, text } if p.distance(Point::new(150.0, 100.0)) < zoomed.tol(20.0) && text.starts_with("W: ")); + assert!(o.iter().any(near), "{o:?}"); + t.pointer(&c, &held(PointerKind::Down, 150.0, 100.0)); + t.pointer(&c, &held(PointerKind::Up, 150.0, 100.0)); + assert!(t.pending.is_some() && t.points.is_empty()); + let above = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0))); + assert_eq!(above["source"], json!({"kind":"extent","node":id})); + assert_eq!(above["orientation"], json!("horizontal")); + let beside = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 260.0, 150.0))); + assert_eq!(beside["orientation"], json!("vertical")); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 260.0, 150.0)); + let placed = t.pointer(&c, &PointerEvent::new(PointerKind::Up, 260.0, 150.0)); + assert!(matches!(placed.last(), Some(Action::Commit)), "{placed:?}"); + // Placed with Alt let go: the box does not show again. + assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color))); + + let mut t = DimensionTool::default(); + t.pointer(&c, &held(PointerKind::Down, 200.0, 150.0)); + let dragged = preview(t.pointer(&c, &held(PointerKind::Drag, 150.0, 240.0))); + assert_eq!((dragged["source"]["kind"].clone(), dragged["orientation"].clone()), (json!("extent"), json!("horizontal"))); + assert!(matches!(t.pointer(&c, &held(PointerKind::Up, 150.0, 240.0)).last(), Some(Action::Commit))); + + let mut t = DimensionTool::default(); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 100.0)); + assert!(t.pending.is_none() && t.points.len() == 1, "a plain click picks a point"); + } + /// A point that Smart Guides leave where the pointer already is (the pointer right in line /// with a target) stays on the guide the overlays show. It does not move to the nearest point /// of a segment within the pick's reach. Off the guides, a point near a segment still lands diff --git a/crates/ui-egui/src/chrome/hints.rs b/crates/ui-egui/src/chrome/hints.rs index 2c679c72a1..b435cf00ed 100644 --- a/crates/ui-egui/src/chrome/hints.rs +++ b/crates/ui-egui/src/chrome/hints.rs @@ -8,6 +8,8 @@ fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> { (" out from a highlighted edge to place its dimension | ", false), ("Click", true), (" two points, then move and click to place an aligned, horizontal or vertical dimension | ", false), + ("Alt+Click", true), + (" a path, then move and click to place its overall width or height | ", false), ("Esc", true), (" cancels | Double-click the tool for options", false), ], diff --git a/docs/dimensions.md b/docs/dimensions.md index bf6cf78653..ba1fd687df 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -82,6 +82,22 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers VectorCraft's own rule. With Alignment Guides on, a guide runs along the level across both lines while the dimension is placed. + The + [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) + describes plotting an object's overall horizontal and vertical dimensions by holding Alt + (Option on macOS) over its path. With Alt held, hovering a path shows a box through the path's + outermost points, as a Smart Guide when Smart Guides are on and in the tool's own color when + they are off, with its width and height beside the pointer when Measurement Labels are on. + Clicking the path, then moving and clicking, places a dimension of the whole path; dragging out + from the path places it on release. The rest is VectorCraft's own rule. With + the pointer above or below the box the dimension measures the path's width, between its + leftmost and rightmost points; to the left or right of the box it measures the height, between + the topmost and bottommost points; past a corner, the side the pointer is farther out on + decides. The points are read from the segments the path draws, curves included, and an anchor + that starts no segment is left out. They are read again whenever the path changes, so a turned + path shows its new overall width or height rather than that of its bounding box before the + turn. The line keeps its distance from the whole path when the path changes or the dimension + changes orientation. Alt has this effect only before the first point is clicked. - **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two straight lines that meet (or would, extended), then click to place. - **Radial:** hover a circle, or a segment that is a perfect arc, and drag: outwards gives its @@ -112,7 +128,9 @@ Measurements follow the art they measure through moves, scaling and anchor and h undo and redo included. When the art is reflected, the line of a linked linear dimension goes to the reflected side, as far past the outermost point as before. This does not happen for art whose anchors and handles all lie on one line, such as a straight line, which a half turn puts in the -same place as a reflection. An unlinked aligned dimension that is reflected, or scaled by a +same place as a reflection, nor for a dimension of a whole path whose box through the path's +outermost points stays where it was, as after Reverse Path Direction or a reflection across the +middle of that box. An unlinked aligned dimension that is reflected, or scaled by a negative factor, has its line on the reflected side of its points. Deleting the art, changing its number of anchors or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves its dimensions where they were, no longer linked, in the same undo step, rather than @@ -150,9 +168,12 @@ another document. ## Commands -- `dimension.create`: two points, or a source (segment, angle, circle, arc, points), the mode, - the orientation of a linear dimension (`aligned`, the default, `horizontal` or `vertical`), - offset and style; returns the group id and label. `offset` is the distance of the dimension +- `dimension.create`: two points, or a source (segment, angle, circle, arc, points, extent), the + mode, the orientation of a linear dimension (`aligned`, the default, `horizontal` or + `vertical`), offset and style; returns the group id and label. `{"kind":"extent","node":}` + measures a whole path, linear only: between its leftmost and rightmost points when horizontal + or aligned, and its topmost and bottommost points when vertical. A version without the extent + source does not open a file that holds one. `offset` is the distance of the dimension line from the first point: along the left normal of a → b for an aligned dimension, downward for a horizontal one and leftward for a vertical one. A negative offset goes the other way. - `dimension.update`: restyle or move existing dimensions, or change the orientation of linear diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..7e35dd9151 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -684,6 +684,7 @@ since 2026-10-01. **Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it. **Drawing tools, selected Dimension extension-line style (#7078):** Properties › Dimension exposes the selected editable dimension's existing extension-line color and weight. Both extension lines share that style, independently of the main dimension line and label. Apply to All keeps its full-style behavior for editable dimensions, leaving a protected dimension unchanged; Set as Default keeps the whole style for a new dimension created without explicit options, without changing existing dimensions. The dimension remains editable. Four cases in `crates/ui-egui/tests/dimension_extension_properties.rs` verify actual Properties input, both canvas extension lines, independent main-line/label styling, full-style Apply to All, locked and unselected controls, defaults/new dimensions, Undo/Redo, and native save/reopen with further editing. Existing document-color conversion is unchanged. The measured geometry and existing snapping behavior are unchanged; no whole-Dimension completion or score/hour change is claimed. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. +**Drawing tools, Dimension tool overall width and height of a path (#5590):** With Alt (Option on macOS) held, hovering a path shows a box through its outermost points (a Smart Guide when Smart Guides are on), and a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, as the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes; by VectorCraft's own rule the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height` and `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. From 6b123376fd8c572dbac71bab1f6b34ca9ad1328f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 23:51:45 -0800 Subject: [PATCH 049/178] 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 9758ece7efae40e3b7cd20e537b3abb8f4962afc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:07:34 -0800 Subject: [PATCH 050/178] Scripts: vc.run export of an open document reads its own linked files A command a script runs with vc.run could read only the script's own places and the open documents' own files, so an export, save, print or package of a document whose linked images or placed files sit elsewhere fell back to the saved previews. The script gate now also reads, and never writes, the files that the documents open when the run began link to: linked images, placed files, the plate files of a DCS image and the images their data sets name. The list is taken once, at the run's first vc.run, from those documents as they were when the run began, and holds real paths, so a path that leads to another file later is refused. A link the script adds or re-points, a path it names itself and a document it opens give it no further file to read, a document it opens from one of these files is not saved over it, and the automation read roots and the name and traversal rules still apply first. --- crates/engine/src/cmd/links.rs | 29 +++++- crates/engine/src/file_access.rs | 128 ++++++++++++++++++++++++-- crates/engine/src/script/files.rs | 15 +-- crates/engine/src/script/mod.rs | 40 +++++++- crates/engine/src/tests/script_run.rs | 62 +++++++++++++ docs/mcp.md | 7 ++ docs/target-app-parity.md | 3 +- 7 files changed, 267 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index fccff66c0c..9f1e7c3d79 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -328,7 +328,12 @@ impl<'a> LinkBase<'a> { /// The open document `st`'s. One with no file of its own looks beside the file it was read from. pub(crate) fn of(st: &'a crate::DocState) -> Self { - let (path, from) = (st.path.as_deref(), st.links_from.as_deref()); + Self::of_files(st.path.as_deref(), st.links_from.as_deref()) + } + + /// An open document's, by its own file `path` and the file it was read from, `from` + /// ([`crate::DocState::links_from`]), as [`Self::of`] gives them. + pub(crate) fn of_files(path: Option<&'a str>, from: Option<&'a str>) -> Self { Self { doc: path.or(from), relative: from.or(path) } } } @@ -401,6 +406,28 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { Some(f) } +/// The files the links of `d` (a document looking from `base`) lead to now: where [`locate`] +/// finds each linked image's and placed document's file from `base` and from no document (as +/// output reads them, [`full_linked_images`]), the plate files of their own of images placed from +/// DCS files, and the image files its data sets name. The commands a script runs may read these +/// for the documents open when the run began ([`crate::file_access::ScriptGate::linked`]). +pub(crate) fn files_linked(d: &Document, base: LinkBase) -> Vec { + let mut out = vec![]; + for g in groups(d, None) { + for from in [base, LinkBase::default()] { + let Some(f) = locate(&g.link, from) else { continue }; + out.extend(g.plate_files.iter().filter_map(|p| super::place::dcs::plate_file_path(&f.path, &p.name))); + out.push(f.path); + } + } + let values = d.variables.datasets.iter().flat_map(|set| set.values.values()); + out.extend(values.filter_map(|v| match v { + DataValue::Image(path) => fileio::document_path(path, base.doc).ok(), + _ => None, + })); + out +} + /// The place `stored` names from the file `from`, as `resolve` ([`fileio::document_path`]) follows /// it, when it also follows that place from the document's own file `doc`: a network share the /// document is no longer on is refused. diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..525094a990 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -27,7 +27,8 @@ //! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`) //! are read from, and the places its `File` and `Folder` objects read and write, inside the roots. //! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the -//! files of the open documents. +//! files of the open documents, and for reading, the files the documents open when the run began +//! link to. use std::cell::RefCell; use std::ffi::OsString; @@ -276,19 +277,53 @@ impl ScopeHandle { /// What a command a running script runs (`vc.run`) may read and write: the places the script's /// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app -/// were opened from or saved to. The automation roots apply as well. A path refused by its name -/// alone ([`ScriptScope::refused_by_name`]) is refused here too. +/// were opened from or saved to. Reading, and only reading, the files the documents open when the +/// run began link to is allowed as well ([`ScriptGate::linked`]). The automation roots apply as +/// well. A path refused by its name alone ([`ScriptScope::refused_by_name`]) is refused here too. #[derive(Clone, Debug)] pub(crate) struct ScriptGate { pub(crate) read: ScriptScope, pub(crate) write: ScriptScope, /// The paths of the open documents' files, as the documents hold them. pub(crate) documents: Vec, + /// The real paths of the files the documents open when the run began link to, as they were + /// when the run's first command was run ([`ScriptGate::real_files`]): readable, not writable. + /// A path that leads to another file now is not one of them. + pub(crate) linked: Arc<[PathBuf]>, /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). pub(crate) also: Option>, } impl ScriptGate { + /// The real paths of the files at `paths` that are files now, each once, for + /// [`ScriptGate::linked`]. A path refused by its name alone, and one that cannot be resolved, + /// is left out. + pub(crate) fn real_files(paths: impl IntoIterator) -> Arc<[PathBuf]> { + let mut real: Vec = paths + .into_iter() + .filter(|p| !ScriptScope::refused_by_name(Path::new(p))) + .filter_map(|p| resolve(&p).ok()) + .filter(|p| p.is_file()) + .collect(); + real.sort(); + real.dedup(); + real.into() + } + + /// This gate without the documents whose files only [`ScriptGate::linked`] lets it read, unless + /// they are among `before`, the files of the documents open when the run began: a document the + /// run opened from such a file is read, never written. + pub(crate) fn keeping_linked_read_only(mut self, before: &[String]) -> Self { + let plain = ScriptGate { documents: vec![], linked: Arc::new([]), also: None, ..self.clone() }; + let linked = self.linked.clone(); + let only_linked = |d: &String| { + let real = if ScriptScope::refused_by_name(Path::new(d)) { None } else { resolve(d).ok() }; + real.is_some_and(|real| linked.binary_search(&real).is_ok()) && plain.check(d, Access::Read).is_err() + }; + self.documents.retain(|d| before.contains(d) || !only_linked(d)); + self + } + /// This gate with `next` at the end of its chain of `also` gates, so a path must pass every /// gate already in the chain as well as `next`. fn followed_by(&self, next: Arc) -> ScriptGate { @@ -307,7 +342,7 @@ impl ScriptGate { let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; let allowed = real.is_some_and(|real| { let scoped = match access { - Access::Read => self.read.allows(&real) || self.write.allows(&real), + Access::Read => self.read.allows(&real) || self.write.allows(&real) || self.linked.binary_search(&real).is_ok(), Access::Write => self.write.allows(&real), }; scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) @@ -918,8 +953,13 @@ mod tests { #[test] fn a_narrowed_scope_keeps_the_script_gates_of_both() { let (base, _) = folders("narrowed-gate"); - let gate = - |dir: &str| ScriptGate { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], also: None }; + let gate = |dir: &str| ScriptGate { + read: ScriptScope::of_folder(&base.join(dir)), + write: ScriptScope::default(), + documents: vec![], + linked: Arc::new([]), + also: None, + }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); let reads = |saved: ScopeHandle, gate_here: Option| { let narrowed = match gate_here { @@ -942,7 +982,13 @@ mod tests { #[test] fn a_scope_narrowed_several_times_keeps_every_gate() { let (base, _) = folders("narrowed-thrice"); - let gate = |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], also: None }; + let gate = |dir: &Path| ScriptGate { + read: ScriptScope::of_folder(dir), + write: ScriptScope::default(), + documents: vec![], + linked: Arc::new([]), + also: None, + }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); let narrow = |saved: ScopeHandle, g: ScriptGate| with_script_gate(g, || saved.within_current()); let reads = |h: &ScopeHandle| h.clone().run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok())); @@ -957,6 +1003,74 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A file an open document linked to when the run began is readable through the gate; its path + /// written with `..`, writing it, a file next to it and a file that was not there when the gate + /// was made are not allowed, and the automation roots still apply. + #[test] + fn a_gate_reads_only_the_linked_files_it_was_given() { + let (base, roots) = folders("linked"); + let (secret, other) = (base.join("outside/secret.svg"), base.join("outside/other.svg")); + std::fs::write(&other, "").unwrap(); + let later = base.join("outside/later.svg"); + let linked = ScriptGate::real_files([s(secret.clone()), s(later.clone()), s(base.join("outside"))]); + assert_eq!(linked.len(), 1, "a missing file and a folder are left out: {linked:?}"); + let gate = + ScriptGate { read: ScriptScope::of_folder(&base.join("in")), write: ScriptScope::default(), documents: vec![], linked, also: None }; + std::fs::write(&later, "").unwrap(); + let (read, write) = + (|p: &Path| gate.check(&s(p.to_path_buf()), Access::Read).is_ok(), |p: &Path| gate.check(&s(p.to_path_buf()), Access::Write).is_ok()); + assert!(read(&secret)); + assert!(!read(&base.join("outside/../outside/secret.svg")), "a path with `..` is refused by its name"); + assert!(!write(&secret), "linked files are not written"); + assert!(!read(&other), "a file next to a linked one"); + assert!(!read(&later), "a file made after the gate"); + assert!(!read(&base.join("outside")), "the linked file's folder"); + let g = gate.clone(); + assert!(confine(Some(&roots), || with_script_gate(g, || check_read(&s(secret.clone())).is_err())), "the roots apply first"); + let _ = std::fs::remove_dir_all(base); + } + + /// A document the run opened from a file only the linked files let it read is not written + /// through the document-file rule; one open when the run began, and one in the script's own + /// places, still is. + #[test] + fn a_document_opened_from_a_linked_file_stays_read_only() { + let (base, _) = folders("linked-doc"); + let (secret, own) = (s(base.join("outside/secret.svg")), s(base.join("in/a.svg"))); + let gate = ScriptGate { + read: ScriptScope::of_folder(&base.join("in")), + write: ScriptScope::of_folder(&base.join("in")), + documents: vec![secret.clone(), own.clone()], + linked: ScriptGate::real_files([secret.clone(), own.clone()]), + also: None, + }; + let opened = gate.clone().keeping_linked_read_only(&[]); + assert!(opened.check(&secret, Access::Read).is_ok()); + assert!(opened.check(&secret, Access::Write).is_err(), "opened by the run from a linked file"); + assert!(opened.check(&own, Access::Write).is_ok(), "a file in the script's own places"); + let before = gate.keeping_linked_read_only(std::slice::from_ref(&secret)); + assert!(before.check(&secret, Access::Write).is_ok(), "open when the run began"); + let _ = std::fs::remove_dir_all(base); + } + + /// A link to a linked file read through the gate counts only while it leads to that file. + #[cfg(unix)] + #[test] + fn a_gate_refuses_a_link_that_now_leads_elsewhere() { + let (base, _) = folders("linked-moved"); + let (secret, other, link) = (base.join("outside/secret.svg"), base.join("outside/other.svg"), base.join("outside/link.svg")); + std::fs::write(&other, "").unwrap(); + std::os::unix::fs::symlink(&secret, &link).unwrap(); + let linked = ScriptGate::real_files([s(link.clone())]); + let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], linked, also: None }; + assert!(gate.check(&s(link.clone()), Access::Read).is_ok() && gate.check(&s(secret.clone()), Access::Read).is_ok()); + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&other, &link).unwrap(); + assert!(gate.check(&s(link.clone()), Access::Read).is_err(), "the link leads to another file now"); + assert!(gate.check(&s(other), Access::Read).is_err()); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn network_paths_are_told_by_name() { for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index c0694bbd81..34179a55b5 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -54,7 +54,8 @@ //! for, loses the grant before that code runs. A run with nobody to ask gets `null` and //! [`NO_PICKER`]. //! - The commands a script runs with `vc.run` read and write only in the places above and in the -//! files of the open documents ([`crate::file_access::ScriptGate`]). +//! files of the open documents ([`crate::file_access::ScriptGate`]). They also read the files that +//! the documents open when the run began link to, as those links were then. //! - `open('w')` empties the file at once; what a script writes is kept in memory, at most //! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at //! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an @@ -72,8 +73,9 @@ //! - In a wasm build every lookup fails with [`NO_WEB`]. use std::collections::HashMap; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::rc::Rc; +use std::sync::Arc; use std::sync::atomic::{AtomicU32, Ordering}; use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; @@ -454,10 +456,11 @@ impl Disk { } } - /// The gate for a command the script runs: the places it reads and writes now, and the files of - /// the open documents, `documents`. - pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { - crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None } + /// The gate for a command the script runs: the places it reads and writes now, the files of the + /// open documents, `documents`, and the files it may only read because the documents open when + /// the run began link to them, `linked`. + pub(crate) fn gate(&self, documents: Vec, linked: Arc<[PathBuf]>) -> crate::file_access::ScriptGate { + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None } } /// The files written since this was last asked, to name in the report. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..62dc11df23 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -799,6 +799,36 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, + /// The documents open when the run began, each with its own file and the file it was read from + /// ([`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files + /// they link to from them ([`Host::linked`]). + run_docs: RefCell>, + /// The files of the documents open when the run began + /// ([`crate::file_access::ScriptGate::keeping_linked_read_only`]). + opened_before: Vec, + /// The real paths of the files the documents open when the run began link to + /// ([`crate::file_access::ScriptGate::linked`]). + linked: std::cell::OnceCell>, +} + +/// A document open when a run began, with its own file and the file it was read from. +type RunDoc = (Arc, Option, Option); + +impl Host { + /// The files the commands the run runs may read because the documents open when the run began + /// link to them, found once, from those documents as they were then: a link the run adds or + /// changes, and a document it opens, give it no file to read. + fn linked(&self) -> Arc<[std::path::PathBuf]> { + self.linked + .get_or_init(|| { + let docs = std::mem::take(&mut *self.run_docs.borrow_mut()); + let files = docs.iter().flat_map(|(d, path, from)| { + crate::cmd::links::files_linked(d, crate::cmd::links::LinkBase::of_files(path.as_deref(), from.as_deref())) + }); + crate::file_access::ScriptGate::real_files(files.collect::>()) + }) + .clone() + } } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -1238,8 +1268,11 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); - // The command reads and writes only where the script's own files may, and the open documents' files. - let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect()); + // The command reads and writes only where the script's own files may, and the open documents' files; + // it also reads the files the documents open when the run began link to, and does not write a document + // the run opened from one of those. + let linked = host.linked(); + let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect(), linked).keeping_linked_read_only(&host.opened_before); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); // A file a command wrote before it failed is on disk all the same. let mut written = host.written.borrow_mut(); @@ -2040,6 +2073,9 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), + run_docs: RefCell::new(self.docs.iter().map(|st| (st.doc.clone(), st.path.clone(), st.links_from.clone())).collect()), + opened_before: self.docs.iter().filter_map(|st| st.path.clone()).collect(), + linked: std::cell::OnceCell::new(), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index bf8154f9a7..d0a9723f3e 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -417,6 +417,68 @@ fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { let _ = std::fs::remove_dir_all(&dir); } +/// The color at the middle of the PNG at `path`. +fn middle_color(path: &std::path::Path) -> [u8; 3] { + let img = craft_image_codecs::decode(&std::fs::read(path).unwrap()).unwrap(); + let (w, h) = img.dimensions(); + let rgba = img.to_rgba8(); + let i = ((h / 2 * w + w / 2) * 4) as usize; + [rgba[i], rgba[i + 1], rgba[i + 2]] +} + +/// A script's export of a document open when the run began draws the file its image links to, +/// also outside the script's places. A file the script names itself, a link it points at such a +/// file, writing to the linked file and the links of a document the script opens are refused all +/// the same. +#[test] +fn a_scripts_export_reads_the_files_the_documents_open_before_it_link_to() { + use crate::tests_links::{BLUE, RED, near, open, place, png, save, session, write}; + let dir = fresh_folder("gate-links"); + let (inside, art) = (dir.join("in"), dir.join("art")); + std::fs::create_dir_all(&inside).unwrap(); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (pic, secret, poster, other) = + (p(art.join("photo.png")), p(art.join("secret.png")), p(art.join("poster.vectorcraft")), p(inside.join("other.vectorcraft"))); + write(&pic, &png(600, 300, RED)); + write(&secret, &png(600, 300, RED)); + let mut s = session(); + place(&mut s, &pic); + save(&mut s, &poster); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + place(&mut s, &secret); + save(&mut s, &other); + s.execute("file.close", &json!({})).unwrap(); + // The files change after the saves: each document holds only the red preview of its image. + write(&pic, &png(600, 300, BLUE)); + write(&secret, &png(600, 300, BLUE)); + open(&mut s, &poster); + let (first, second) = (inside.join("first.png"), inside.join("second.png")); + let call = |id: &str, params: String| { + format!( + "try {{ var r = vc.run('{id}', {params}); vc.log(r.warnings ? r.warnings.length : 0); }} \ + catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n" + ) + }; + let export = |to: &std::path::Path| format!("{{path: {:?}, format: 'png', background: 'white'}}", p(to.to_path_buf())); + let source = [ + call("document.export", export(&first)), + call("file.place", format!("{{path: {secret:?}, at: [200, 150]}}")), + "vc.run('select.all', {});\n".to_string(), + call("links.relink", format!("{{path: {secret:?}}}")), + call("document.export", format!("{{path: {pic:?}, format: 'png'}}")), + call("document.open", format!("{{path: {other:?}}}")), + call("document.export", export(&second)), + ] + .concat(); + let r = run_allowed(&mut s, &inside, &source).unwrap(); + assert_eq!(r["log"], json!([0, "denied", "denied", "denied", 0, 1]), "{r}"); + assert!(near(middle_color(&first), BLUE), "the linked file, not its preview: {:?}", middle_color(&first)); + assert!(near(middle_color(&second), RED), "a document the script opened gets no linked file: {:?}", middle_color(&second)); + assert_eq!(std::fs::read(&pic).unwrap(), png(600, 300, BLUE), "the linked file is not written"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A command a script runs does not save into the app's own libraries; the same command run /// outside a script does. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..9a1f57c42f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3020,6 +3020,13 @@ VectorCraft writes files by these rules of its own: `Script file access denied` and the path, saving into a user library (swatches, brushes, symbols or graphic styles) included; reading the app's own libraries is allowed. A script given as `source` that a person allowed nothing writes only in its `Folder.temp` and `Folder.userData` and to the open documents' own files. + Such a command also reads, and does not write, the files that the documents open when the run began link to + (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, + save, print or package of them includes the linked art. A document the script opens from such a file is not + saved over it. The files are taken as those links led at the run's + first `vc.run`, and a path that leads to another file since is refused. A link the script adds or points + elsewhere, and a document it opens, does not let it read any file it could not read before. The automation + read roots still apply. A pick inside the folder that holds the settings gives `null` and sets `error` to `Script file access to the app's own folders is not allowed`. - A run with nobody to ask, as over MCP or the command line, gives `null` from every file dialog and sets `error` to diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..37b87a97d9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1039,7 +1039,8 @@ 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 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, and read the files linked as the next line says; 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: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run`; a path that leads to another file since, a link the script adds or points elsewhere and a document it opens give it no further file to read, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - 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 f85fc7614ede48573de4c1b391305148dd4f7473 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:10:09 -0800 Subject: [PATCH 051/178] 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 4367a9ce68b9b1cba848dd06c1a573369096ac8a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:22:58 -0800 Subject: [PATCH 052/178] Smooth: the progress line says every anchor and segment is still looked up A release still looks up every anchor and curved segment of a path in the drag's grid, so that work grows with the path's length. The line now says the grid reduces the stretch measures, and that the 7,533 and 19,899,801 figures count stretch measures. --- 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 bfa156bd1c..bce51bbfb4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1552,7 +1552,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a Smooth tool drag reaches the first or last anchor of an open path, that anchor stays where it is and the curve there leaves or arrives along the smoothed path within the reach, so a jagged first or last segment no longer sets the end's direction; an end where the smoothed path turns back by 90° or more keeps its segment's direction, and where the refitted stretch ends inside the path the curve keeps the direction of the part outside the drag. This rule is VectorCraft's own (`tests/draw2.rs`, `smoothing_an_open_path_turns_its_jagged_ends_with_the_path` and `a_smooth_drag_turns_only_the_end_it_reaches`). A Smooth tool drag keeps a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) and rounds a wider one. An anchor is kept as a corner when the path turns by that much at the anchor and also over the drag's reach and over twice the reach on either side of it, so a jag or a bump smaller than the reach is still smoothed; [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes the tool as reducing irregularities in a path. The stretches on either side of a kept corner are smoothed and refitted on their own, and the corner keeps its place and the directions the path arrives and leaves along, on every drag, on open and closed paths, the anchor a closed path starts at included. A drag that changes no anchor adds no undo step. The threshold and the two distances are VectorCraft's own values, the same on every drag and at any Fidelity (`tests/draw2.rs`, `the_smooth_tool_keeps_corners_sharper_than_its_threshold`, `smoothing_a_closed_path_keeps_its_corners` and `a_smooth_drag_that_only_meets_corners_adds_no_undo_step`). A Smooth drag along a curved segment smooths the stretch of it in the drag's reach even when neither of the segment's anchors is in reach, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes dragging along the path segment; the segment is cut where the drag enters and leaves the reach, and the parts outside keep their shape (`path.smoothRegion`). Paths of two anchors are smoothed too, and Alt with the Paintbrush smooths a selected two-anchor curve; a two-anchor straight line still gets the closed stroke. How the reach is found on a segment (samples no more than half the reach apart) is VectorCraft's own, and a straight segment is left as it is. - A Smooth drag measures only the anchors and curved segments near the drag, and each against only the stretches of the drag near it, so the work of a release on a long path follows the part of the path under the drag rather than the whole path's length. On a curved path of 100,000 anchors, a drag of 200 points over 200 pt of it makes 7,533 measures to find the curved segments in its reach, where it made 19,899,801 (99,999 segments times 199 stretches). The smoothed path is the same as before (engine tests `a_drag_over_a_long_path_measures_only_what_is_near_it` and `the_drag_grid_gives_the_results_of_measuring_the_whole_drag` in `crates/engine/src/cmd/draw2/smooth.rs`). + A Smooth drag measures only the anchors and curved segments near the drag, and each against only the stretches of the drag near it. A release still looks up every anchor and curved segment of a path in the drag's grid, so the lookups still grow with the path's length. The grid reduces the number of stretch measures. On a curved path of 100,000 anchors, a drag of 200 points over 200 pt of it makes 7,533 stretch measures to find the curved segments in its reach, where it made 19,899,801 (99,999 segments times 199 stretches). The smoothed path is the same as before (engine tests `a_drag_over_a_long_path_measures_only_what_is_near_it` and `the_drag_grid_gives_the_results_of_measuring_the_whole_drag` in `crates/engine/src/cmd/draw2/smooth.rs`). Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). From 8a878f0ebebbf6aa87d2e9597bab6d215294e494 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:41:10 -0800 Subject: [PATCH 053/178] 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 bab25d02487c087f44d143d0000ea33fb0de2660 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:32:08 -0800 Subject: [PATCH 054/178] Scripts: a document opened from a linked file stays read-only when its path changes The gate now records each path a script's command reads only because it led to a file the open documents link to. A document whose file is such a path is taken out of the open documents' files for the rest of the run, without looking at where the path leads now or what the script may read now. Before, the gate decided that again for each command from the path's current target, so a path pointed at another file by a link, or a read grant given later, let the run read and write through the document. --- crates/engine/src/file_access.rs | 139 ++++++++++++++++++++++++++---- crates/engine/src/script/files.rs | 5 +- crates/engine/src/script/mod.rs | 11 +-- docs/mcp.md | 4 +- 4 files changed, 135 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 525094a990..890be26fb9 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -286,19 +286,52 @@ pub(crate) struct ScriptGate { pub(crate) write: ScriptScope, /// The paths of the open documents' files, as the documents hold them. pub(crate) documents: Vec, - /// The real paths of the files the documents open when the run began link to, as they were - /// when the run's first command was run ([`ScriptGate::real_files`]): readable, not writable. - /// A path that leads to another file now is not one of them. - pub(crate) linked: Arc<[PathBuf]>, + /// The files the documents open when the run began link to: readable, not writable. + pub(crate) linked: LinkedFiles, /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). pub(crate) also: Option>, } +/// The files the commands a script runs may only read because the documents open when the run +/// began link to them ([`ScriptGate::linked`]), and the paths a command read through them alone. +/// Clones share the record of those paths. +#[derive(Clone, Debug, Default)] +pub(crate) struct LinkedFiles { + /// The real paths of the files, as they were when the run's first command was run, sorted. A + /// path that leads to another file now is not one of them. + files: Arc<[PathBuf]>, + /// The paths, absolute as a document holds its file, that a command read only because they led + /// to one of `files` when it read them. A document opened from one of them stays read-only for + /// the rest of the run, wherever the path leads later. + read: Arc>>, +} + +impl LinkedFiles { + /// Is `real`, a real path, one of the files? + fn has(&self, real: &Path) -> bool { + self.files.binary_search_by(|f| f.as_path().cmp(real)).is_ok() + } + + /// The paths read through the files alone so far. + fn read_paths(&self) -> Vec { + self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() + } + + /// Notes that `path` was read through the files alone. + fn note_read(&self, path: &str) { + let path = crate::cmd::fileio::absolute_path(path); + let mut read = self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if !read.contains(&path) { + read.push(path); + } + } +} + impl ScriptGate { /// The real paths of the files at `paths` that are files now, each once, for /// [`ScriptGate::linked`]. A path refused by its name alone, and one that cannot be resolved, /// is left out. - pub(crate) fn real_files(paths: impl IntoIterator) -> Arc<[PathBuf]> { + pub(crate) fn real_files(paths: impl IntoIterator) -> LinkedFiles { let mut real: Vec = paths .into_iter() .filter(|p| !ScriptScope::refused_by_name(Path::new(p))) @@ -307,18 +340,20 @@ impl ScriptGate { .collect(); real.sort(); real.dedup(); - real.into() + LinkedFiles { files: real.into(), read: Arc::default() } } /// This gate without the documents whose files only [`ScriptGate::linked`] lets it read, unless /// they are among `before`, the files of the documents open when the run began: a document the - /// run opened from such a file is read, never written. + /// run opened from such a file is read, never written. A document counts as one when a command + /// read its file through the linked files alone, whatever the path leads to or the script may + /// read now, and when its file is one of them now that nothing else lets the gate read. pub(crate) fn keeping_linked_read_only(mut self, before: &[String]) -> Self { - let plain = ScriptGate { documents: vec![], linked: Arc::new([]), also: None, ..self.clone() }; - let linked = self.linked.clone(); + let plain = ScriptGate { documents: vec![], linked: LinkedFiles::default(), also: None, ..self.clone() }; + let (linked, read) = (self.linked.clone(), self.linked.read_paths()); let only_linked = |d: &String| { let real = if ScriptScope::refused_by_name(Path::new(d)) { None } else { resolve(d).ok() }; - real.is_some_and(|real| linked.binary_search(&real).is_ok()) && plain.check(d, Access::Read).is_err() + read.contains(d) || (real.is_some_and(|real| linked.has(&real)) && plain.check(d, Access::Read).is_err()) }; self.documents.retain(|d| before.contains(d) || !only_linked(d)); self @@ -342,10 +377,17 @@ impl ScriptGate { let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; let allowed = real.is_some_and(|real| { let scoped = match access { - Access::Read => self.read.allows(&real) || self.write.allows(&real) || self.linked.binary_search(&real).is_ok(), + Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; - scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) + if scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) { + return true; + } + let linked = matches!(access, Access::Read) && self.linked.has(&real); + if linked { + self.linked.note_read(path); + } + linked }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -957,7 +999,7 @@ mod tests { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], - linked: Arc::new([]), + linked: LinkedFiles::default(), also: None, }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); @@ -986,7 +1028,7 @@ mod tests { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], - linked: Arc::new([]), + linked: LinkedFiles::default(), also: None, }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); @@ -1013,7 +1055,7 @@ mod tests { std::fs::write(&other, "").unwrap(); let later = base.join("outside/later.svg"); let linked = ScriptGate::real_files([s(secret.clone()), s(later.clone()), s(base.join("outside"))]); - assert_eq!(linked.len(), 1, "a missing file and a folder are left out: {linked:?}"); + assert_eq!(linked.files.len(), 1, "a missing file and a folder are left out: {linked:?}"); let gate = ScriptGate { read: ScriptScope::of_folder(&base.join("in")), write: ScriptScope::default(), documents: vec![], linked, also: None }; std::fs::write(&later, "").unwrap(); @@ -1053,6 +1095,73 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A document opened from a file a command read through the linked files alone stays + /// read-only after the script is allowed to read that file's folder, and after the file is + /// replaced by another one. + #[test] + fn a_document_read_through_a_linked_file_stays_read_only_after_a_read_grant() { + let (base, _) = folders("linked-granted"); + let secret = s(base.join("outside/secret.svg")); + let linked = ScriptGate::real_files([secret.clone()]); + let gate = |read: &str, documents: Vec| ScriptGate { + read: ScriptScope::of_folder(&base.join(read)), + write: ScriptScope::default(), + documents, + linked: linked.clone(), + also: None, + }; + assert!(gate("in", vec![]).check(&secret, Access::Read).is_ok(), "the command that opens it reads it through the linked file"); + let granted = gate("outside", vec![secret.clone()]).keeping_linked_read_only(&[]); + assert!(granted.check(&secret, Access::Read).is_ok()); + assert!(granted.check(&secret, Access::Write).is_err(), "a read grant made later does not make it writable"); + std::fs::remove_file(&secret).unwrap(); + std::fs::write(&secret, "").unwrap(); + let replaced = gate("in", vec![secret.clone()]).keeping_linked_read_only(&[]); + assert!(replaced.check(&secret, Access::Write).is_err(), "replaced by another file"); + let _ = std::fs::remove_dir_all(base); + } + + /// A document opened from a file a command read through the linked files alone gives no + /// access to the file its path leads to after the path is pointed elsewhere by a link. + #[test] + fn a_document_read_through_a_linked_file_gives_nothing_once_its_path_leads_elsewhere() { + let (base, _) = folders("linked-redirected"); + #[cfg(unix)] + let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok(); + #[cfg(windows)] + let made = |target: &Path, link: &Path| std::os::windows::fs::symlink_dir(target, link).is_ok(); + #[cfg(not(any(unix, windows)))] + let made = |_: &Path, _: &Path| false; + let (first, second, via) = (base.join("outside/first"), base.join("outside/second"), base.join("outside/via")); + for dir in [&first, &second] { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(dir.join("a.svg"), "").unwrap(); + } + // Windows needs Developer Mode or elevation to make links: nothing to test without them. + if !made(&first, &via) { + eprintln!("skipped: symbolic links can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + let (doc, elsewhere) = (s(via.join("a.svg")), s(second.join("a.svg"))); + let linked = ScriptGate::real_files([doc.clone()]); + let gate = |documents: Vec| ScriptGate { + read: ScriptScope::default(), + write: ScriptScope::default(), + documents, + linked: linked.clone(), + also: None, + }; + assert!(gate(vec![]).check(&doc, Access::Read).is_ok(), "the command that opens it reads it through the linked file"); + std::fs::remove_dir(&via).or_else(|_| std::fs::remove_file(&via)).unwrap(); + assert!(made(&second, &via)); + let opened = gate(vec![doc.clone()]).keeping_linked_read_only(&[]); + for (path, access) in [(&doc, Access::Read), (&doc, Access::Write), (&elsewhere, Access::Read), (&elsewhere, Access::Write)] { + assert!(opened.check(path, access).is_err(), "{path} {access:?}"); + } + let _ = std::fs::remove_dir_all(base); + } + /// A link to a linked file read through the gate counts only while it leads to that file. #[cfg(unix)] #[test] diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 34179a55b5..2c63c9cd66 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -73,9 +73,8 @@ //! - In a wasm build every lookup fails with [`NO_WEB`]. use std::collections::HashMap; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::rc::Rc; -use std::sync::Arc; use std::sync::atomic::{AtomicU32, Ordering}; use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; @@ -459,7 +458,7 @@ impl Disk { /// The gate for a command the script runs: the places it reads and writes now, the files of the /// open documents, `documents`, and the files it may only read because the documents open when /// the run began link to them, `linked`. - pub(crate) fn gate(&self, documents: Vec, linked: Arc<[PathBuf]>) -> crate::file_access::ScriptGate { + pub(crate) fn gate(&self, documents: Vec, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate { crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None } } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 62dc11df23..9e3419d10d 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -806,9 +806,9 @@ struct Host { /// The files of the documents open when the run began /// ([`crate::file_access::ScriptGate::keeping_linked_read_only`]). opened_before: Vec, - /// The real paths of the files the documents open when the run began link to - /// ([`crate::file_access::ScriptGate::linked`]). - linked: std::cell::OnceCell>, + /// The files the documents open when the run began link to, and the paths the run's commands + /// read through them alone ([`crate::file_access::ScriptGate::linked`]). + linked: std::cell::OnceCell, } /// A document open when a run began, with its own file and the file it was read from. @@ -817,8 +817,9 @@ type RunDoc = (Arc, Option, Option); impl Host { /// The files the commands the run runs may read because the documents open when the run began /// link to them, found once, from those documents as they were then: a link the run adds or - /// changes, and a document it opens, give it no file to read. - fn linked(&self) -> Arc<[std::path::PathBuf]> { + /// changes, and a document it opens, give it no file to read. Every command's gate shares the + /// record of the paths read through them. + fn linked(&self) -> crate::file_access::LinkedFiles { self.linked .get_or_init(|| { let docs = std::mem::take(&mut *self.run_docs.borrow_mut()); diff --git a/docs/mcp.md b/docs/mcp.md index 9a1f57c42f..6c0de9e418 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3023,7 +3023,9 @@ VectorCraft writes files by these rules of its own: Such a command also reads, and does not write, the files that the documents open when the run began link to (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, save, print or package of them includes the linked art. A document the script opens from such a file is not - saved over it. The files are taken as those links led at the run's + saved over it for the rest of the run, also after the script is allowed to read that file's folder, and when its + path leads to another file later, the document does not let the script read or write that file. The files are + taken as those links led at the run's first `vc.run`, and a path that leads to another file since is refused. A link the script adds or points elsewhere, and a document it opens, does not let it read any file it could not read before. The automation read roots still apply. From 2efe8814da093334841b14fd4dd8b79cbaa6c163 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:31:53 -0800 Subject: [PATCH 055/178] 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 2d6b8680e6de3d718dadd704b09a7d34130a966d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:01:48 -0800 Subject: [PATCH 056/178] Dimension tool: whole-path dimensions keep clear of the path when turned A dimension of a whole path whose line lay across the path, made vertical or horizontal with dimension.update, now goes as far past the path as it lay from its first point. Before, its line landed on the path's edge. A line on the edge to within rounding still counts as outside the path. When the new place would be more than 1,000,000 pt from the first point, the update is an error unless it also gives offset, and the dimension is left as it was. A dimension whose measured node is missing or is not a path, as in a file that names a node it does not hold, is unlinked at the next edit. Tests: a dimension of a whole path saved in a native file and opened again still follows the path, and one that names a missing node is unlinked at the next edit; past a corner of the path the side the pointer is farther out on decides; after the first point Alt picks a point; a hovered segment's length stays by the pointer at a high zoom. The line in docs/target-app-parity.md now attributes only the Alt hover over a path to the linear dimensions help page. Docs: docs/dimensions.md and dimension.update's params text. --- crates/doc/src/dimension.rs | 62 ++++++++++++++++++--------- crates/engine/src/cmd/dimension.rs | 11 ++++- crates/engine/tests/it/dimensions.rs | 64 ++++++++++++++++++++++++++++ crates/tools/src/dimension.rs | 25 +++++++++++ docs/dimensions.md | 8 ++-- docs/target-app-parity.md | 2 +- 6 files changed, 145 insertions(+), 27 deletions(-) diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 0b50358622..3e08f96977 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -425,10 +425,11 @@ impl DimensionSource { }) } /// Whether a path it measures differs between `before` and `after`, or is in only one of them. + /// A node without a path, or missing from both, counts as changed. pub fn art_changed(&self, before: &Document, after: &Document) -> bool { self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) { - (Some(old), Some(new)) => !std::ptr::eq(old, new) && old.path_data() != new.path_data(), - (old, new) => old.is_some() != new.is_some(), + (Some(old), Some(new)) => old.path_data().is_none() || (!std::ptr::eq(old, new) && old.path_data() != new.path_data()), + _ => true, }) } /// The map that took the measured art from `before` to `after`, when every path it measures @@ -861,28 +862,44 @@ impl Dimension { /// that side as the old line lay from its points. A dimension of a whole path /// ([`DimensionSource::Extent`]) first reads from `doc` the outermost points it measures in the /// new orientation, and its line keeps its distance from the whole path ([`Self::span`]), on - /// the side the middle of the old line is on. + /// the side the middle of the old line is on. A line that lay across the path goes as far past + /// the path as it lay from its first point. For such a dimension it is an error when the path + /// no longer exists, or when the line would lie more than 1,000,000 pt from its first point, + /// and the dimension is then left as it was. pub fn set_orientation(&mut self, orientation: Orientation, doc: &Document) -> Result<(), String> { if self.mode != DimensionMode::Linear || self.orientation == orientation { self.orientation = orientation; return Ok(()); } - let (handle, mut gap) = (self.handle(), self.offset.abs()); - if let Some(DimensionSource::Extent { .. }) = &self.source { - // Measured from the whole path. - let (low, high) = self.span(Some(doc)); - let line = self.a.to_vec2().dot(self.normal()) + self.offset; - gap = if line >= high { line - high } else { (low - line).max(0.0) }; + let mut next = self.clone(); + let (handle, mut gap) = (next.handle(), next.offset.abs()); + if let Some(DimensionSource::Extent { .. }) = &next.source { + // Measured from the whole path, relative to the first point, which the line is + // `offset` from. A line on the path's edge, to within the rounding of the + // projections, is outside it. + let n = next.normal(); + let base = next.a.to_vec2().dot(n); + let (low, high) = next.span(Some(doc)); + let eps = 8.0 * f64::EPSILON * ((next.a.x * n.x).abs() + (next.a.y * n.y).abs() + low.abs() + high.abs()); + let (low, high, line) = (low - base, high - base, next.offset); + gap = if line >= high - eps { + (line - high).max(0.0) + } else if line <= low + eps { + (low - line).max(0.0) + } else { + gap + }; } - self.orientation = orientation; - if let Some(DimensionSource::Extent { node }) = &self.source { - (self.a, self.b) = extent(doc, *node, orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?; + next.orientation = orientation; + if let Some(DimensionSource::Extent { node }) = &next.source { + (next.a, next.b) = extent(doc, *node, orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?; } - let n = self.normal(); - let across = |p: Point| p.to_vec2().dot(n); - let (low, high) = self.span(Some(doc)); - let h = across(handle); - let whole = matches!(self.source, Some(DimensionSource::Extent { .. })); + // Along the new normal, relative to the new first point, so that the result is the offset. + let n = next.normal(); + let base = next.a.to_vec2().dot(n); + let (low, high) = next.span(Some(doc)); + let (low, high, h) = (low - base, high - base, handle.to_vec2().dot(n) - base); + let whole = matches!(next.source, Some(DimensionSource::Extent { .. })); let at = if whole && h >= high { high + gap } else if whole && h <= low { @@ -894,11 +911,14 @@ impl Dimension { } else { low - gap }; - let offset = at - across(self.a); - if offset.is_finite() && offset.abs() <= 1e6 { - self.offset = offset; + if at.is_finite() && at.abs() <= 1e6 { + next.offset = at; + } else if whole { + // The old offset would put the line across the path. + return Err("Invalid dimension offset".into()); } - self.length = self.measured(); + next.length = next.measured(); + *self = next; Ok(()) } fn bisector(&self) -> Vec2 { diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 27e1d81ae8..610558be73 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Update Dimensions", [], None, - "{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}", + "{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on; for an extent source, an error when that would put the line more than 1,000,000 pt from its first point and no offset is given), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}", has_doc, update ), @@ -175,7 +175,14 @@ fn update(s: &mut Session, p: &Value) -> Result { dim.options = o.clone(); } if let Some(orientation) = orientation(p, dim.mode)? { - dim.set_orientation(orientation, doc).map_err(error)?; + // An offset given with the orientation replaces the one the orientation would + // give: the dimension takes the orientation, and `resolve` reads its points. + if let Err(e) = dim.set_orientation(orientation, doc) { + if p.get("offset").is_none() { + return Err(error(e)); + } + dim.orientation = orientation; + } } dim.offset = distance(p, dim.offset)?; dim.resolve(doc).map_err(error)?; diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 2cbd61de92..2c0738f737 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -596,6 +596,28 @@ fn a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws() { assert!(sides.iter().all(|v| *v > 1e-6) || sides.iter().all(|v| *v < -1e-6), "{a:?} to {b:?}: {sides:?}"); let nearest = sides.iter().map(|v| v.abs()).fold(f64::INFINITY, f64::min); assert!((nearest - 40.0).abs() < 1e-6, "nearest corner {nearest} pt from the line"); + + // A line across the path, 30 pt below the top, made vertical: it goes 30 pt past the path's + // side rather than onto it. + let rect = run(&mut s, "shape.rectangle", json!({"x":600,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":30}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"vertical"})); + let line = recipe(&s, id).line_ends().0.x; + assert!((line - 570.0).abs() < 1e-6 || (line - 730.0).abs() < 1e-6, "line at x = {line}, path from 600 to 700"); + // When that would put the line farther from its first point than an offset may be, the + // change is refused rather than leaving the line across the path. + let far = run(&mut s, "path.create", json!({"d":"M0 0 L950000 -100 L950000 200000 Z","closed":true}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":far},"orientation":"horizontal","offset":100000}))["id"] + .as_u64() + .unwrap(); + assert!(s.execute("dimension.update", &json!({"ids":[id],"orientation":"vertical"})).is_err()); + assert_eq!(recipe(&s, id).orientation, vectorcraft_doc::dimension::Orientation::Horizontal); + // An offset given with the orientation places the line instead. + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"vertical","offset":-30})); + let line = recipe(&s, id).line_ends().0.x; + assert!((line - 950030.0).abs() < 1e-6, "line at x = {line}"); } /// The line of a linked horizontal dimension keeps its gap from the outermost point on its side @@ -1223,6 +1245,48 @@ fn free_points_survive_a_native_file() { assert!(near(d.a, before.a + v) && near(d.b, before.b + v), "{before:?} → {d:?}"); } +/// Saved and opened again, a dimension of a whole path still measures the path: turned, the path +/// is wider than before, and so is the dimension. +#[test] +fn a_dimension_of_a_whole_path_survives_a_native_file() { + let value = |s: &Session, id: u64| text(s, id).trim_end_matches(" pt").parse::().unwrap(); + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-30}))["id"] + .as_u64() + .unwrap(); + let before = recipe(&s, id); + let doc = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let mut reopened = Session::new(); + reopened.add_document(doc, None); + assert_eq!(recipe(&reopened, id).source, before.source); + run(&mut reopened, "select.set", json!({"ids":[rect]})); + run(&mut reopened, "object.rotate", json!({"angle":30})); + let wide = 100.0 * 30f64.to_radians().cos() + 60.0 * 30f64.to_radians().sin(); + assert!((value(&reopened, id) - wide).abs() < 0.01, "{} against {wide}", text(&reopened, id)); + + // A file whose dimension names a node that is not there: the next edit unlinks it. + let mut v: Value = serde_json::from_slice(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + fn dangle(v: &mut Value) { + match v { + Value::Object(m) => { + if m.get("kind") == Some(&json!("extent")) { + m.insert("node".into(), json!(99999)); + } + m.values_mut().for_each(dangle); + } + Value::Array(a) => a.iter_mut().for_each(dangle), + _ => {} + } + } + dangle(&mut v); + let mut dangling = Session::new(); + dangling.add_document(vectorcraft_format::load(&serde_json::to_vec(&v).unwrap()).unwrap(), None); + assert!(recipe(&dangling, id).source.is_some()); + run(&mut dangling, "shape.rectangle", json!({"x":300,"y":300,"width":10,"height":10})); + assert!(recipe(&dangling, id).source.is_none(), "no longer linked"); +} + /// A linked dimension opened from a file with options it cannot be drawn with keeps its art, as a /// plain group, when the art it measures is deleted. #[test] diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index f5a9ca880c..fe82d4df30 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -2365,6 +2365,11 @@ mod tests { let above = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0))); assert_eq!(above["source"], json!({"kind":"extent","node":id})); assert_eq!(above["orientation"], json!("horizontal")); + // Past a corner, the side the pointer is farther out on decides. + let corner = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 280.0, 70.0))); + assert_eq!(corner["orientation"], json!("vertical")); + let corner = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 230.0, 40.0))); + assert_eq!(corner["orientation"], json!("horizontal")); let beside = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 260.0, 150.0))); assert_eq!(beside["orientation"], json!("vertical")); t.pointer(&c, &PointerEvent::new(PointerKind::Down, 260.0, 150.0)); @@ -2383,6 +2388,26 @@ mod tests { t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)); t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 100.0)); assert!(t.pending.is_none() && t.points.len() == 1, "a plain click picks a point"); + // After the first point, Alt does not make the path whole: the second click picks a point. + t.pointer(&c, &held(PointerKind::Move, 100.0, 150.0)); + assert!(matches!(t.hover, Some(Target::Segment(_))), "{:?}", t.hover); + t.pointer(&c, &held(PointerKind::Down, 100.0, 150.0)); + t.pointer(&c, &held(PointerKind::Up, 100.0, 150.0)); + let d = t.pending.as_ref().expect("the second click starts placing a dimension between the two points"); + assert!( + !matches!(d.source, Some(DimensionSource::Extent { .. })) + && d.a.distance(Point::new(150.0, 100.0)) < 1e-6 + && d.b.distance(Point::new(100.0, 150.0)) < 1e-6, + "{d:?}" + ); + + // A hovered segment's length also stays by the pointer at a high zoom. + let mut t = DimensionTool::default(); + t.pointer(&zoomed, &PointerEvent::new(PointerKind::Move, 150.0, 100.0)); + assert!(matches!(t.hover, Some(Target::Segment(_))), "{:?}", t.hover); + let o = t.overlays(&zoomed); + let near = |o: &Overlay| matches!(o, Overlay::Measure { p, .. } if p.distance(Point::new(150.0, 100.0)) < zoomed.tol(20.0)); + assert!(o.iter().any(near), "{o:?}"); } /// A point that Smart Guides leave where the pointer already is (the pointer right in line diff --git a/docs/dimensions.md b/docs/dimensions.md index ba1fd687df..f886371dbb 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -84,7 +84,7 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers placed. The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) - describes plotting an object's overall horizontal and vertical dimensions by holding Alt + describes plotting an object's horizontal and vertical dimensions by holding Alt (Option on macOS) over its path. With Alt held, hovering a path shows a box through the path's outermost points, as a Smart Guide when Smart Guides are on and in the tool's own color when they are off, with its width and height beside the pointer when Measurement Labels are on. @@ -177,8 +177,10 @@ another document. line from the first point: along the left normal of a → b for an aligned dimension, downward for a horizontal one and leftward for a vertical one. A negative offset goes the other way. - `dimension.update`: restyle or move existing dimensions, or change the orientation of linear - ones. A new orientation keeps the line on the side of the points it was on. An update that - changes nothing records no undo step. + ones. A new orientation keeps the line on the side of the points it was on. For a dimension of + a whole path, a new orientation that would put the line more than 1,000,000 pt from its first + point is an error unless the update also gives `offset`. An update that changes nothing records + no undo step. - `dimension.applyToAll`: every dimension takes one dimension's style, in one undo step. - `tool.select {"tool":"dimension"}` and `tool.setOption {"tool":"dimension","values":{"mode":"linear","style":{"units":"mm","scale":"1:10"}}}` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e35dd9151..6b185f98d9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -684,7 +684,7 @@ since 2026-10-01. **Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it. **Drawing tools, selected Dimension extension-line style (#7078):** Properties › Dimension exposes the selected editable dimension's existing extension-line color and weight. Both extension lines share that style, independently of the main dimension line and label. Apply to All keeps its full-style behavior for editable dimensions, leaving a protected dimension unchanged; Set as Default keeps the whole style for a new dimension created without explicit options, without changing existing dimensions. The dimension remains editable. Four cases in `crates/ui-egui/tests/dimension_extension_properties.rs` verify actual Properties input, both canvas extension lines, independent main-line/label styling, full-style Apply to All, locked and unselected controls, defaults/new dimensions, Undo/Redo, and native save/reopen with further editing. Existing document-color conversion is unchanged. The measured geometry and existing snapping behavior are unchanged; no whole-Dimension completion or score/hour change is claimed. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. -**Drawing tools, Dimension tool overall width and height of a path (#5590):** With Alt (Option on macOS) held, hovering a path shows a box through its outermost points (a Smart Guide when Smart Guides are on), and a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, as the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes; by VectorCraft's own rule the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height` and `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` cover it. +**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows a box through its outermost points (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. From 29ddc57821b8d559b0de4f704e6e48b1df98980f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:45:27 -0800 Subject: [PATCH 057/178] Scripts: what a script's commands open or change gives later runs no file access The commands a script runs could read the files that the documents open at the run's start link to, and could read and write the files of every open document. Both lists were taken from the documents as they were, so a document a script opened, or a link or data set value a script added, widened what the next run could read, and a document opened from a linked file could be saved over that file in the next run. - DocState::by_script records what scripts' commands did to a document since the person last opened or saved it: opened it, or changed it or gave it another file, keeping the document, its file and the file it was read from as they were before. The script host notes it after every command, and a save the person makes from the document's current content clears it. Revert keeps it, and a recovery copy restores the document as one a script opened. - The gate's document files and the linked files are taken from each document as the person left it (DocState::as_person_left). A document a script opened gives neither, in that run or a later one. - This replaces the per-run record of paths read through the linked files and ScriptGate::keeping_linked_read_only. - docs/mcp.md and docs/target-app-parity.md describe the rule. --- crates/engine/src/cmd/fileio/save.rs | 6 +- crates/engine/src/cmd/links.rs | 3 +- crates/engine/src/cmd/recovery.rs | 9 ++ crates/engine/src/doc_state.rs | 44 ++++++++ crates/engine/src/file_access.rs | 135 +++++-------------------- crates/engine/src/script/files.rs | 9 +- crates/engine/src/script/mod.rs | 44 ++++---- crates/engine/src/session/documents.rs | 2 + crates/engine/src/tests/script_run.rs | 110 ++++++++++++++++++++ docs/mcp.md | 15 +-- docs/target-app-parity.md | 2 +- 11 files changed, 238 insertions(+), 141 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f03dc6fe0d..7585861e9b 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1148,10 +1148,14 @@ impl SaveJob { /// Once written: Save and Save As (except to a template) make the file `st`'s own: path, /// title, format, options, and the snapshot as the saved state (edits made since the job was /// made keep the document modified; changes that are not edits to save don't, - /// [`DocState::same_content`]). + /// [`DocState::same_content`]). Saved outside a command a script runs, from the document's + /// content as it is now, the document is as the person left it ([`DocState::by_script`]). pub fn finish(self, st: &mut DocState) { let retargets = self.plan.retargets(); if let (true, Some(path)) = (retargets, self.plan.path) { + if !crate::file_access::in_script_command() && st.same_content(&self.source) { + st.by_script = None; + } st.path = Some(path); st.format = self.plan.format.id; st.save_options = self.plan.options; diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 9f1e7c3d79..3950d39f0b 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -410,7 +410,8 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { /// finds each linked image's and placed document's file from `base` and from no document (as /// output reads them, [`full_linked_images`]), the plate files of their own of images placed from /// DCS files, and the image files its data sets name. The commands a script runs may read these -/// for the documents open when the run began ([`crate::file_access::ScriptGate::linked`]). +/// for the documents open when the run began, as the person left them +/// ([`crate::file_access::ScriptGate::linked`]). pub(crate) fn files_linked(d: &Document, base: LinkBase) -> Vec { let mut out = vec![]; for g in groups(d, None) { diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 193e86b600..de64441623 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -874,6 +874,11 @@ struct Meta { /// images were kept apart: the document entry holds them). #[serde(skip_serializing_if = "BTreeMap::is_empty")] images: BTreeMap, + /// A command a script ran opened or changed the document since the person last saved it + /// ([`crate::DocState::by_script`]): the commands scripts run treat the restored document as + /// one a script opened. + #[serde(skip_serializing_if = "std::ops::Not::not")] + by_script: bool, } /// One of a copy's images: its entry in the copy's area. @@ -1195,6 +1200,7 @@ pub fn jobs(s: &mut Session, store: &Arc) -> Result<(Vec, file: &str) -> R st.imported_from = meta.imported_from.clone(); st.import_losses = meta.import_losses.clone(); st.format = SAVE_FORMATS.iter().copied().find(|f| *f == meta.format).unwrap_or("vectorcraft"); + if meta.by_script { + st.by_script = Some(crate::doc_state::ByScript::Opened); + } if let Some(pdf) = meta.native_pdf_compatible { st.save_options.insert("pdfCompatible".into(), json!(pdf)); } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index cabc774737..d57173ae76 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -128,6 +128,11 @@ pub struct DocState { /// paths the document links to are looked at within them later too, when the Links panel /// asks about a link outside any caller's scope. pub opened_by: Option>, + /// What the commands scripts ran did to the document since the person last opened or saved it: + /// `None` when they did nothing. The commands a script runs read and write the document's file, + /// and read the files it links to, only as the person left them ([`DocState::as_person_left`]). + /// Not saved. + pub(crate) by_script: Option, /// The live-effect plug-in stages deferred while the document is drawn on screen, and the time /// budget of its first view ([`vectorcraft_plugins::deferred`]). Not saved. pub plugin_effects: vectorcraft_plugins::deferred::Deferrals, @@ -146,6 +151,17 @@ pub struct DocState { pub(crate) inline_resolved: Option, } +/// What the commands scripts ran did to an open document since the person last opened or saved it +/// ([`DocState::by_script`]). +#[derive(Clone, Debug)] +pub(crate) enum ByScript { + /// A command a script ran opened it (or made it). + Opened, + /// A command a script ran changed it or gave it another file: the document, its file and the + /// file it was read from as they were before the first such command. + Changed { doc: Arc, path: Option, links_from: Option }, +} + /// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that /// was measured. #[derive(Clone, Debug, Default)] @@ -360,6 +376,7 @@ impl DocState { links_from: None, last_perspective: None, opened_by: file_access::current(), + by_script: None, empty_artboards: Default::default(), plugin_effects: Default::default(), art_to_fit: Default::default(), @@ -367,6 +384,33 @@ impl DocState { inline_resolved: None, } } + + /// The document, its file and the file it was read from as the person last left them, for the + /// commands scripts run ([`DocState::by_script`]): `None` for a document a script's command + /// opened. + pub(crate) fn as_person_left(&self) -> Option<(&Arc, Option<&str>, Option<&str>)> { + match &self.by_script { + None => Some((&self.doc, self.path.as_deref(), self.links_from.as_deref())), + Some(ByScript::Opened) => None, + Some(ByScript::Changed { doc, path, links_from }) => Some((doc, path.as_deref(), links_from.as_deref())), + } + } + + /// Notes what a command a script ran did to the document, which was `was` (the document, its + /// file and the file it was read from) before the command ran, or not open when `was` is + /// `None`. The first change is kept until the person saves the document. + pub(crate) fn note_script_command(&mut self, was: Option<(&Arc, &Option, &Option)>) { + if self.by_script.is_some() { + return; + } + let Some((doc, path, links_from)) = was else { + self.by_script = Some(ByScript::Opened); + return; + }; + if !Arc::ptr_eq(doc, &self.doc) || *path != self.path || *links_from != self.links_from { + self.by_script = Some(ByScript::Changed { doc: doc.clone(), path: path.clone(), links_from: links_from.clone() }); + } + } /// `measure`'s answer for the document now. `measure` runs once for each version of the document, /// so a menu that asks on every frame measures it once, and a change of the selection or the view /// keeps the answer. diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 890be26fb9..c20e37b58e 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -28,7 +28,7 @@ //! are read from, and the places its `File` and `Folder` objects read and write, inside the roots. //! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the //! files of the open documents, and for reading, the files the documents open when the run began -//! link to. +//! link to, each as the person last left the document. use std::cell::RefCell; use std::ffi::OsString; @@ -277,33 +277,31 @@ impl ScopeHandle { /// What a command a running script runs (`vc.run`) may read and write: the places the script's /// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app -/// were opened from or saved to. Reading, and only reading, the files the documents open when the -/// run began link to is allowed as well ([`ScriptGate::linked`]). The automation roots apply as -/// well. A path refused by its name alone ([`ScriptScope::refused_by_name`]) is refused here too. +/// were opened from or saved to by the person ([`crate::DocState::as_person_left`]). Reading, and +/// only reading, the files the documents link to as the person left them when the run began is +/// allowed as well ([`ScriptGate::linked`]). The automation roots apply as well. A path refused by +/// its name alone ([`ScriptScope::refused_by_name`]) is refused here too. #[derive(Clone, Debug)] pub(crate) struct ScriptGate { pub(crate) read: ScriptScope, pub(crate) write: ScriptScope, - /// The paths of the open documents' files, as the documents hold them. + /// The paths of the open documents' files, as the documents held them when the person last + /// opened or saved them. A document a script's command opened has none here. pub(crate) documents: Vec, - /// The files the documents open when the run began link to: readable, not writable. + /// The files the documents link to as the person left them when the run began: readable, not + /// writable. pub(crate) linked: LinkedFiles, /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). pub(crate) also: Option>, } /// The files the commands a script runs may only read because the documents open when the run -/// began link to them ([`ScriptGate::linked`]), and the paths a command read through them alone. -/// Clones share the record of those paths. +/// began link to them as the person left them ([`ScriptGate::linked`]). #[derive(Clone, Debug, Default)] pub(crate) struct LinkedFiles { /// The real paths of the files, as they were when the run's first command was run, sorted. A /// path that leads to another file now is not one of them. files: Arc<[PathBuf]>, - /// The paths, absolute as a document holds its file, that a command read only because they led - /// to one of `files` when it read them. A document opened from one of them stays read-only for - /// the rest of the run, wherever the path leads later. - read: Arc>>, } impl LinkedFiles { @@ -311,20 +309,6 @@ impl LinkedFiles { fn has(&self, real: &Path) -> bool { self.files.binary_search_by(|f| f.as_path().cmp(real)).is_ok() } - - /// The paths read through the files alone so far. - fn read_paths(&self) -> Vec { - self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() - } - - /// Notes that `path` was read through the files alone. - fn note_read(&self, path: &str) { - let path = crate::cmd::fileio::absolute_path(path); - let mut read = self.read.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if !read.contains(&path) { - read.push(path); - } - } } impl ScriptGate { @@ -340,23 +324,7 @@ impl ScriptGate { .collect(); real.sort(); real.dedup(); - LinkedFiles { files: real.into(), read: Arc::default() } - } - - /// This gate without the documents whose files only [`ScriptGate::linked`] lets it read, unless - /// they are among `before`, the files of the documents open when the run began: a document the - /// run opened from such a file is read, never written. A document counts as one when a command - /// read its file through the linked files alone, whatever the path leads to or the script may - /// read now, and when its file is one of them now that nothing else lets the gate read. - pub(crate) fn keeping_linked_read_only(mut self, before: &[String]) -> Self { - let plain = ScriptGate { documents: vec![], linked: LinkedFiles::default(), also: None, ..self.clone() }; - let (linked, read) = (self.linked.clone(), self.linked.read_paths()); - let only_linked = |d: &String| { - let real = if ScriptScope::refused_by_name(Path::new(d)) { None } else { resolve(d).ok() }; - read.contains(d) || (real.is_some_and(|real| linked.has(&real)) && plain.check(d, Access::Read).is_err()) - }; - self.documents.retain(|d| before.contains(d) || !only_linked(d)); - self + LinkedFiles { files: real.into() } } /// This gate with `next` at the end of its chain of `also` gates, so a path must pass every @@ -380,14 +348,7 @@ impl ScriptGate { Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; - if scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) { - return true; - } - let linked = matches!(access, Access::Read) && self.linked.has(&real); - if linked { - self.linked.note_read(path); - } - linked + scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || (matches!(access, Access::Read) && self.linked.has(&real)) }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -431,6 +392,11 @@ fn check_gate(path: &str, access: Access) -> Result<(), String> { GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access)) } +/// Whether this thread runs a command a script runs ([`with_script_gate`]). +pub(crate) fn in_script_command() -> bool { + GATE.with(|g| g.borrow().is_some()) +} + /// The roots in force on this thread, if any. pub fn current() -> Option> { match SCOPE.with(|s| s.borrow().clone()) { @@ -1072,59 +1038,10 @@ mod tests { let _ = std::fs::remove_dir_all(base); } - /// A document the run opened from a file only the linked files let it read is not written - /// through the document-file rule; one open when the run began, and one in the script's own - /// places, still is. + /// A path read through the linked files gives no access to the file it leads to after it is + /// pointed elsewhere by a link in one of its folders. #[test] - fn a_document_opened_from_a_linked_file_stays_read_only() { - let (base, _) = folders("linked-doc"); - let (secret, own) = (s(base.join("outside/secret.svg")), s(base.join("in/a.svg"))); - let gate = ScriptGate { - read: ScriptScope::of_folder(&base.join("in")), - write: ScriptScope::of_folder(&base.join("in")), - documents: vec![secret.clone(), own.clone()], - linked: ScriptGate::real_files([secret.clone(), own.clone()]), - also: None, - }; - let opened = gate.clone().keeping_linked_read_only(&[]); - assert!(opened.check(&secret, Access::Read).is_ok()); - assert!(opened.check(&secret, Access::Write).is_err(), "opened by the run from a linked file"); - assert!(opened.check(&own, Access::Write).is_ok(), "a file in the script's own places"); - let before = gate.keeping_linked_read_only(std::slice::from_ref(&secret)); - assert!(before.check(&secret, Access::Write).is_ok(), "open when the run began"); - let _ = std::fs::remove_dir_all(base); - } - - /// A document opened from a file a command read through the linked files alone stays - /// read-only after the script is allowed to read that file's folder, and after the file is - /// replaced by another one. - #[test] - fn a_document_read_through_a_linked_file_stays_read_only_after_a_read_grant() { - let (base, _) = folders("linked-granted"); - let secret = s(base.join("outside/secret.svg")); - let linked = ScriptGate::real_files([secret.clone()]); - let gate = |read: &str, documents: Vec| ScriptGate { - read: ScriptScope::of_folder(&base.join(read)), - write: ScriptScope::default(), - documents, - linked: linked.clone(), - also: None, - }; - assert!(gate("in", vec![]).check(&secret, Access::Read).is_ok(), "the command that opens it reads it through the linked file"); - let granted = gate("outside", vec![secret.clone()]).keeping_linked_read_only(&[]); - assert!(granted.check(&secret, Access::Read).is_ok()); - assert!(granted.check(&secret, Access::Write).is_err(), "a read grant made later does not make it writable"); - std::fs::remove_file(&secret).unwrap(); - std::fs::write(&secret, "").unwrap(); - let replaced = gate("in", vec![secret.clone()]).keeping_linked_read_only(&[]); - assert!(replaced.check(&secret, Access::Write).is_err(), "replaced by another file"); - let _ = std::fs::remove_dir_all(base); - } - - /// A document opened from a file a command read through the linked files alone gives no - /// access to the file its path leads to after the path is pointed elsewhere by a link. - #[test] - fn a_document_read_through_a_linked_file_gives_nothing_once_its_path_leads_elsewhere() { + fn a_path_read_through_a_linked_file_gives_nothing_once_it_leads_elsewhere() { let (base, _) = folders("linked-redirected"); #[cfg(unix)] let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok(); @@ -1144,20 +1061,18 @@ mod tests { return; } let (doc, elsewhere) = (s(via.join("a.svg")), s(second.join("a.svg"))); - let linked = ScriptGate::real_files([doc.clone()]); - let gate = |documents: Vec| ScriptGate { + let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), - documents, - linked: linked.clone(), + documents: vec![], + linked: ScriptGate::real_files([doc.clone()]), also: None, }; - assert!(gate(vec![]).check(&doc, Access::Read).is_ok(), "the command that opens it reads it through the linked file"); + assert!(gate.check(&doc, Access::Read).is_ok(), "read through the linked file"); std::fs::remove_dir(&via).or_else(|_| std::fs::remove_file(&via)).unwrap(); assert!(made(&second, &via)); - let opened = gate(vec![doc.clone()]).keeping_linked_read_only(&[]); for (path, access) in [(&doc, Access::Read), (&doc, Access::Write), (&elsewhere, Access::Read), (&elsewhere, Access::Write)] { - assert!(opened.check(path, access).is_err(), "{path} {access:?}"); + assert!(gate.check(path, access).is_err(), "{path} {access:?}"); } let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 2c63c9cd66..d0f54bfe32 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -54,8 +54,9 @@ //! for, loses the grant before that code runs. A run with nobody to ask gets `null` and //! [`NO_PICKER`]. //! - The commands a script runs with `vc.run` read and write only in the places above and in the -//! files of the open documents ([`crate::file_access::ScriptGate`]). They also read the files that -//! the documents open when the run began link to, as those links were then. +//! files the person gave the open documents ([`crate::file_access::ScriptGate`]). They also read +//! the files that the documents open when the run began link to, as the person last left those +//! documents and as those links led then. //! - `open('w')` empties the file at once; what a script writes is kept in memory, at most //! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at //! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an @@ -455,8 +456,8 @@ impl Disk { } } - /// The gate for a command the script runs: the places it reads and writes now, the files of the - /// open documents, `documents`, and the files it may only read because the documents open when + /// The gate for a command the script runs: the places it reads and writes now, the files the + /// person gave the open documents, `documents`, and the files it may only read because the documents open when /// the run began link to them, `linked`. pub(crate) fn gate(&self, documents: Vec, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate { crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 9e3419d10d..6d7181d283 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -799,15 +799,13 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, - /// The documents open when the run began, each with its own file and the file it was read from - /// ([`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files + /// The documents open when the run began as the person last left them, each with its own file + /// and the file it was read from ([`crate::DocState::as_person_left`], + /// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files /// they link to from them ([`Host::linked`]). run_docs: RefCell>, - /// The files of the documents open when the run began - /// ([`crate::file_access::ScriptGate::keeping_linked_read_only`]). - opened_before: Vec, - /// The files the documents open when the run began link to, and the paths the run's commands - /// read through them alone ([`crate::file_access::ScriptGate::linked`]). + /// The files the documents open when the run began link to as the person left them + /// ([`crate::file_access::ScriptGate::linked`]). linked: std::cell::OnceCell, } @@ -816,9 +814,9 @@ type RunDoc = (Arc, Option, Option); impl Host { /// The files the commands the run runs may read because the documents open when the run began - /// link to them, found once, from those documents as they were then: a link the run adds or - /// changes, and a document it opens, give it no file to read. Every command's gate shares the - /// record of the paths read through them. + /// link to them, found once, from those documents as the person left them: a link a script's + /// command added or changed, in this run or an earlier one, and a document it opened, give it + /// no file to read. fn linked(&self) -> crate::file_access::LinkedFiles { self.linked .get_or_init(|| { @@ -1269,12 +1267,19 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); - // The command reads and writes only where the script's own files may, and the open documents' files; - // it also reads the files the documents open when the run began link to, and does not write a document - // the run opened from one of those. - let linked = host.linked(); - let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect(), linked).keeping_linked_read_only(&host.opened_before); + // The command reads and writes only where the script's own files may, and the files the person gave + // the open documents; it also reads the files the documents open when the run began link to, as the + // person left them. A document a script's command opened gives it no file. + let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect(); + let gate = host.disk.borrow().gate(documents, host.linked()); + let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect(); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); + // What the command opened, changed or gave another file is not as the person left it. + for st in &mut s.docs { + let prior = was.iter().find(|(uid, _)| *uid == st.uid); + st.note_script_command(prior.map(|(_, (doc, path, from))| (doc, path, from))); + } + drop(was); // A file a command wrote before it failed is on disk all the same. let mut written = host.written.borrow_mut(); for path in crate::file_access::finish_recording_writes(r.is_ok()) { @@ -2074,8 +2079,13 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), - run_docs: RefCell::new(self.docs.iter().map(|st| (st.doc.clone(), st.path.clone(), st.links_from.clone())).collect()), - opened_before: self.docs.iter().filter_map(|st| st.path.clone()).collect(), + run_docs: RefCell::new( + self.docs + .iter() + .filter_map(DocState::as_person_left) + .map(|(doc, path, from)| (doc.clone(), path.map(str::to_string), from.map(str::to_string))) + .collect(), + ), linked: std::cell::OnceCell::new(), }); *link.borrow_mut() = Some(host.clone()); diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..d5d71c9704 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -402,6 +402,8 @@ impl Session { st.opened_as_tab = old.opened_as_tab; st.revision = old.revision + 1; st.format = old.format; + // What scripts' commands did to the document stays until the person saves it. + st.by_script = old.by_script.clone(); st.save_options = old.save_options.clone(); // The remembered artboard pick follows the artboards it named when the file read back has // the artboards the document had at the save, in the same order and with the same ids (a diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index d0a9723f3e..a57d3be23b 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -479,6 +479,116 @@ fn a_scripts_export_reads_the_files_the_documents_open_before_it_link_to() { let _ = std::fs::remove_dir_all(&dir); } +/// A script line that runs command `id` with `params` and logs `ok`, or `denied` when the gate +/// refuses a file. +fn tried(id: &str, params: &str) -> String { + format!( + "try {{ vc.run('{id}', {params}); vc.log('ok'); }} \ + catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n" + ) +} + +/// A document a script opened from a file that only a link let it read is not written in that run +/// or a later one, and gives a later run no access to its file once no document the person left +/// links to it. +#[test] +fn a_document_a_script_opened_from_a_linked_file_stays_read_only_in_later_runs() { + use crate::tests_links::{RED, open, place, png, save, session, write}; + let art = fresh_folder("gate-linked-runs").join("art"); + std::fs::create_dir_all(&art).unwrap(); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (pic, inner, poster) = (p(art.join("photo.png")), p(art.join("inner.vectorcraft")), p(art.join("poster.vectorcraft"))); + write(&pic, &png(60, 30, RED)); + let mut s = session(); + place(&mut s, &pic); + save(&mut s, &inner); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + place(&mut s, &inner); + save(&mut s, &poster); + s.execute("file.close", &json!({})).unwrap(); + open(&mut s, &poster); + let bytes = std::fs::read(&inner).unwrap(); + let opened = run(&mut s, &[tried("document.open", &format!("{{path: {inner:?}}}")), tried("document.save", "{}")].concat()).unwrap(); + assert_eq!(opened["log"], json!(["ok", "denied"]), "{opened}"); + assert_eq!(s.doc().unwrap().path.as_deref(), Some(inner.as_str())); + let mut log = vec![]; + let next = run(&mut s, &tried("document.save", "{}")).unwrap(); + log.push(next["log"][0].clone()); + // The person closes the document that links to it. + let at = s.documents().iter().position(|d| d.path.as_deref() == Some(poster.as_str())).unwrap(); + assert!(s.set_active(at)); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let later = run(&mut s, &tried("file.place", &format!("{{path: {inner:?}, at: [200, 150]}}"))).unwrap(); + log.push(later["log"][0].clone()); + assert_eq!(log, [json!("denied"), json!("denied")], "a save in the next run, then a read once nothing the person left links to it"); + assert_eq!(std::fs::read(&inner).unwrap(), bytes, "the linked file is as it was"); + let _ = std::fs::remove_dir_all(art.parent().unwrap()); +} + +/// A data set value a script gives a document, and a document a script opens, let no later run +/// read the files they name; once the person saves the document, the files its data sets name are +/// read again. +#[test] +fn what_a_script_adds_to_the_documents_lets_no_later_run_read_more() { + use crate::tests_links::{RED, place, png, session, write}; + let dir = fresh_folder("gate-linked-later"); + let (inside, art) = (dir.join("in"), dir.join("art")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&art).unwrap(); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (secret, other, mine) = (p(art.join("secret.png")), p(inside.join("other.vectorcraft")), p(inside.join("mine.vectorcraft"))); + write(&secret, &png(60, 30, RED)); + let mut s = session(); + place(&mut s, &secret); + s.execute("document.save", &json!({"path": other})).unwrap(); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let read_secret = tried("file.place", &format!("{{path: {secret:?}, at: [200, 150]}}")); + let set = format!( + "vc.run('variable.define', {{name: 'Photo', kind: 'image'}});\nvc.run('dataset.new', {{name: 'X', values: {{Photo: {secret:?}}}}});\n" + ); + run(&mut s, &set).unwrap(); + let mut log = vec![]; + log.push(run(&mut s, &read_secret).unwrap()["log"][0].clone()); + let own = s.active_index().unwrap(); + let r = run_allowed(&mut s, &inside, &tried("document.open", &format!("{{path: {other:?}}}"))).unwrap(); + assert_eq!(r["log"], json!(["ok"]), "{r}"); + log.push(run(&mut s, &read_secret).unwrap()["log"][0].clone()); + assert_eq!(log, [json!("denied"), json!("denied")], "after a data set value, then after a document a script opened"); + assert!(s.set_active(own)); + s.execute("document.save", &json!({"path": mine})).unwrap(); + let saved = run(&mut s, &read_secret).unwrap(); + assert_eq!(saved["log"], json!(["ok"]), "saved by the person: {saved}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A save the person started before a script's command changed the document, and that finishes +/// after it, does not let a later run read the files that change names. +#[test] +fn a_save_started_before_a_scripts_change_lets_no_later_run_read_more() { + use crate::cmd::fileio::{SaveMode, save_job, save_plan}; + use crate::tests_links::{RED, png, session, write}; + let dir = fresh_folder("gate-linked-save"); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (secret, mine) = (p(dir.join("secret.png")), p(dir.join("mine.vectorcraft"))); + write(&secret, &png(60, 30, RED)); + let mut s = session(); + let uid = s.doc().unwrap().uid; + let plan = save_plan(&s, SaveMode::SaveAs, &json!({"path": mine})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let set = format!( + "vc.run('variable.define', {{name: 'Photo', kind: 'image'}});\nvc.run('dataset.new', {{name: 'X', values: {{Photo: {secret:?}}}}});\n" + ); + run(&mut s, &set).unwrap(); + job.write(|_, _| Ok(())).unwrap(); + job.complete(&mut s, uid); + let r = run(&mut s, &tried("file.place", &format!("{{path: {secret:?}, at: [200, 150]}}"))).unwrap(); + assert_eq!(r["log"], json!(["denied"]), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A command a script runs does not save into the app's own libraries; the same command run /// outside a script does. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 6c0de9e418..62978099cb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3022,13 +3022,14 @@ VectorCraft writes files by these rules of its own: its `Folder.temp` and `Folder.userData` and to the open documents' own files. Such a command also reads, and does not write, the files that the documents open when the run began link to (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, - save, print or package of them includes the linked art. A document the script opens from such a file is not - saved over it for the rest of the run, also after the script is allowed to read that file's folder, and when its - path leads to another file later, the document does not let the script read or write that file. The files are - taken as those links led at the run's - first `vc.run`, and a path that leads to another file since is refused. A link the script adds or points - elsewhere, and a document it opens, does not let it read any file it could not read before. The automation - read roots still apply. + save, print or package of them includes the linked art. The files are taken as those links led at the run's + first `vc.run`, and a path that leads to another file since is refused. + Both rules count each document as the person last opened or saved it. A document that a script's command opened, + in this run or an earlier one, gives the commands no access to its file, and its links give them no file to read. + A document opened from a linked file is therefore not saved over that file unless the script may write there. A + link or data set value that a script's command adds or changes, and a file that a script's command saves a document + to, give later runs no access either. The person's next save of the document ends this. The automation read roots + still apply. A pick inside the folder that holds the settings gives `null` and sets `error` to `Script file access to the app's own folders is not allowed`. - A run with nobody to ask, as over MCP or the command line, gives `null` from every file dialog and sets `error` to diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 37b87a97d9..4c24e057f2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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, and read the files linked as the next line says; 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: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run`; a path that leads to another file since, a link the script adds or points elsewhere and a document it opens give it no further file to read, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - 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 a45e2dc710c28b9e81e54fe0adc904e2c8824876 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:57:54 -0800 Subject: [PATCH 058/178] Scripts: a linked file in the settings folder is not read through the linked list The read check for the files the documents link to now applies the script scope's fence of the folder that holds the settings, as the script's own reads do. A file in a place left open inside that folder is still read. --- crates/engine/src/file_access.rs | 35 ++++++++++++++++++++++++++++++-- docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c20e37b58e..50b7f725fa 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -348,7 +348,8 @@ impl ScriptGate { Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; - scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || (matches!(access, Access::Read) && self.linked.has(&real)) + let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real); + scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -663,7 +664,13 @@ impl ScriptScope { pub(crate) fn allows(&self, real: &Path) -> bool { (self.files.iter().any(|f| inside(real, f) && real.components().count() == f.components().count()) || self.roots.iter().any(|r| inside(real, r))) - && !self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o))) + && !self.keeps_out(real) + } + + /// Is the real path `real` in a folder kept out ([`ScriptScope::fence`]), and not in a place + /// left open there? + fn keeps_out(&self, real: &Path) -> bool { + self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o))) } /// The scope of a script run from a file in the folder whose real path, with its links already @@ -1038,6 +1045,30 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A linked file in a folder the script's scope keeps out, such as the settings folder, is not + /// read through the gate; one in a place left open there is. + #[test] + fn a_gate_reads_no_linked_file_in_a_folder_kept_out() { + let (base, _) = folders("linked-fenced"); + let (kept, open) = (base.join("outside/kept.svg"), base.join("outside/open/a.svg")); + std::fs::create_dir_all(base.join("outside/open")).unwrap(); + std::fs::write(&kept, "").unwrap(); + std::fs::write(&open, "").unwrap(); + let real = |p: &Path| resolve(&s(p.to_path_buf())).unwrap(); + let mut read = ScriptScope::of_folder(&base.join("in")); + read.fence(real(&base.join("outside")), &[real(&base.join("outside/open"))]); + let gate = ScriptGate { + read, + write: ScriptScope::default(), + documents: vec![], + linked: ScriptGate::real_files([s(kept.clone()), s(open.clone())]), + also: None, + }; + assert!(gate.check(&s(kept), Access::Read).is_err(), "in the folder kept out"); + assert!(gate.check(&s(open), Access::Read).is_ok(), "in a place left open"); + let _ = std::fs::remove_dir_all(base); + } + /// A path read through the linked files gives no access to the file it leads to after it is /// pointed elsewhere by a link in one of its folders. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 62978099cb..9967588b8f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3023,7 +3023,8 @@ VectorCraft writes files by these rules of its own: Such a command also reads, and does not write, the files that the documents open when the run began link to (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, save, print or package of them includes the linked art. The files are taken as those links led at the run's - first `vc.run`, and a path that leads to another file since is refused. + first `vc.run`, and a path that leads to another file since is refused. A linked file in the folder that holds + the settings is not read this way. Both rules count each document as the person last opened or saved it. A document that a script's command opened, in this run or an earlier one, gives the commands no access to its file, and its links give them no file to read. A document opened from a linked file is therefore not saved over that file unless the script may write there. A diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c24e057f2..8af5ee8f9e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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, and read the files linked as the next line says; 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: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - 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 f54afb117b27335113b0dcdb0985b901f014965c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 03:49:04 -0800 Subject: [PATCH 059/178] Smooth: a drag that would not make a path smoother leaves it as it was path.smoothRegion kept every changed result. A drag along the top of a clean ellipse split it from 4 to 5 anchors without smoothing it, took away its Live Shape and added an undo step, and a third drag left it with 7 anchors and about 20% more turning. Each subpath's result is now measured against the subpath at one spacing: how much it turns along its length, with each turn at an anchor counted twice, and how much it bends. The result is kept only when it turns no more than a thousandth more and has fewer anchors, turns less or bends less. Otherwise the subpath stays as it was; a path with no kept subpath keeps its Live Shape, is left out of ids and the counts, and a call that keeps nothing adds no undo step. The measure and the thresholds are VectorCraft's own. Three tests that dragged over a convex curve with nothing to smooth now drag over a sharp peak or crest, so they still test the reach search and a closed path of two anchors. --- crates/engine/src/cmd/draw2/commands.rs | 2 +- crates/engine/src/cmd/draw2/smooth.rs | 114 +++++++++++++++++++++++- crates/engine/src/tests/draw2.rs | 90 ++++++++++++++++--- docs/mcp.md | 8 ++ docs/target-app-parity.md | 1 + 5 files changed, 203 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index e4846367b5..d56c4be6b4 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Smooth", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side, and leaving a subpath as it is when the result would not be smoother (docs/mcp.md) → {ids, before, after}", has_selection, smooth_region ), diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..cca6cbbb2c 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -730,6 +730,89 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool out } +/// Most pieces [`roughness`] cuts one curved segment into. +const ROUGHNESS_SEGMENT_PIECES: usize = 1024; + +/// Most pieces [`roughness`] cuts the curved segments of one subpath into, shared equally by them. +const ROUGHNESS_PIECES: usize = 1 << 18; + +/// How rough the subpath `sp` is, measured along the lines between points on each curved segment +/// no more than `step` apart along its control polygon (at least 4 and at most +/// [`ROUGHNESS_SEGMENT_PIECES`] pieces a segment, fewer on a subpath of very many segments): how +/// much it turns along its length in radians, from the direction each segment leaves its first anchor +/// along to the one it arrives at its last anchor along, with each turn at an anchor counted twice; +/// and how much it bends, the sum of each turn between two pieces squared over their mean length. +/// `None` when a point or a turn is not a number. +fn roughness(sp: &SubPath, step: f64) -> Option<(f64, f64)> { + let segments = sp.segment_count(); + let most = (ROUGHNESS_PIECES / segments.max(1)).clamp(4, ROUGHNESS_SEGMENT_PIECES); + // The directions along the path, each with whether it leaves an anchor, and the pieces' vectors. + let (mut dirs, mut pieces): (Vec<(kurbo::Vec2, bool)>, Vec) = (vec![], vec![]); + for i in 0..segments { + let c = sp.segment(i); + if sp.segment_is_line(i) { + dirs.push((c.p3 - c.p0, true)); + pieces.push(c.p3 - c.p0); + continue; + } + let leave = [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default(); + let arrive = [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default(); + let len = polygon_len(c); + let k = if step > 0.0 && step.is_finite() && len.is_finite() { (len / step).ceil().clamp(4.0, most as f64) as usize } else { most }; + dirs.push((leave, true)); + let mut at = c.p0; + for j in 1..=k { + let q = if j == k { c.p3 } else { c.eval(j as f64 / k as f64) }; + dirs.push((q - at, false)); + pieces.push(q - at); + at = q; + } + dirs.push((arrive, false)); + } + // A direction of no length is left out; the turn at an anchor is then taken at the next one. + let mut kept: Vec<(kurbo::Vec2, bool)> = Vec::with_capacity(dirs.len()); + let mut at_anchor = false; + for (d, anchor) in dirs { + at_anchor |= anchor; + if d.hypot() > 1e-12 { + kept.push((d, at_anchor)); + at_anchor = false; + } + } + pieces.retain(|d| d.hypot() > 1e-12); + let turn = |u: kurbo::Vec2, v: kurbo::Vec2| u.cross(v).atan2(u.dot(v)).abs(); + let pairs = |n: usize| if sp.closed { n } else { n.saturating_sub(1) }; + let mut turning = 0.0; + for j in 0..pairs(kept.len()) { + let (u, (v, anchor)) = (kept[j].0, kept[(j + 1) % kept.len()]); + turning += if anchor { 2.0 } else { 1.0 } * turn(u, v); + } + let mut bending = 0.0; + for j in 0..pairs(pieces.len()) { + let (u, v) = (pieces[j], pieces[(j + 1) % pieces.len()]); + bending += turn(u, v).powi(2) / (0.5 * (u.hypot() + v.hypot())); + } + (turning.is_finite() && bending.is_finite()).then_some((turning, bending)) +} + +/// Whether the Smooth tool keeps `new`, the subpath `old` smoothed with the reach `radius` +/// (VectorCraft's own rule). Both are measured with [`roughness`] at one spacing, an eighth of the +/// reach or 1/512 of the diagonal of `old`'s control points, whichever is smaller. `new` must turn +/// no more than a thousandth more than `old` (counting a turn of less than 1 radian as 1), and it +/// must have fewer anchors, turn less, or bend more than a ten-thousandth less. A result that would +/// leave the path rougher, or that adds anchors or changes the path without smoothing it, is not +/// kept. +fn smoother(old: &SubPath, new: &SubPath, radius: f64) -> bool { + let size = old.anchors.iter().fold(None, |r: Option, a| { + let b = Rect::from_points(a.p, a.h_in).union_pt(a.h_out); + Some(r.map_or(b, |r| r.union(b))) + }); + let step = (radius / 8.0).min(size.map_or(0.0, |r| r.width().hypot(r.height()) / 512.0)); + let (Some((t0, b0)), Some((t1, b1))) = (roughness(old, step), roughness(new, step)) else { return false }; + let scale = t0.max(1.0); + t1 <= t0 + 1e-3 * scale && (new.anchors.len() < old.anchors.len() || t0 - t1 >= 1e-6 * scale || b0 - b1 > 1e-4 * b0) +} + pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { const C: &str = "path.smoothRegion"; let pts = points_param(p, "points", C)?; @@ -759,7 +842,10 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { _ => sp.clone(), }) .collect(); - if changed { + // A subpath whose result would not be smoother stays as it was. + let subs: Vec = + subs.into_iter().zip(&pd.subpaths).map(|(n, sp)| if n == *sp || smoother(sp, &n, radius) { n } else { sp.clone() }).collect(); + if changed && subs != pd.subpaths { let np = PathData::new(subs); before += pd.anchor_count(); after += np.anchor_count(); @@ -1246,4 +1332,30 @@ mod tests { assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]); assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]); } + + /// `sp` scaled by `k` about the origin. + fn scaled(sp: &SubPath, k: f64) -> SubPath { + let at = |p: Point| Point::new(p.x * k, p.y * k); + SubPath::new(sp.anchors.iter().map(|a| Anchor { p: at(a.p), h_in: at(a.h_in), h_out: at(a.h_out), ..*a }).collect::>(), sp.closed) + } + + /// The Smooth tool keeps a result that turns less, and not one that turns more with as many + /// anchors, one that adds an anchor and keeps the outline, or one that is the path itself, at + /// any size. + #[test] + fn the_smooth_tool_keeps_only_a_smoother_result() { + let round = ring(); + let mut bumped = ring(); + bumped.anchors[1].translate(kurbo::Vec2::new(0.0, -25.0)); + let split = start_nearest(ring(), round.segment(0).eval(0.3), &round); + assert_eq!(split.anchors.len(), 5, "{split:?}"); + for k in [1e-3, 1.0, 1e3] { + let (round, bumped, split) = (scaled(&round, k), scaled(&bumped, k), scaled(&split, k)); + let reach = 12.0 * k; + assert!(smoother(&bumped, &round, reach), "at {k}x a bump smoothed away is kept"); + assert!(!smoother(&round, &bumped, reach), "at {k}x a bump added is not kept"); + assert!(!smoother(&round, &split, reach), "at {k}x an anchor added on the outline is not kept"); + assert!(!smoother(&round, &round.clone(), reach), "at {k}x the same path is not kept"); + } + } } diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 75d7d081d9..3e2a319c01 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2306,13 +2306,13 @@ fn a_smooth_drag_that_comes_back_to_a_segment_smooths_where_it_comes_back() { assert!(gap < 0.5, "{between:?} is {gap} pt off the smoothed path"); } -/// A click on a curve 100,000 pt long, between the places a fixed number of samples along it would -/// look at, still finds the curve under it. +/// A click on a curve 100,000 pt long, at the sharp crest in its middle and between the places a +/// fixed number of samples along it would look at, still finds the curve under it. #[test] fn a_smooth_drag_finds_a_very_long_curve_under_it() { use kurbo::ParamCurve; let mut s = session(); - let anchors = [json!({"x": 0.0, "y": 0.0, "out": [30000.0, -9000.0]}), json!({"x": 100000.0, "y": 0.0, "in": [70000.0, -9000.0]})]; + let anchors = [json!({"x": 0.0, "y": 0.0, "out": [99800.0, -9000.0]}), json!({"x": 100000.0, "y": 0.0, "in": [200.0, -9000.0]})]; let id = smooth_test_path(&mut s, &anchors, false); let at = path(&s, id).subpaths[0].segment(0).eval(0.5 + 0.5 / 1024.0); assert_eq!(smooth_pass_ids(&mut s, &[at]), json!([id.0])); @@ -2329,9 +2329,9 @@ fn a_smooth_click_that_only_just_reaches_a_segment_smooths_it() { assert_ne!(path(&s, id), before); } -/// A drag that runs along a very long curve first and then crosses a second curve away from its -/// middle, with both of its anchors out of reach, smooths the second curve too: each curve in reach -/// gets the same share of the search, so the long one does not use it all. +/// A drag that runs along a very long curve first and then crosses a second curve at the peak in +/// its middle, with both of its anchors out of reach, smooths the second curve too: each curve in +/// reach gets the same share of the search, so the long one does not use it all. #[test] fn a_long_curve_searched_first_leaves_the_next_curve_its_share() { let mut s = session(); @@ -2342,7 +2342,7 @@ fn a_long_curve_searched_first_leaves_the_next_curve_its_share() { ); let next = smooth_test_path( &mut s, - &[json!({"x": 100100.0, "y": -100.0, "out": [100130.0, 200.0]}), json!({"x": 100100.0, "y": 900.0, "in": [100130.0, 600.0]})], + &[json!({"x": 100050.0, "y": 75.0, "out": [100150.0, -25.0]}), json!({"x": 100250.0, "y": 75.0, "in": [100150.0, -25.0]})], false, ); s.execute("select.set", &json!({"ids": [long.0, next.0]})).unwrap(); @@ -2372,14 +2372,14 @@ fn smoothing_smooths_an_open_two_anchor_path() { assert_eq!((a[0].p, a[a.len() - 1].p), (Point::new(100.0, 200.0), Point::new(200.0, 200.0)), "the ends stay"); } -/// A closed path of two anchors is smoothed along the middle of one side and stays closed. +/// A closed path of two anchors is smoothed at the peak in the middle of one side and stays closed. #[test] fn smoothing_smooths_a_closed_two_anchor_path() { use kurbo::ParamCurve; let mut s = session(); let anchors = [ - json!({"x": 100.0, "y": 300.0, "in": [100.0, 400.0], "out": [100.0, 200.0]}), - json!({"x": 300.0, "y": 300.0, "in": [300.0, 160.0], "out": [300.0, 440.0]}), + json!({"x": 100.0, "y": 300.0, "in": [100.0, 400.0], "out": [200.0, 150.0]}), + json!({"x": 300.0, "y": 300.0, "in": [200.0, 150.0], "out": [300.0, 440.0]}), ]; let id = smooth_test_path(&mut s, &anchors, true); let before = path(&s, id); @@ -2405,6 +2405,76 @@ fn smoothing_leaves_paths_out_of_reach_and_straight_segments_alone() { assert_eq!(path(&s, line), before); } +/// Whether `id` is still a Live Shape. +fn smooth_test_live(s: &Session, id: NodeId) -> bool { + matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { live: Some(_), .. }) +} + +/// Smooth drags over a clean ellipse, again and again and at any Fidelity, change nothing: the +/// ellipse has nothing to smooth, so no pass adds anchors to it, leaves it rougher, adds an undo step +/// or takes its Live Shape away. Each returns no ids and counts of 0, as a drag that reaches no path +/// does. +#[test] +fn smooth_drags_over_a_clean_ellipse_change_nothing() { + for fidelity in [0.05, 0.5, 2.5, 10.0] { + let mut s = session(); + let id = NodeId(s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 120})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = path(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + let pts: Vec<_> = smooth_drag_along(100.0, 160.0, 240.0).iter().map(|p| json!([p.x, p.y])).collect(); + for pass in 1..=4 { + let r = s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": fidelity})).unwrap(); + assert_eq!(r, json!({"ids": [], "before": 0, "after": 0}), "Fidelity {fidelity}, pass {pass}"); + assert_eq!(path(&s, id), before, "Fidelity {fidelity}, pass {pass}: {} anchors", path(&s, id).anchor_count()); + assert!(smooth_test_live(&s, id), "Fidelity {fidelity}, pass {pass}: still a Live Shape"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "Fidelity {fidelity}, pass {pass}: no undo step"); + } + } +} + +/// A Smooth drag over a clean ellipse and a jagged line selected together smooths the line only: the +/// result names the line and counts its anchors alone, the ellipse stays as it was and a Live Shape, +/// and one undo brings the line back. +#[test] +fn a_smooth_drag_over_an_ellipse_and_a_jagged_line_changes_only_the_line() { + let mut s = session(); + let ellipse = NodeId(s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 120})).unwrap()["id"].as_u64().unwrap()); + let mut seed = 11u64; + let anchors: Vec<_> = (0..=50).map(|i| json!({"x": 320.0 + 5.0 * f64::from(i), "y": 100.0 + smooth_noise(&mut seed)})).collect(); + let line = smooth_test_path(&mut s, &anchors, false); + s.execute("select.set", &json!({"ids": [ellipse.0, line.0]})).unwrap(); + let (oval, jagged) = (path(&s, ellipse), path(&s, line)); + let pts: Vec<_> = smooth_drag_along(100.0, 160.0, 580.0).iter().map(|p| json!([p.x, p.y])).collect(); + let r = s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 2.5})).unwrap(); + let smoothed = path(&s, line); + assert!(smoothed.anchor_count() < jagged.anchor_count(), "the line is smoothed: {} anchors", smoothed.anchor_count()); + assert_eq!(r, json!({"ids": [line.0], "before": jagged.anchor_count(), "after": smoothed.anchor_count()})); + assert_eq!(path(&s, ellipse), oval); + assert!(smooth_test_live(&s, ellipse), "the ellipse is still a Live Shape"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((path(&s, line), path(&s, ellipse)), (jagged, oval)); +} + +/// A Smooth drag at the lowest Fidelity still smooths a jagged line: it turns less and has fewer +/// anchors after each of three drags. +#[test] +fn a_smooth_drag_at_the_lowest_fidelity_still_smooths_a_jagged_line() { + let mut s = session(); + let mut seed = 11u64; + let anchors: Vec<_> = (0..=60).map(|i| json!({"x": 100.0 + 5.0 * f64::from(i), "y": 200.0 + smooth_noise(&mut seed)})).collect(); + let id = smooth_test_path(&mut s, &anchors, false); + let pts: Vec<_> = smooth_drag_along(200.0, 90.0, 410.0).iter().map(|p| json!([p.x, p.y])).collect(); + let mut before = path(&s, id); + for pass in 1..=3 { + s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 0.05})).unwrap(); + let after = path(&s, id); + assert!(after.anchor_count() < before.anchor_count(), "pass {pass}: {} -> {} anchors", before.anchor_count(), after.anchor_count()); + assert!(total_turning(&after) < total_turning(&before), "pass {pass}: turning {} -> {}", total_turning(&before), total_turning(&after)); + before = after; + } +} + /// The turn, in degrees, of `sp` at each of its anchors: round a closed path, and 0 at an open /// path's first and last anchors. fn smooth_anchor_turns(sp: &vectorcraft_geom::SubPath) -> Vec { diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..27b2b0d236 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7171,6 +7171,14 @@ own, and the corner keeps its place and the directions the path arrives and leav `fidelity`. A call that changes no anchor returns `{ids: [], before: 0, after: 0}` and adds no undo step. The 57.5° threshold is VectorCraft's own value. +`path.smoothRegion` keeps a subpath's result only when it is smoother. Measured along lines between points no more +than an eighth of `radius` apart (or 1/512 of the subpath's size when that is smaller), the result must turn no more +than a thousandth more than the subpath did, with each turn at an anchor counted twice, and it must have fewer +anchors, turn less, or bend more than a ten-thousandth less (the sum of each turn squared over the length it is taken +over). Any other result is dropped and the subpath stays as it was. A path none of whose subpaths is kept stays a Live +Shape if it was one, is left out of `ids` and is not counted in `before` or `after`. The measure and both thresholds +are VectorCraft's own. + In the desktop app, Object › Path › Smooth, the canvas context menu's Smooth… (listed while the selection holds a path) and the Contextual Task Bar's Smooth (with a path selected whole with the Direct Selection tool) open the slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog `smoothSlider` with field `level`) at the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..e5658b152a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1547,6 +1547,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `brush.freehand` refuses a `brush` that names no brush in the document, or is not a string, and a `style` other than "pencil" or "brush", with an error and no change or undo step, instead of drawing the plain path; the Paintbrush skips a chosen brush that has since been deleted (engine tests `brush_freehand_refuses_a_brush_or_style_it_cannot_use` and `paintbrush_tool_skips_a_deleted_brush`). A `brush.freehand` stroke and its brush are one undo step, so one Undo removes both. A `brush` for a path with no stroke (a continued or redrawn path without one, or a new filled "pencil" path while the stroke is None) is refused with "cannot apply brush ``: path has no stroke", and a key the command does not take with "unknown parameter", with no change or undo step; the no-stroke refusal is VectorCraft's own rule (engine tests `brush_freehand_direct_call_has_one_undo_step`, `brush_freehand_refuses_a_brush_on_a_path_without_a_stroke` and `brush_freehand_refuses_unknown_keys`). Each drag of the Smooth tool smooths the stretch of a selected path in its reach along its length before refitting it within Fidelity, so a wobble wider than Fidelity is smoothed out and another drag over the same place smooths it further, as [the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/smooth-tool.html) describes (`path.smoothRegion`). The smoothing spread (a third of the reach) and the rule that each refit stays within twice the distance the smoothing moved the path, so repeated drags do not drift from it, are VectorCraft's own. A drag over the whole of a closed path smooths it across its first anchor too, so a bump there is smoothed like any other and no corner is left; Object › Path › Smooth smooths a closed path across its first anchor the same way. + A Smooth drag changes a path only when the result is smoother, which [the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=79) gives as the aim of the tool's Fidelity: the result turns no more than a thousandth more along its length than the path did, with each turn at an anchor counted twice, and it has fewer anchors, turns less or bends less. Otherwise the path stays as it was and keeps its Live Shape, and the drag adds no undo step, so drags over a clean ellipse no longer add anchors to it or leave it rougher. A drag that only splits a convex curve into more anchors without smoothing it now leaves the path as it was. The measure and its thresholds are VectorCraft's own (engine tests `smooth_drags_over_a_clean_ellipse_change_nothing`, `a_smooth_drag_over_an_ellipse_and_a_jagged_line_changes_only_the_line`, `a_smooth_drag_at_the_lowest_fidelity_still_smooths_a_jagged_line` and `cmd::draw2::smooth::tests::the_smooth_tool_keeps_only_a_smoother_result`). When a Smooth tool drag reaches the first anchor of a closed path, the smoothed path starts at its point nearest where that anchor was: at an anchor there, or at a new anchor split into the curve without changing its outline. Dashes and type on the path start from that point. A drag that does not reach the first anchor leaves it first. This is VectorCraft's own rule (engine tests `smoothing_over_a_closed_paths_first_anchor_keeps_its_start` and `smoothing_a_whole_closed_path_with_a_spike_keeps_its_start`). The Smooth tool shows the Not Allowed cursor while no path is selected that it can act on (an editable path, not a guide, with three or more anchors on one of its subpaths or two anchors joined by a curve), and the release of a drag then sends no command and changes nothing; [the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/smooth-tool.html) has the path selected first. A selected path anywhere on the canvas gives the Smooth cursor wherever the pointer is. The Pencil with Alt key toggles to Smooth Tool on and the Blob Brush show Not Allowed the same way when Alt gives them the Smooth tool; the Paintbrush keeps its closing cursor, since its release with Alt closes the stroke. Use Precise Cursors leaves Not Allowed as it is. This cursor rule is VectorCraft's own (tools `smooth_shows_not_allowed_without_a_selected_path_to_smooth`, `borrowed_smooth_shows_not_allowed_without_a_selected_path_to_smooth`, `smoothing_release_sends_nothing_without_a_selected_path_to_smooth`; engine `use_precise_cursors_keeps_the_smooth_tools_not_allowed_pointer`). When a Smooth tool drag reaches the first or last anchor of an open path, that anchor stays where it is and the curve there leaves or arrives along the smoothed path within the reach, so a jagged first or last segment no longer sets the end's direction; an end where the smoothed path turns back by 90° or more keeps its segment's direction, and where the refitted stretch ends inside the path the curve keeps the direction of the part outside the drag. This rule is VectorCraft's own (`tests/draw2.rs`, `smoothing_an_open_path_turns_its_jagged_ends_with_the_path` and `a_smooth_drag_turns_only_the_end_it_reaches`). From 2fcee167569dbbef78cee791ab510a11e7e97cb9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:08:23 -0800 Subject: [PATCH 060/178] Scripts: a recovery copy keeps a script's change through a crash A recovery copy's details now say that a script's command changed the document before the new document entry is written, and a restore writes a copy's details before its document entry in the new area. A crash between the two writes no longer restores a script-changed document without that record, so a later run cannot read the files its links name. The docs say that a linked file in one of the script's own places inside the settings folder is still read. --- crates/engine/src/cmd/recovery.rs | 13 ++++++--- crates/engine/src/tests/recovery.rs | 42 +++++++++++++++++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 53 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index de64441623..fe6deb0b4b 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -1038,10 +1038,13 @@ impl RecoveryJob { let meta_name = format!("{}{META_EXT}", self.file); // The details name the images, so a crash between writing the document and its details // would pair the new document with the old copy's images: when the new document has - // images the old details don't name, they name both until the new document is in. - let old = read_meta(store, &self.file).images; - if meta.images.iter().any(|(k, r)| old.get(k).is_none_or(|o| o.blob != r.blob)) { + // images the old details don't name, they name both until the new document is in. Likewise + // when a script's command changed the document since the old details: they say so first. + let old_meta = read_meta(store, &self.file); + let old = old_meta.images; + if (meta.by_script && !old_meta.by_script) || meta.images.iter().any(|(k, r)| old.get(k).is_none_or(|o| o.blob != r.blob)) { let mut both = meta.clone(); + both.by_script |= old_meta.by_script; for (k, r) in old { both.images.entry(k).or_insert(r); } @@ -1503,8 +1506,10 @@ fn restore_one(s: &mut Session, store: &Arc, file: &str) -> R for (blob, data) in &blobs { store.write(&format!("{area}/{blob}"), data).map_err(EngineError::Other)?; } - store.write(&format!("{mine}{DOC_EXT}"), &bytes).map_err(EngineError::Other)?; + // The details go first: a crash in between leaves no copy without them (a copy is its + // document entry), and the copy in the old area stays whole. store.write(&format!("{mine}{META_EXT}"), &meta_bytes).map_err(EngineError::Other)?; + store.write(&format!("{mine}{DOC_EXT}"), &bytes).map_err(EngineError::Other)?; } // The copy's images in its old area go with the area, once no copy is left there. store.remove(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?; diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index eed8801efc..613a453d47 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -1714,3 +1714,45 @@ fn a_crash_between_a_copys_document_and_its_details_keeps_every_image() { assert_eq!(images_of(&s), images, "first copy: {first}"); } } + +/// A crash between writing a copy's document and its details, after a script's command changed +/// the document since the last copy, restores the document as one a script opened. +#[test] +fn a_crash_between_a_copys_document_and_its_details_keeps_a_scripts_change() { + let store = Arc::new(MemoryStore::default()); + let mut s = session_in(&store); + s.execute("file.recovery.save", &json!({})).unwrap(); + let source = "vc.run('shape.ellipse', {x: 80, y: 20, width: 20, height: 20});"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + assert!(s.doc().unwrap().by_script.is_some(), "the script's command changed the document"); + let doc = vectorcraft_doc::Document::clone(&s.doc().unwrap().doc); + s.recovery.set_store(Arc::new(DiesAfterDocument { inner: store.clone(), dead: Default::default() })); + assert!(s.execute("file.recovery.save", &json!({})).is_err(), "the details weren't written"); + drop(s); + let mut s = relaunch(&store); + assert_eq!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()), 1); + let count = |d: &vectorcraft_doc::Document| d.layers.iter().map(|l| l.count()).sum::(); + assert_eq!(count(&s.doc().unwrap().doc), count(&doc), "the new document is in"); + assert!(s.doc().unwrap().by_script.is_some(), "restored as a document a script opened"); +} + +/// A crash while a restore moves a copy into the app's own area leaves no copy that a later +/// restore opens without its details: a script's change is kept. +#[test] +fn a_crash_while_a_copy_is_restored_keeps_a_scripts_change() { + let store = Arc::new(MemoryStore::default()); + let mut s = session_in(&store); + let source = "vc.run('shape.ellipse', {x: 80, y: 20, width: 20, height: 20});"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + s.execute("file.recovery.save", &json!({})).unwrap(); + drop(s); + let mut s = Session::new(); + s.recovery.set_store(Arc::new(DiesAfterDocument { inner: store.clone(), dead: Default::default() })); + let _ = s.execute("file.recovery.restore", &json!({})); + drop(s); + let mut s = relaunch(&store); + assert!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()) >= 1); + for st in s.documents().iter().filter(|st| st.recovered) { + assert!(st.by_script.is_some(), "every restored copy keeps the script's change: {}", st.title()); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 9967588b8f..fede932de6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3024,7 +3024,7 @@ VectorCraft writes files by these rules of its own: (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, save, print or package of them includes the linked art. The files are taken as those links led at the run's first `vc.run`, and a path that leads to another file since is refused. A linked file in the folder that holds - the settings is not read this way. + the settings is not read this way unless it lies in one of the script's own places inside that folder. Both rules count each document as the person last opened or saved it. A document that a script's command opened, in this run or an earlier one, gives the commands no access to its file, and its links give them no file to read. A document opened from a linked file is therefore not saved over that file unless the script may write there. A diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8af5ee8f9e..b00ba51236 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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, and read the files linked as the next line says; 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: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read unless it lies in one of the script's own places inside that folder, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - 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 162a3c10651c6b6ea7cbe79810fada2224ce9602 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 05:00:00 -0800 Subject: [PATCH 061/178] Scripts: a recovery copy with unreadable details restores as a script's document A recovery copy whose details entry is missing or can't be parsed now restores as a document a script opened, and the details written for the moved copy say so, so a later restore does the same. A valid details entry without the script's mark still restores as the person left it. The script docs now say that a link does not let a command write the file it names: a linked file is written only where the script's write places or an open document's own file allow it. --- crates/engine/src/cmd/recovery.rs | 14 ++++++++++++-- crates/engine/src/tests/recovery.rs | 25 +++++++++++++++++++++++++ docs/mcp.md | 7 ++++--- docs/target-app-parity.md | 2 +- 4 files changed, 42 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index fe6deb0b4b..b81e0b3885 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -1465,8 +1465,18 @@ fn targets(s: &mut Session, store: &dyn RecoveryStore, cmd: &str, p: &Value) -> /// (for Save As) and format. The copy moves into this session's area (another crash keeps it). fn restore_one(s: &mut Session, store: &Arc, file: &str) -> Result { let bytes = store.read(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?; - let meta_bytes = store.read(&format!("{file}{META_EXT}")).unwrap_or_default(); - let meta: Meta = serde_json::from_slice(&meta_bytes).unwrap_or_default(); + // A details entry that is missing or can't be parsed does not say whether a script's command + // changed the document: the copy restores as one a script opened, and the details written for + // it say so. + let read = store.read(&format!("{file}{META_EXT}")).ok().and_then(|b| serde_json::from_slice::(&b).ok().map(|m| (m, b))); + let (meta, meta_bytes) = match read { + Some(both) => both, + None => { + let meta = Meta { by_script: true, ..Meta::default() }; + let bytes = serde_json::to_vec_pretty(&meta).map_err(|e| EngineError::Other(e.to_string()))?; + (meta, bytes) + } + }; let (mut doc, _, mut warnings) = fileio::native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?; // A frame whose first paragraph continues from the frame before draws it without the // paragraph's first-line indent and list marker. diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index 613a453d47..08a691f222 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -1756,3 +1756,28 @@ fn a_crash_while_a_copy_is_restored_keeps_a_scripts_change() { assert!(st.by_script.is_some(), "every restored copy keeps the script's change: {}", st.title()); } } + +/// A copy whose details entry is missing or can't be parsed restores as a document a script +/// opened, and so does the copy that restore writes, after a later crash; a valid details entry +/// without the script's mark restores as the person left it. +#[test] +fn a_copy_without_readable_details_restores_as_a_scripts_document() { + let cases: [Option<&[u8]>; 3] = [Some(b"{ not json"), None, Some(b"{}")]; + for details in cases { + let store = Arc::new(MemoryStore::default()); + let mut s = session_in(&store); + let r = s.execute("file.recovery.save", &json!({})).unwrap(); + let entry = format!("{}.json", r["saved"][0]["file"].as_str().unwrap()); + drop(s); + match details { + Some(bytes) => store.write(&entry, bytes).unwrap(), + None => store.remove(&entry).unwrap(), + } + let by_script = details != Some(b"{}".as_slice()); + for round in 1..=2 { + let mut s = relaunch(&store); + assert_eq!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()), 1, "{details:?}, restore {round}"); + assert_eq!(s.doc().unwrap().by_script.is_some(), by_script, "{details:?}, restore {round}"); + } + } +} diff --git a/docs/mcp.md b/docs/mcp.md index fede932de6..1bd3166ee0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3020,9 +3020,10 @@ VectorCraft writes files by these rules of its own: `Script file access denied` and the path, saving into a user library (swatches, brushes, symbols or graphic styles) included; reading the app's own libraries is allowed. A script given as `source` that a person allowed nothing writes only in its `Folder.temp` and `Folder.userData` and to the open documents' own files. - Such a command also reads, and does not write, the files that the documents open when the run began link to - (linked images, placed files, the plate files of a DCS image and the images their data sets name), so an export, - save, print or package of them includes the linked art. The files are taken as those links led at the run's + Such a command also reads the files that the documents open when the run began link to (linked images, placed + files, the plate files of a DCS image and the images their data sets name), so an export, save, print or package + of them includes the linked art. A link does not let the command write the file it names: it writes a linked file + only when the rule above lets it write there. The files are taken as those links led at the run's first `vc.run`, and a path that leads to another file since is refused. A linked file in the folder that holds the settings is not read this way unless it lies in one of the script's own places inside that folder. Both rules count each document as the person last opened or saved it. A document that a script's command opened, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b00ba51236..ce4d074eef 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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, and read the files linked as the next line says; 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: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files, and do not write them, as the links led at the run's first `vc.run` and as the person last opened or saved each document; a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read unless it lies in one of the script's own places inside that folder, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. + - Scripts: an export, save, print or package that a script runs with `vc.run` includes the linked images and placed files of the documents open when the run began, also when those files are outside the script's own places. VectorCraft's own rules: the commands read those files as the links led at the run's first `vc.run` and as the person last opened or saved each document; a link does not let them write the file it names, and they write a linked file only where the previous line lets them write (the script's own write places and the open documents' own files); a path that leads to another file since, a link or data set value a script's command adds or changes, in that run or an earlier one, and a document a script's command opens give it no further file to read, and a document a script's command opened gives the commands no access to its own file until the person saves it; a linked file in the folder that holds the settings is not read unless it lies in one of the script's own places inside that folder, and the automation read roots still apply. `crates/engine/src/tests/script_run.rs`, `file_access::tests` in `vectorcraft-engine`. - 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 80b089590b90c8df7fe4799bbaf7c8d20a339eec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 05:37:52 -0800 Subject: [PATCH 062/178] Smooth: the long-curve click test puts the crest between the places a fixed search would look at The click sat 0.15 pt from two of 1,024 evenly spaced places along the curve, so a fixed search found it too. The crest is now a cusp halfway between two of 65 evenly spaced places and more than the 12 pt reach from each, and the test checks that distance before the drag. --- crates/engine/src/tests/draw2.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 3e2a319c01..289a11f9cc 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2306,15 +2306,25 @@ fn a_smooth_drag_that_comes_back_to_a_segment_smooths_where_it_comes_back() { assert!(gap < 0.5, "{between:?} is {gap} pt off the smoothed path"); } -/// A click on a curve 100,000 pt long, at the sharp crest in its middle and between the places a -/// fixed number of samples along it would look at, still finds the curve under it. +/// A click on the sharp crest of a curve 100,000 pt wide finds the curve under it, although the crest +/// lies halfway between two of 65 evenly spaced places along the curve and more than the click's 12 pt +/// reach from each of them, so a search that looked only at those places would miss it. #[test] fn a_smooth_drag_finds_a_very_long_curve_under_it() { use kurbo::ParamCurve; let mut s = session(); - let anchors = [json!({"x": 0.0, "y": 0.0, "out": [99800.0, -9000.0]}), json!({"x": 100000.0, "y": 0.0, "in": [200.0, -9000.0]})]; + // The crest is a cusp at t0: the control points are chosen so that the curve's velocity is 0 there. + let (t0, wide): (f64, f64) = (32.5 / 64.0, 1.0e5); + let (d0, d2) = ((wide, -wide), (wide, wide)); + let d1 = ((1.0 - t0).powi(2) * d0.0 + t0 * t0 * d2.0, (1.0 - t0).powi(2) * d0.1 + t0 * t0 * d2.1); + let d1 = (-d1.0 / (2.0 * t0 * (1.0 - t0)), -d1.1 / (2.0 * t0 * (1.0 - t0))); + let (p1, p2) = (d0, (d0.0 + d1.0, d0.1 + d1.1)); + let anchors = [json!({"x": 0.0, "y": 0.0, "out": [p1.0, p1.1]}), json!({"x": p2.0 + d2.0, "y": p2.1 + d2.1, "in": [p2.0, p2.1]})]; let id = smooth_test_path(&mut s, &anchors, false); - let at = path(&s, id).subpaths[0].segment(0).eval(0.5 + 0.5 / 1024.0); + let curve = path(&s, id).subpaths[0].segment(0); + let at = curve.eval(t0); + let nearest_place = (0..=64).map(|k| curve.eval(f64::from(k) / 64.0).distance(at)).fold(f64::INFINITY, f64::min); + assert!(nearest_place > 12.0, "the nearest of 65 places is {nearest_place} pt from the click"); assert_eq!(smooth_pass_ids(&mut s, &[at]), json!([id.0])); } From e50cc27abd314b6a63e32e0419ae08bb054d3f61 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 08:18:11 -0800 Subject: [PATCH 063/178] 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 d2fdc9728a674754caab11ca664f6103344da859 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:13:22 -0800 Subject: [PATCH 064/178] Pen: Quick Pen marks an arc's center with a cross while the arc is drawn Wherever the Quick Pen tool shows an arc's protractor (while the arc is dragged, or as the piece the next click adds), it also draws a small cross at the arc's center, as the circle and three-point arc tools draw theirs. The cross is VectorCraft's own behavior. Adds a test for the cross while hovering and dragging. --- crates/engine/src/tests/quickpen.rs | 27 +++++++++++++++++++++++++++ crates/tools/src/quickpen.rs | 18 ++++++++++++------ docs/mcp.md | 3 ++- docs/target-app-parity.md | 1 + 4 files changed, 42 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index c6174aa19f..3612dfe2b9 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -677,6 +677,33 @@ fn a_hovered_arc_shows_the_protractor_with_the_rubber_band() { } } +/// The two arms of a cross centered on `c` among the overlays. +fn crosses_at(o: &[Overlay], c: Point) -> usize { + o.iter().filter(|o| matches!(o, Overlay::Line { a, b, .. } if a.midpoint(*b).distance(c) < 1e-9)).count() +} + +/// While a half circle from (200, 100) to (300, 100) is dragged, or is the piece the next click +/// adds, the tool shows a cross at its center, (250, 100); while a line is dragged, it shows none. +#[test] +fn an_arc_shows_a_cross_at_its_center() { + let mut s = session(); + quick_pen(&mut s); + let center = pt(250.0, 100.0); + for (action, arms) in [("line", 0), ("sharpArc", 2)] { + key(&mut s, ToolKey::Escape); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap(); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": action})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 100.0), view()).unwrap(); + assert_eq!(crosses_at(&s.overlays(view()), center), arms, "hovering, {action}"); + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 150.0), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 100.0), view()).unwrap(); + assert_eq!(crosses_at(&s.overlays(view()), center), arms, "dragging, {action}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 100.0), view()).unwrap(); + } +} + /// With Measurement Labels on, hovering after the path's last point shows the distance label /// beside the pointer; with them off, no label shows. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index d542af832c..6b6a56b408 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -15,12 +15,13 @@ //! //! While an arc is drawn, by a drag or as the piece the next click adds, the tool shows a //! protractor around the arc's center: a tick across its circle every 15° from where the arc -//! starts, a longer one every 90°, and one where it ends. The piece the next click adds shows its -//! protractor only while the Pen tool's rubber band preference shows that piece. With Smart Guides -//! on, the end of a continuous arc goes onto the nearest tick of that protractor when the tick lies -//! within the snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither -//! the grid nor pixels snap drawn points. A sharp-corner arc sweeps its arc size, so its end is not -//! snapped to a tick. Shift does not constrain Quick Pen points, so it does not change the snapping. +//! starts, a longer one every 90°, and one where it ends, with a small cross at the center. The +//! piece the next click adds shows its protractor only while the Pen tool's rubber band preference +//! shows that piece. With Smart Guides on, the end of a continuous arc goes onto the nearest tick +//! of that protractor when the tick lies within the snapping tolerance of the pointer, no other +//! Smart Guide snaps the point, and neither the grid nor pixels snap drawn points. A sharp-corner +//! arc sweeps its arc size, so its end is not snapped to a tick. Shift does not constrain Quick Pen +//! points, so it does not change the snapping. use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; @@ -49,6 +50,8 @@ pub const MAX_TURN: f64 = 359.0; pub const TICK_STEP: f64 = 15.0; /// Half the length (screen points) of a protractor tick; the ticks every 90° are twice as long. const TICK_PX: f64 = 4.0; +/// Half the length (screen points) of each arm of the cross at an arc's center. +const CROSS_PX: f64 = 4.0; /// Screen points the pointer moves after a press before the press drags. const DRAG_PX: f64 = 3.0; /// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight @@ -824,6 +827,9 @@ impl Tool for QuickPenTool { }; if let Some(arc) = arc { o.push(Overlay::Path { path: protractor(cx, &arc), color: FEEDBACK, width: 1.0, dashed: false }); + let (c, arm) = (arc.center, cx.tol(CROSS_PX)); + o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color: FEEDBACK, dashed: false }); + o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: FEEDBACK, dashed: false }); } if self.press.is_none() && let Some(h) = end.or(self.hover) diff --git a/docs/mcp.md b/docs/mcp.md index 65383caa1b..c5659c8b5c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7335,7 +7335,8 @@ that piece. With Smart Guides on, the end of a continuous arc snaps onto the nea circle, when that tick lies within the Smart Guides snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc sweeps the arc size, so its end does not snap to a tick. Shift does not constrain Quick Pen points, so it does not change the tick snapping. The -protractor, its 15° step and the tick snapping are VectorCraft's own behavior. +protractor, its 15° step and the tick snapping are VectorCraft's own behavior. A small cross marks the arc's center +wherever the protractor shows; the cross is VectorCraft's own behavior too. Selecting the tool shows its toolbar on the canvas: Straight Line, Continuous Arc and Sharp Corner Arc set `action`, Flip Arc flips the last sharp-corner arc as C does (`tool.quickPen.flipArc {}`, which first finishes any pending tool edit, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 581f72bb0f..fb125077f7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -643,6 +643,7 @@ 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, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. - **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. +- **Quick Pen arc center:** wherever the Quick Pen tool shows an arc's protractor, it also marks the arc's center with a small cross. The cross is VectorCraft's own behavior. Test: engine `an_arc_shows_a_cross_at_its_center`. 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. From dcff4edc3d61ba43eb8d0c3c76b5eacab4c34bb8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:55:41 -0800 Subject: [PATCH 065/178] 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 20425b6914113ec7d59bdfd0562ee8b480a3f036 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:09:35 -0800 Subject: [PATCH 066/178] Pen: Quick Pen snaps no first continuous arc to a tick and hides a stale hover A continuous arc that starts a path has no direction to follow and sweeps the arc size, as a sharp-corner arc does. Moving its end onto a protractor tick put the end on a circle the drawn arc does not follow, so `tick_end` now gives no tick for it. The hover keeps the snap settings it was made with (`SnapSettings` in guides/snap.rs: the window, zoom, snapping options, tolerances, Alignment Guides and construction angles). After one of them changes under a still pointer, the hover's rubber band, protractor, distance label and Smart Guides are hidden until the pointer moves, also through a press, so the preview shows no point that a click would not place. A press also drops the hover, so after a click puts an arc's end on a tick no preview runs from that end back to the pointer. While the pointer hovers, the tool asks the canvas to hover it again when the view, the document or the selection changes (`wants_rehover`). --- crates/engine/src/tests/quickpen.rs | 89 +++++++++++++++++++++++++++++ crates/tools/src/guides.rs | 2 +- crates/tools/src/guides/snap.rs | 22 +++++++ crates/tools/src/quickpen.rs | 56 +++++++++++++----- crates/tools/src/quickpen/tests.rs | 15 +++++ docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 7 files changed, 177 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 3612dfe2b9..fe4a9ae553 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -616,6 +616,23 @@ fn a_click_puts_a_continuous_arc_end_on_a_tick() { } } +/// After a click puts a continuous arc's end on a tick away from the pointer, no preview runs from +/// the placed end back to where the pointer was; the next move shows the preview again. +#[test] +fn a_click_on_a_tick_leaves_no_preview_back_to_the_pointer() { + let at = arc_end_61(); + let v = ViewInfo::default(); + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), v).unwrap(); + press_in(&mut s, &[(at.x, at.y)], v); + assert!(drawn_end(&s).distance(tick_60()) < 1e-6); + let label = |s: &mut Session| s.overlays(v).iter().any(|o| matches!(o, Overlay::Measure { .. })); + assert!(!label(&mut s), "no distance label back to the pointer"); + s.pointer(&PointerEvent::new(PointerKind::Move, 400.0, 300.0), v).unwrap(); + assert!(label(&mut s)); +} + /// Hovering near a tick as a continuous arc puts the distance label beside the tick; after Alt /// switches the action, the same hover puts it beside the pointer. #[test] @@ -640,6 +657,78 @@ fn a_hover_snaps_to_a_tick_only_for_a_continuous_arc() { } } +/// A hover made with Smart Guides off shows nothing once they are turned on under the still +/// pointer, so it shows no tick that a click would not use (another path's anchor under the +/// pointer takes the click). The next move shows the hover again, its label beside the anchor; +/// once Smart Guides are turned off again, its guides are hidden with it, also after a click. +#[test] +fn a_hover_shows_nothing_after_smart_guides_change() { + let at = arc_end_61(); + let off = ViewInfo { smart_guides: false, ..Default::default() }; + let on = ViewInfo::default(); + let mut s = session(); + s.execute("shape.line", &json!({"x1": at.x, "y1": at.y, "x2": 600, "y2": at.y})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + continuous_arc_after_a_line(&mut s, off); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), off).unwrap(); + let label = |s: &mut Session, v: ViewInfo| { + s.overlays(v).iter().find_map(|o| match o { + Overlay::Measure { p, .. } => Some(*p), + _ => None, + }) + }; + assert!(label(&mut s, off).is_some()); + assert_eq!(label(&mut s, on), None, "the hover from before the change shows nothing"); + 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"); + // 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"); +} + +/// While the pointer hovers, the tool asks the canvas to hover it again when the view, the document +/// or the selection changes under a still pointer, so the snapped point follows the art; a press +/// stops it until the next move. +#[test] +fn a_hover_is_hovered_again_when_the_art_changes() { + let mut s = session(); + continuous_arc_after_a_line(&mut s, view()); + assert!(!s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Move, 280.0, 180.0), view()).unwrap(); + assert!(s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 180.0), view()).unwrap(); + assert!(!s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 180.0), view()).unwrap(); + assert!(!s.tool_wants_rehover()); +} + +/// A hover on the path's last point, which another path's anchor shares, shows that anchor's Smart +/// Guide; after Smart Guides are turned off, a click there adds nothing and the guide stays hidden +/// while the button is held and after it is let go. +#[test] +fn a_click_that_adds_nothing_keeps_a_stale_hover_hidden() { + let off = ViewInfo { smart_guides: false, ..Default::default() }; + let on = ViewInfo::default(); + let mut s = session(); + s.execute("shape.line", &json!({"x1": 200, "y1": 100, "x2": 200, "y2": 400})).unwrap(); + 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); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), off).unwrap(); + assert!(only_points(&mut s, off), "the guide stays hidden while the button is held"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 100.0), off).unwrap(); + assert_eq!(undo_steps(&s), steps, "the click adds nothing"); + assert!(only_points(&mut s, off), "the guide stays hidden"); +} + /// While a press drags an arc, the tool shows its protractor; while it drags a line, it shows none. #[test] fn an_arc_drag_shows_the_protractor() { diff --git a/crates/tools/src/guides.rs b/crates/tools/src/guides.rs index e9f7bf7318..ccbf258512 100644 --- a/crates/tools/src/guides.rs +++ b/crates/tools/src/guides.rs @@ -25,10 +25,10 @@ mod snap; mod targets; pub(crate) use bitangent::TangentLine; -pub(crate) use snap::hold_on_path; pub use snap::{ DEFAULT_CONSTRUCTION_ANGLES, DrawSnap, HandleSnap, Leave, PointSnap, construction_angles, distance_guides, snap_draw, snap_pick, square, }; +pub(crate) use snap::{SnapSettings, hold_on_path}; use targets::Kind; pub use targets::Targets; #[cfg(test)] diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 948f5668b9..0a48b35001 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -376,6 +376,28 @@ impl SnapKey { } } +/// Every setting that can move a snapped drawn point besides the document: the window and the +/// zoom, the options and tolerances [`SnapKey`] holds except the guides' color and labels, and +/// the construction guides' angles a [`Leave::segment`] follows. A tool that keeps a hover's +/// snapped point compares two of these to see whether a click would still snap the same way. +#[derive(PartialEq)] +pub(crate) struct SnapSettings { + screen: Option, + zoom: f64, + view: [bool; 7], + snap_to_glyph: Option, + alignment_lines: bool, + tolerances: [f64; 2], + angles: &'static [f64], +} + +impl SnapSettings { + pub(crate) fn of(cx: &ToolContext) -> Self { + let SnapKey { screen, view, snap_to_glyph, style, tolerances, .. } = SnapKey::of(cx, &[]); + Self { screen, zoom: cx.zoom, view, snap_to_glyph, alignment_lines: style.lines, tolerances, angles: cx.construction_angles } + } +} + /// The part of the document the window shows (none headless: all of it). pub(super) fn visible(cx: &ToolContext) -> Option { let s = cx.screen?; diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 6b6a56b408..f4bf64a648 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -20,8 +20,11 @@ //! shows that piece. With Smart Guides on, the end of a continuous arc goes onto the nearest tick //! of that protractor when the tick lies within the snapping tolerance of the pointer, no other //! Smart Guide snaps the point, and neither the grid nor pixels snap drawn points. A sharp-corner -//! arc sweeps its arc size, so its end is not snapped to a tick. Shift does not constrain Quick Pen -//! points, so it does not change the snapping. +//! arc, and a continuous arc that has no direction to follow, sweep the arc size, so their ends are +//! not snapped to a tick. After a snap setting changes under a still pointer, the hover's preview, +//! protractor, distance label and Smart Guides are hidden until the pointer moves; when the view, +//! the document or the selection changes, the canvas hovers the still pointer again. Shift does +//! not constrain Quick Pen points, so it does not change the snapping. use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; @@ -31,7 +34,7 @@ use vectorcraft_doc::{Document, MAX_COORD, Node, NodeId, NodeKind}; use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; use crate::draw2::FEEDBACK; -use crate::guides::{DrawSnap, Leave}; +use crate::guides::{DrawSnap, Leave, SnapSettings}; use crate::pen::{continue_from, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -237,12 +240,14 @@ pub fn arc_circle(sp: &SubPath, piece: &Piece) -> Option { /// The protractor tick nearest the end of a continuous arc ending at `piece.to`: the point on the /// arc's circle ([`arc_circle`]) where the sweep is a whole number of [`TICK_STEP`]s. None for -/// other pieces, an arc without a circle, a sweep that rounds to nothing or to a whole circle, and -/// a tick past the document's coordinate limit. +/// other pieces, a continuous arc with no direction to follow (it sweeps the arc size, as a +/// sharp-corner arc does), an arc without a circle, a sweep that rounds to nothing or to a whole +/// circle, and a tick past the document's coordinate limit. pub fn tick_end(sp: &SubPath, piece: &Piece) -> Option { if piece.stroke != Stroke::ContinuousArc { return None; } + arrival(sp)?; let arc = arc_circle(sp, piece)?; let step = TICK_STEP.to_radians(); let s = (arc.sweep / step).round() * step; @@ -374,10 +379,11 @@ pub struct QuickPenTool { press: Option, hover: Option, snap: DrawSnap, - /// The pointer while it hovers, and whether it lies on a Smart Guide target ([`Self::landed`]); - /// `hover` is where Smart Guides put it. The protractor's tick is applied when the point is - /// used ([`Self::hover_end`]), for the action chosen then. A press clears it. - pointer: Option<(Point, bool)>, + /// The pointer while it hovers, whether it lies on a Smart Guide target ([`Self::landed`]), and + /// the snap settings then; `hover` is where Smart Guides put it. The protractor's tick is + /// applied when the point is used ([`Self::hover_end`]), for the action chosen then. A press + /// clears it. + pointer: Option<(Point, bool, SnapSettings)>, } impl Default for QuickPenTool { @@ -508,12 +514,22 @@ impl QuickPenTool { /// Where the next click's piece after `sp` ends while the pointer hovers: the hover's snapped /// point, on the protractor's tick when [`Self::on_tick`] puts it there. None before the - /// pointer moves after a press. + /// pointer moves after a press, and while the hover is stale ([`Self::hover_stale`]). fn hover_end(&self, cx: &ToolContext, sp: &SubPath) -> Option { - let ((p, landed), q) = (self.pointer?, self.hover?); + let (&(p, landed, _), q) = (self.pointer.as_ref()?, self.hover?); + if self.hover_stale(cx) { + return None; + } Some(self.on_tick(cx, sp, self.piece_to(q), p, q, landed)) } + /// Whether the snap settings changed since the pointer last moved: the hover's snapped point + /// and its tick may then not be where a click puts the point, so the hover shows nothing until + /// the pointer moves again. + fn hover_stale(&self, cx: &ToolContext) -> bool { + self.pointer.as_ref().is_some_and(|(_, _, at)| *at != SnapSettings::of(cx)) + } + /// During a press that adds a piece: the points before that piece, as the press found them /// (the last two, see [`tail`]). fn before_piece(&self) -> Option { @@ -636,13 +652,20 @@ impl Tool for QuickPenTool { let (on, from) = self.leave(cx).unzip(); let q = self.snap.hover(cx, p, on.as_slice(), from.as_ref()); self.hover = Some(q); - self.pointer = Some((p, on.is_some() && self.landed(cx, p, q, from.as_ref()))); + self.pointer = Some((p, on.is_some() && self.landed(cx, p, q, from.as_ref()), SnapSettings::of(cx))); vec![] } PointerKind::Down => { if self.press.is_some() { return vec![]; } + // The hover shows again when the pointer moves after the press: the point the press + // places can lie on a tick away from it. A stale hover's guides stay hidden, also + // when the press snaps nothing. + if self.hover_stale(cx) { + self.snap.clear(); + } + self.hover = None; self.pointer = None; self.press_down(cx, p) } @@ -812,8 +835,14 @@ impl Tool for QuickPenTool { self.pointer = None; } + /// A hover's snapped point and its tick depend on the art and the view under a still pointer. + fn wants_rehover(&self) -> bool { + self.pointer.is_some() + } + fn overlays(&self, cx: &ToolContext) -> Vec { - let mut o = self.snap.guides().to_vec(); + // A stale hover's Smart Guides go with its preview. + let mut o = if self.hover_stale(cx) { vec![] } else { self.snap.guides().to_vec() }; let Some((id, sp)) = self.active(cx) else { return o }; let end = if self.press.is_none() { self.hover_end(cx, sp) } else { None }; // The arc being drawn: the piece a press drags, or the piece the next click adds while the @@ -832,6 +861,7 @@ impl Tool for QuickPenTool { o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: FEEDBACK, dashed: false }); } if self.press.is_none() + && !self.hover_stale(cx) && let Some(h) = end.or(self.hover) { if cx.pen_rubber_band diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index 5fb23565c5..1319948423 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -259,6 +259,21 @@ fn a_tick_past_the_coordinate_limit_is_not_used() { assert!(tick_end(&sp, &inside).is_some(), "a tick inside the limit is used"); } +/// A continuous arc that starts a path has no direction to follow and sweeps the arc size, so its +/// end has no tick to go to: with a 100° arc size, a tick at 105° would move the end off the arc +/// the click draws. +#[test] +fn a_continuous_arc_without_a_direction_has_no_tick() { + let sp = start(pt(0.0, 0.0)); + let pc = Piece { turn: 100.0, ..piece(100.0, 10.0, Stroke::ContinuousArc) }; + let arc = arc_circle(&sp, &pc).unwrap(); + assert!((arc.sweep.to_degrees() - 100.0).abs() < 1e-9, "{arc:?}"); + assert!(tick_end(&sp, &pc).is_none()); + // After a line, the same end has a tick. + let sp = build(&start(pt(-100.0, 0.0)), &[piece(0.0, 0.0, Stroke::Line)], false); + assert!(tick_end(&sp, &pc).is_some()); +} + /// The protractor has a tick every 15° of the sweep, each across the arc's circle, the first /// through the arc's start; a sweep that is not a whole number of steps adds a tick at its end. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index c5659c8b5c..a01a4440e4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7333,8 +7333,12 @@ center: a tick across the arc's circle every 15° from where the arc starts, a l arc ends. The piece the next click adds shows its protractor only while Enable Rubber Band for the Pen tool shows that piece. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick of its protractor, on the same circle, when that tick lies within the Smart Guides snapping tolerance of the pointer, no other Smart Guide snaps the -point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc sweeps the arc size, so its end -does not snap to a tick. Shift does not constrain Quick Pen points, so it does not change the tick snapping. The +point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc, and a continuous arc that +starts a path and so has no direction to follow, sweep the arc size, so their ends do not snap to a tick. After a snap +setting (Smart Guides, Snap to Point, Snap to Grid, Snap to Pixel or a snapping tolerance) changes under a still +pointer, the hover's preview, its protractor, its distance label and its Smart Guides are hidden until the pointer +moves. When the view, the document or the selection changes, the canvas hovers the still pointer again. Shift does not constrain Quick Pen points, so it +does not change the tick snapping. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. A small cross marks the arc's center wherever the protractor shows; the cross is VectorCraft's own behavior too. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fb125077f7..06234e9f34 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -642,7 +642,7 @@ 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, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. -- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. +- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Quick Pen arc center:** wherever the Quick Pen tool shows an arc's protractor, it also marks the arc's center with a small cross. The cross is VectorCraft's own behavior. Test: engine `an_arc_shows_a_cross_at_its_center`. 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. From a5433617279e68e8fbc6a840d540fd22672dd2b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:41:30 -0800 Subject: [PATCH 067/178] Pen: Alt tapped during a Quick Pen press moves the end on or off the tick at once A press keeps the pointer and the snapped point for the end of the piece it adds. When Alt changes the action during the press, the end goes through the protractor's tick again for the new action, so a continuous arc that snapped to a tick and becomes a sharp-corner arc ends at the pointer, and a piece that becomes a continuous arc goes onto the tick, without waiting for the next drag. This also covers a press that has not dragged. --- crates/engine/src/tests/quickpen.rs | 28 +++++++++++++++++ crates/tools/src/quickpen.rs | 47 ++++++++++++++++++++--------- docs/mcp.md | 4 ++- docs/target-app-parity.md | 2 +- 4 files changed, 64 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index fe4a9ae553..375f648ac8 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -616,6 +616,34 @@ fn a_click_puts_a_continuous_arc_end_on_a_tick() { } } +/// Alt tapped during a press moves the end of the piece for the new action at once, with no +/// further drag: a continuous arc's end on the 60° tick goes to the pointer once the piece is a +/// sharp-corner arc, after a drag and after a press that has not dragged, and a line's end at the +/// pointer goes onto the tick once the piece is a continuous arc. +#[test] +fn an_alt_tap_during_a_press_moves_the_end_for_the_new_action() { + let at = arc_end_61(); + let v = ViewInfo::default(); + // (drag first, Alt taps before the press, the end before Alt, the end after it) + for (drag, taps, before, after) in [(true, 0, tick_60(), at), (false, 0, tick_60(), at), (true, 2, at, tick_60())] { + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + for _ in 0..taps { + key(&mut s, ToolKey::AltTap); + } + let first = if drag { (280.0, 140.0) } else { (at.x, at.y) }; + s.pointer(&PointerEvent::new(PointerKind::Down, first.0, first.1), v).unwrap(); + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, at.x, at.y), v).unwrap(); + } + assert!(drawn_end(&s).distance(before) < 1e-6, "{drag} {taps}: {:?}", drawn_end(&s)); + s.tool_key(ToolKey::AltTap, Mods::default(), v).unwrap(); + assert!(drawn_end(&s).distance(after) < 1e-6, "{drag} {taps} after Alt: {:?}", drawn_end(&s)); + s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y), v).unwrap(); + assert!(drawn_end(&s).distance(after) < 1e-6, "{drag} {taps} placed: {:?}", drawn_end(&s)); + } +} + /// After a click puts a continuous arc's end on a tick away from the pointer, no preview runs from /// the placed end back to where the pointer was; the next move shows the preview again. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index f4bf64a648..2e5eb61491 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -364,12 +364,14 @@ impl Drawing { } /// The press in progress: where it went down, whether it has dragged, and whether it began an undo -/// step (a piece it adds). +/// step (a piece it adds). `end` is the pointer for the end of the piece it adds and where the +/// snap put that end, before the protractor's tick. #[derive(Clone, Copy, Debug, PartialEq)] struct Press { at: Point, dragged: bool, begun: bool, + end: Option<(Point, Point)>, } pub struct QuickPenTool { @@ -478,12 +480,12 @@ impl QuickPenTool { let before = self.before_piece(); let from = before.as_ref().and_then(|sp| sp.anchors.last()).map(|a| Leave::segment(cx, a.p, false).without_contact()); let q = self.snap.drag(cx, p, from.as_ref()); - let q = match (&before, self.drawing.as_ref().and_then(|dr| dr.pieces.last())) { - (Some(sp), Some(piece)) => { - let landed = piece.stroke == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); - self.on_tick(cx, sp, *piece, p, q, landed) - } - _ => q, + if let Some(pr) = self.press.as_mut() { + pr.end = Some((p, q)); + } + let q = match self.drawing.as_ref().and_then(|dr| dr.pieces.last()) { + Some(piece) => self.press_end(cx, piece, p, q), + None => q, }; let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) else { return vec![] }; if last.to == q { @@ -493,6 +495,15 @@ impl QuickPenTool { vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()] } + /// Where `piece`, which a press draws, ends with the pointer at `p` that the snap put at `q`: + /// on the protractor's tick when [`Self::on_tick`] puts it there for the piece's action. + fn press_end(&self, cx: &ToolContext, piece: &Piece, p: Point, q: Point) -> Point { + let Some(sp) = self.before_piece() else { return q }; + let from = sp.anchors.last().map(|a| Leave::segment(cx, a.p, false).without_contact()); + let landed = piece.stroke == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); + self.on_tick(cx, &sp, *piece, p, q, landed) + } + /// `q`, where the last snap put the end of `piece` drawn after `sp` (the pointer being at `p`), /// moved onto the protractor's nearest tick ([`tick_end`]) when Smart Guides are on, the tick /// lies within the snapping tolerance of the pointer, and nothing else snapped the point: the @@ -582,15 +593,15 @@ impl QuickPenTool { return vec![]; } let from = self.leave(cx).map(|l| l.1); - let q = self.snap.press(cx, p, &[id], from.as_ref()); - let landed = self.action == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); - let q = self.on_tick(cx, sp, self.piece_to(q), p, q, landed); + let snapped = self.snap.press(cx, p, &[id], from.as_ref()); + let landed = self.action == Stroke::ContinuousArc && self.landed(cx, p, snapped, from.as_ref()); + let q = self.on_tick(cx, sp, self.piece_to(snapped), p, snapped, landed); let (piece, kept) = (self.piece_to(q), sp.anchors.len()); if let Some(dr) = self.drawing.as_mut() { dr.push(piece, kept); dr.before_press = shared_node(cx.doc, id).cloned(); } - self.press = Some(Press { at: p, dragged: false, begun: true }); + self.press = Some(Press { at: p, dragged: false, begun: true, end: Some((p, snapped)) }); return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) @@ -800,11 +811,17 @@ impl Tool for QuickPenTool { } ToolKey::AltTap => { self.action = self.action.next(); - // A drag under way draws its piece with the new action. + // A drag under way draws its piece with the new action. Its end goes through the + // protractor's tick again for that action: a continuous arc's end on a tick goes + // back to where the snap put the pointer for another action, and the other way. if self.press.is_some_and(|pr| pr.begun) && self.held(cx) { - let (action, turn) = (self.action, self.turn); - if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { - (last.stroke, last.turn, last.flip) = (action, turn, false); + let (action, turn, end) = (self.action, self.turn, self.press.and_then(|pr| pr.end)); + let piece = self.drawing.as_ref().and_then(|dr| dr.pieces.last()).map(|&pc| { + let pc = Piece { stroke: action, turn, flip: false, ..pc }; + end.map_or(pc, |(p, q)| Piece { to: self.press_end(cx, &pc, p, q), ..pc }) + }); + if let (Some(piece), Some(last)) = (piece, self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut())) { + *last = piece; } return vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } diff --git a/docs/mcp.md b/docs/mcp.md index a01a4440e4..a529564ad9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7334,7 +7334,9 @@ arc ends. The piece the next click adds shows its protractor only while Enable R that piece. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick of its protractor, on the same circle, when that tick lies within the Smart Guides snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc, and a continuous arc that -starts a path and so has no direction to follow, sweep the arc size, so their ends do not snap to a tick. After a snap +starts a path and so has no direction to follow, sweep the arc size, so their ends do not snap to a tick. Alt tapped +during a press moves the piece's end for the new action at once: off the tick when a continuous arc becomes a +sharp-corner arc, and onto it when the piece becomes a continuous arc. After a snap setting (Smart Guides, Snap to Point, Snap to Grid, Snap to Pixel or a snapping tolerance) changes under a still pointer, the hover's preview, its protractor, its distance label and its Smart Guides are hidden until the pointer moves. When the view, the document or the selection changes, the canvas hovers the still pointer again. Shift does not constrain Quick Pen points, so it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 06234e9f34..03f9478ece 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -642,7 +642,7 @@ 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, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. -- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. +- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, Alt tapped during a press moves the piece's end onto or off the tick for the new action, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `an_alt_tap_during_a_press_moves_the_end_for_the_new_action`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Quick Pen arc center:** wherever the Quick Pen tool shows an arc's protractor, it also marks the arc's center with a small cross. The cross is VectorCraft's own behavior. Test: engine `an_arc_shows_a_cross_at_its_center`. 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. From 4a6924669e6cef186cee3bd1e21aef26fcf74a25 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:25:03 -0800 Subject: [PATCH 068/178] 3D: meshes carry UVs, smooth bevel normals and a part index Every mesh the 3D effects build now carries texture coordinates for each corner and a part for each triangle (front, back, side, front bevel, back bevel, end cap, cut side). Corners shared by two bands of one bevel take the mean of the bands' normals unless the bevel turns there by 60 degrees or more or a band lies flat toward the front or back, and Inflate's puffed front and back keep the surface's own normals. The vector facets do not change. - Caps, Rotate's plane and Inflate's front and back map the art's bounds; walls and bevels run u along each contour and v from the front cap's edge to the back cap's; Revolve's side runs u around the sweep and v along the profile. - OBJ, glTF and USD write every corner's texture coordinates, not only those of faces with mapped graphics. - Mesh::join checks its index offsets, and joining or exporting a mesh whose lists do not match or that holds a value that is not a number is an error. Docs: docs/three-d.md (3D meshes), docs/mcp.md, docs/effects-parity.md, docs/target-app-parity.md. --- crates/effects/src/lib.rs | 2 +- crates/effects/src/revolve.rs | 11 +- crates/effects/src/solids.rs | 13 +- crates/engine/src/cmd/fileio/mesh3d.rs | 32 +- crates/engine/src/cmd/fileio/mesh3d/tests.rs | 62 ++- crates/engine/src/tests/assets_3d.rs | 14 +- crates/three-d/src/lib.rs | 54 ++- crates/three-d/src/mesh.rs | 121 +++++- crates/three-d/src/mesh/tests.rs | 24 +- crates/three-d/src/mesh/tests_attributes.rs | 432 +++++++++++++++++++ crates/three-d/src/shadow.rs | 6 +- crates/three-d/src/solid.rs | 2 +- crates/three-d/src/solid/build.rs | 289 +++++++++++-- crates/three-d/src/solid/inflate.rs | 55 ++- crates/three-d/src/solid/tests.rs | 2 +- crates/three-d/src/tests/cut_sides.rs | 4 +- 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/effects-parity.md | 2 +- docs/mcp.md | 8 +- docs/target-app-parity.md | 1 + docs/three-d.md | 31 ++ 45 files changed, 1081 insertions(+), 109 deletions(-) create mode 100644 crates/three-d/src/mesh/tests_attributes.rs diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index c46ab0c76e..91715c500d 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -117,7 +117,7 @@ pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; pub use trap::TRAP; pub use vectorcraft_three_d::PlanarFace; -pub use vectorcraft_three_d::{BevelProfile, Mesh}; +pub use vectorcraft_three_d::{BevelProfile, Mesh, MeshPart}; pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version}; mod catalog; diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index a6f0d6b2ae..dfaf8c35e6 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -893,8 +893,11 @@ fn surface_meshes( } let (mesh, on) = vectorcraft_three_d::revolve_mesh_surface(path, rule, b, options)?; let (mut side, mut rest, mut art) = (vectorcraft_three_d::Mesh::default(), vectorcraft_three_d::Mesh::default(), vec![]); - for (t, points) in mesh.triangles.iter().zip(&on) { - let corner = |i: u32| mesh.positions.get(i as usize).copied().zip(mesh.normals.get(i as usize).copied()); + for ((t, points), part) in mesh.triangles.iter().zip(&on).zip(&mesh.parts) { + let corner = |i: u32| { + let i = i as usize; + Some((*mesh.positions.get(i)?, *mesh.normals.get(i)?, *mesh.uvs.get(i)?)) + }; let Some(corners) = t.iter().map(|&i| corner(i)).collect::>>() else { continue }; let into = match points { Some(points) => { @@ -904,11 +907,13 @@ fn surface_meshes( None => &mut rest, }; let base = into.positions.len() as u32; - for (p, n) in corners { + for (p, n, uv) in corners { into.positions.push(p); into.normals.push(n); + into.uvs.push(uv); } into.triangles.push([base, base + 1, base + 2]); + into.parts.push(*part); } let mut out = vec![]; if !rest.is_empty() { diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 5d1493fcd7..ea5d72f7ef 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -2893,10 +2893,13 @@ fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity }; let Some(on_mesh) = on_mesh else { continue }; let (mut taken, mut left, mut art) = (Mesh::default(), Mesh::default(), vec![]); - for t in &rest.triangles { - let corner = |i: u32| rest.positions.get(i as usize).copied().zip(rest.normals.get(i as usize).copied()); + for (t, part) in rest.triangles.iter().zip(&rest.parts) { + let corner = |i: u32| { + let i = i as usize; + Some((*rest.positions.get(i)?, *rest.normals.get(i)?, *rest.uvs.get(i)?)) + }; let Some(corners) = t.iter().map(|&i| corner(i)).collect::>>() else { continue }; - let points: Option> = corners.iter().map(|(m, n)| on_mesh.art_point(*m, *n)).collect(); + let points: Option> = corners.iter().map(|(m, n, _)| on_mesh.art_point(*m, *n)).collect(); let into = match points { Some(points) => { art.extend(points); @@ -2905,11 +2908,13 @@ fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity None => &mut left, }; let base = into.positions.len() as u32; - for (m, n) in corners { + for (m, n, uv) in corners { into.positions.push(m); into.normals.push(n); + into.uvs.push(uv); } into.triangles.push([base, base + 1, base + 2]); + into.parts.push(*part); } rest = left; if !taken.is_empty() { diff --git a/crates/engine/src/cmd/fileio/mesh3d.rs b/crates/engine/src/cmd/fileio/mesh3d.rs index 2e781772ea..205a3cec35 100644 --- a/crates/engine/src/cmd/fileio/mesh3d.rs +++ b/crates/engine/src/cmd/fileio/mesh3d.rs @@ -7,7 +7,9 @@ //! about the point the object turns about: in points in OBJ and USD (whose layer says how many //! meters a unit is), in meters in glTF, as its specification asks. glTF and USD colors are linear, //! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since -//! an open solid or a turned plane is seen from both sides. +//! an open solid or a turned plane is seen from both sides. Every corner carries its normal and +//! texture coordinates (`vt`, `TEXCOORD_0`, `primvars:st`); a mesh whose lists do not match, or +//! that holds a value that is not a number, is refused before anything is written. //! //! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its //! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through @@ -140,6 +142,7 @@ pub(crate) fn image_maps(textures: &[Option]) -> Vec { /// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after /// its texture). `textures` holds the picture of each part that has one, in the order of `parts`. pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option]) -> Result)>, String> { + check_parts(parts)?; let (images, image) = images(parts.len(), textures); let maps: Vec = images.iter().map(|(_, map)| map.is_some()).collect(); let names = mesh_file_names(stem, format, &maps)?; @@ -180,6 +183,21 @@ impl Scene<'_> { let t = self.textures.get(k)?.as_ref()?; Some((t.uv.as_slice(), (*self.image.get(k)?)?)) } + + /// Part `k`'s texture coordinates, one for each corner, 0 to 1 across from the left and down + /// from the top: its picture's when it has one, else its mesh's own. + fn coords(&self, k: usize) -> Option<&[[f64; 2]]> { + let count = self.parts.get(k)?.mesh.positions.len(); + let own = self.parts.get(k).map(|p| p.mesh.uvs.as_slice()); + self.texture(k).map(|(uv, _)| uv).into_iter().chain(own).find(|uv| uv.len() == count && count > 0) + } +} + +/// An error when a part's mesh cannot be written as it is: its lists do not match, or a +/// position, normal or texture coordinate is not a number +/// ([`vectorcraft_render::effects::Mesh::check`]). +fn check_parts(parts: &[SolidMesh]) -> Result<(), String> { + parts.iter().try_for_each(|p| p.mesh.check()) } /// A material: a color, with a picture that replaces its red, green and blue. @@ -230,7 +248,7 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) { } // OBJ's texture coordinates run up from the picture's bottom. for k in 0..parts.len() { - for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() { + for uv in scene.coords(k).unwrap_or_default() { let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1])); } } @@ -243,9 +261,9 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) { for (k, p) in parts.iter().enumerate() { let _ = writeln!(o, "g Solid_{}", k + 1); let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1); - let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some(); + let coords = scene.coords(k).is_some(); for t in &p.mesh.triangles { - if textured { + if coords { let [a, b, c] = t.map(|i| i as usize); let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base); let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c)); @@ -255,7 +273,7 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) { } } base += p.mesh.positions.len(); - uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len()); + uv_base += scene.coords(k).map_or(0, <[_]>::len); } let mut m = String::new(); for (k, mat) in materials.iter().enumerate() { @@ -313,7 +331,7 @@ fn gltf(stem: &str, scene: &Scene) -> String { "material": material.get(k).copied().unwrap_or(0), }); // glTF's texture coordinates run down from the picture's top, as the picture's own do. - if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) { + if let Some(uv) = scene.coords(k) { let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect(); let coords = view(&mut buffer, bytes, 34962); primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len()); @@ -415,7 +433,7 @@ fn usda(stem: &str, scene: &Scene) -> String { ); let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]); // USD's texture coordinates run up from the picture's bottom. - if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) { + if let Some(uv) = scene.coords(k) { let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect()); let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )"); } diff --git a/crates/engine/src/cmd/fileio/mesh3d/tests.rs b/crates/engine/src/cmd/fileio/mesh3d/tests.rs index 876140fce7..f87625d9fe 100644 --- a/crates/engine/src/cmd/fileio/mesh3d/tests.rs +++ b/crates/engine/src/cmd/fileio/mesh3d/tests.rs @@ -1,12 +1,18 @@ use serde_json::Value; -use vectorcraft_render::effects::{Mesh, SolidMesh}; +use vectorcraft_render::effects::{Mesh, MeshPart, SolidMesh}; use super::*; /// A 10 × 10 square facing the viewer: two triangles, each with corners of its own. fn square(color: [f32; 4]) -> SolidMesh { let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]]; - let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] }; + let mesh = Mesh { + positions: vec![a, b, c, a, c, d], + normals: vec![[0.0, 0.0, 1.0]; 6], + uvs: vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]], + triangles: vec![[0, 1, 2], [3, 4, 5]], + parts: vec![MeshPart::Front; 2], + }; SolidMesh::plain(mesh, color) } @@ -31,8 +37,9 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() { assert!(obj.starts_with("mtllib Box.mtl\no Box\n")); assert_eq!(obj.lines().filter(|l| l.starts_with("v ")).count(), 18); assert_eq!(obj.lines().filter(|l| l.starts_with("vn ")).count(), 18); + assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).count(), 18); // The third solid's last triangle uses corners 13 to 18; red solids share Material_1. - assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 16//16 17//17 18//18")); + assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 16/16/16 17/17/17 18/18/18")); assert_eq!(obj.lines().filter(|l| l.starts_with("usemtl ")).collect::>(), ["usemtl Material_1", "usemtl Material_2", "usemtl Material_1"]); let mtl = text(&files, "Box.mtl"); assert_eq!(mtl.matches("newmtl").count(), 2); @@ -64,8 +71,12 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() { assert_eq!(g["materials"][1]["alphaMode"], "BLEND"); assert!(g["materials"][0].get("alphaMode").is_none()); assert_eq!(g["materials"][0]["doubleSided"], true); - // Without graphics there are no textures. - assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none()); + // Without graphics there are no textures, but every corner has its mesh's texture coordinates. + assert!(g.get("images").is_none() && g.get("textures").is_none()); + for p in prims { + let uv = &g["accessors"][p["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize]; + assert_eq!((uv["type"].as_str(), uv["count"].as_u64()), (Some("VEC2"), Some(6))); + } } #[test] @@ -82,7 +93,28 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() { // sRGB 0.5 is about 0.214 linear. assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}"); assert_eq!(u.matches('{').count(), u.matches('}').count()); - assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture")); + // Each mesh carries its own texture coordinates, up from the bottom, with no picture to show. + assert_eq!(u.matches("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]").count(), 2, "{u}"); + assert!(!u.contains("UsdUVTexture")); +} + +#[test] +fn a_mesh_whose_lists_do_not_match_or_hold_no_number_is_refused() { + let good = square(RED); + let mut nan = square(RED); + nan.mesh.uvs[2] = [f64::NAN, 0.0]; + let mut infinite = square(RED); + infinite.mesh.normals[0] = [f64::INFINITY, 0.0, 0.0]; + let mut short = square(RED); + short.mesh.uvs.pop(); + let mut unnamed = square(RED); + unnamed.mesh.parts.pop(); + for bad in [nan, infinite, short, unnamed] { + for format in FORMATS_3D { + assert!(plain_files("Box", format, &[good.clone(), bad.clone()]).is_err(), "{format} {bad:?}"); + } + } + assert!(plain_files("Box", "obj", &[good]).is_ok()); } #[test] @@ -141,7 +173,10 @@ fn prim_names_are_usd_identifiers() { fn textured(png: &[u8]) -> (Vec, Vec>) { let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]; let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv }; - (vec![square(RED), square(BLUE)], vec![None, Some(texture)]) + // The picture's coordinates replace the mesh's own. + let mut blue = square(BLUE); + blue.mesh.uvs = vec![[0.25, 0.25]; 6]; + (vec![square(RED), blue], vec![None, Some(texture)]) } #[test] @@ -154,16 +189,18 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() { assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]); assert_eq!(files[2].1, png); let obj = text(&files, "My_Box.obj"); - assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]); - assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12")); - assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates"); + // The plain part's own coordinates come first, then the textured part's picture's. + let square_vt = ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]; + assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::>(), [square_vt, square_vt].concat()); + assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/10/10 11/11/11 12/12/12")); + assert!(obj.contains("f 1/1/1 2/2/2 3/3/3"), "the plain part keeps its mesh's texture coordinates"); let mtl = text(&files, "My_Box.mtl"); assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}"); assert_eq!(mtl.matches("map_Kd").count(), 1); // glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI. let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap(); let prims = g["meshes"][0]["primitives"].as_array().unwrap(); - assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none()); + assert!(prims[0]["attributes"].get("TEXCOORD_0").is_some(), "the plain part keeps its mesh's texture coordinates"); let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize]; assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126))); let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize]; @@ -182,8 +219,7 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() { let files = mesh_files("Box", "usda", &parts, &pictures).unwrap(); assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box.usda", "Box-texture-1.png"]); let u = text(&files, "Box.usda"); - assert_eq!(u.matches("primvars:st").count(), 1); - assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}"); + assert_eq!(u.matches("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]").count(), 2, "{u}"); assert!(u.contains("color3f inputs:diffuseColor.connect = "), "{u}"); assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\"")); assert!(u.contains("float2 inputs:st.connect = ")); diff --git a/crates/engine/src/tests/assets_3d.rs b/crates/engine/src/tests/assets_3d.rs index 1a647fb798..05141e2cb9 100644 --- a/crates/engine/src/tests/assets_3d.rs +++ b/crates/engine/src/tests/assets_3d.rs @@ -301,8 +301,9 @@ fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() { assert!(is_red(pixel(back, at(20.0), 64)) && is_blue(pixel(back, 64, 64)), "{:?}", pixel(back, 64, 64)); // The USDA's front cap shows the front picture through st, up from the picture's bottom. let usda = String::from_utf8(out[0].1.clone()).unwrap(); - assert_eq!(usda.matches("primvars:st").count(), 2); + assert_eq!(usda.matches("UsdUVTexture").count(), 2); assert_eq!(usda.matches("def Mesh").count(), 3, "the walls, the front cap and the back cap"); + assert_eq!(usda.matches("texCoord2f[] primvars:st").count(), 3, "every mesh carries texture coordinates"); // glTF holds both pictures, and a cap's coordinates stay inside its picture. let (mut s, _) = mapped("gltf"); let out = files(&run(&mut s, "assets.export3D", json!({}))); @@ -354,7 +355,7 @@ fn export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format() { let middle = (150.0 * scale) as u32; assert!(is_red(pixel(picture, 256, middle)) && is_blue(pixel(picture, 10, 10)), "{:?}", pixel(picture, 256, middle)); let usda = String::from_utf8(out[0].1.clone()).unwrap(); - assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (1, 1), "the side is the only face"); + assert_eq!((usda.matches("def Mesh").count(), usda.matches("UsdUVTexture").count()), (1, 1), "the side is the only face"); // Moved 50 pt around the axis, the graphic moves as far across the picture. let (mut s, _) = revolved("usda", json!({}), 50.0); let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 512}))); @@ -381,7 +382,8 @@ fn a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side() { let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), ["Ball.usda", "Ball-texture-1.png"]); let usda = String::from_utf8(out[0].1.clone()).unwrap(); - assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (2, 1), "the cut sides and the side"); + assert_eq!((usda.matches("def Mesh").count(), usda.matches("UsdUVTexture").count()), (2, 1), "the cut sides and the side"); + assert_eq!(usda.matches("texCoord2f[] primvars:st").count(), 2, "the plain cut sides keep their own texture coordinates"); let d = &s.doc().unwrap().doc; let id = d.asset(asset).unwrap().nodes[0].0; // Without its graphics the surface is one plain mesh, as before. @@ -476,7 +478,11 @@ fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes() let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box.obj", "Box.mtl"]); let obj = String::from_utf8(out[0].1.clone()).unwrap(); - assert!(!obj.contains("vt ") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1); + assert!(!out[1].1.windows(6).any(|w| w == b"map_Kd") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1); + // The plain mesh still carries a texture coordinate, 0 to 1, for every corner. + let count = |p: &str| obj.lines().filter(|l| l.starts_with(p)).count(); + assert!(count("vt ") > 0 && count("vt ") == count("v ")); + assert!(obj.lines().filter_map(|l| l.strip_prefix("vt ")).flat_map(|l| l.split(' ')).all(|v| (0.0..=1.0).contains(&v.parse::().unwrap()))); } #[test] diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 56a49aadf7..891ff4fcbc 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -23,7 +23,9 @@ mod lights; pub use lights::{Light, Lights, MAX_LIGHTS}; mod caps; mod mesh; -pub use mesh::{Mesh, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh, revolve_mesh_surface}; +pub use mesh::{ + Mesh, MeshPart, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh, revolve_mesh_surface, +}; mod shadow; pub use shadow::{ MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, SolidFaces, TOO_COMPLEX_SHADOW, extrude_shadowed, inflate_shadowed, @@ -1071,9 +1073,21 @@ fn keep_profile( turn: f64, caps: &[usize], surface: Option>, - mut keep: impl FnMut(Vec, V3, Option<[Point; 4]>) -> Result<(), String>, + mut keep: impl FnMut(Vec, V3, Option<[Point; 4]>, MeshPart, solid::Attrs) -> Result<(), String>, ) -> Result<(), String> { let (o, steps) = (at.o, at.steps); + // For the mesh's texture, the side runs around the sweep (0 to 1 from its start) and along the + // profile (0 to 1 from its first point); each end cap spans its disk. + let mut profile = Vec::with_capacity(s.points.len()); + let mut length = 0.0; + for (k, p) in s.points.iter().enumerate() { + if let Some(q) = k.checked_sub(1).and_then(|k| s.points.get(k)) { + length += q.distance(*p); + } + profile.push(length); + } + let along = |k: usize| if length > 1e-12 { (profile.get(k).copied().unwrap_or(0.0) / length).clamp(0.0, 1.0) } else { 0.5 }; + let around = |j: usize| j as f64 / steps.max(1) as f64; for (i, (pair, hole)) in s.points.windows(2).zip(&s.holes).enumerate() { let [a, b] = pair else { continue }; let turn = if *hole { -turn } else { turn }; @@ -1088,7 +1102,9 @@ fn keep_profile( let (sin, cos) = (at.sweep * (j as f64 + 0.5) / steps as f64).sin_cos(); // The corners on the side surface, as the drawn faces place them. let uv = surface.map(|(along, angle)| surface_corners(*a, *b, at.axis, along.get(i).copied().unwrap_or_default(), angle(j))); - keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)), uv)?; + let (u0, u1, w0, w1) = (around(j), around(j + 1), along(i), along(i + 1)); + let texture = solid::Attrs::Corners(vec![vec![([u0, w0], None), ([u0, w1], None), ([u1, w1], None), ([u1, w0], None)]]); + keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)), uv, MeshPart::Side, texture)?; } } for &index in caps { @@ -1099,7 +1115,14 @@ fn keep_profile( } else { cap.insert(0, o.rotate(V3(0.0, end.y - at.center_y, 0.0))); } - keep(cap, o.rotate(V3(0.0, outward, 0.0)), None)?; + let r = (end.x - at.axis).abs(); + let plane = solid::PlaneUv { + origin: o.rotate(V3(0.0, end.y - at.center_y, 0.0)), + x: o.rotate(V3(1.0, 0.0, 0.0)), + y: o.rotate(V3(0.0, 0.0, 1.0)), + area: Rect::new(-r, -r, r, r), + }; + keep(cap, o.rotate(V3(0.0, outward, 0.0)), None, MeshPart::Cap, solid::Attrs::Planar(plane))?; } Ok(()) } @@ -1324,8 +1347,8 @@ impl CutRegions { let (draw, mesh, lost) = kept; let result = match mesh.as_deref_mut() { Some(m) => cut_loops(&self.kept, rule, axis).and_then(|loops| { - keep_cuts(at, &loops, |contours, normal| { - m.push((contours, normal)); + keep_cuts(at, &loops, |contours, normal, attrs| { + m.push(solid::Face3 { contours, normal, part: MeshPart::Cut, attrs }); if m.len() > face_limit { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) } }) }), @@ -1343,14 +1366,19 @@ impl CutRegions { /// Keep for a mesh the two cut sides of a partial sweep: the loops `loops` of their regions /// ([`cut_loops`]) turned to each side. Outlines run one way round and holes the other, so the mesh -/// leaves the holes open. `keep` keeps one face with its outward normal. -fn keep_cuts(at: &Sweeping, loops: &[Vec], mut keep: impl FnMut(Vec>, V3) -> Result<(), String>) -> Result<(), String> { +/// leaves the holes open. `keep` keeps one face with its outward normal and where its corners lie +/// on its texture: each corner's profile point in the bounds of the loops. +fn keep_cuts(at: &Sweeping, loops: &[Vec], mut keep: impl FnMut(Vec>, V3, solid::Attrs) -> Result<(), String>) -> Result<(), String> { if loops.is_empty() { return Ok(()); } + let area = solid::rings_bounds(loops.iter().map(Vec::as_slice)); for (step, normal) in cut_sides(at) { let contours = loops.iter().map(|r| r.iter().map(|p| at.vertex(*p, step)).collect()).collect(); - keep(contours, at.o.rotate(normal))?; + // A profile point goes to view space by one affine map at each step. + let origin = at.vertex(Point::ZERO, step); + let (x, y) = (at.vertex(Point::new(1.0, 0.0), step).sub(origin), at.vertex(Point::new(0.0, 1.0), step).sub(origin)); + keep(contours, at.o.rotate(normal), solid::Attrs::Planar(solid::PlaneUv { origin, x, y, area }))?; } Ok(()) } @@ -1399,8 +1427,8 @@ fn revolve_sweep( } let face_limit = revolve_face_limit(o); // A face kept for a mesh: its normal follows from its corners. - let keep = |mesh: &mut Vec, face: Vec, normal: V3| { - mesh.push((vec![face], normal)); + let keep = |mesh: &mut Vec, face: Vec, normal: V3, part: MeshPart, attrs: solid::Attrs| { + mesh.push(solid::Face3 { contours: vec![face], normal, part, attrs }); if mesh.len() > face_limit { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) } }; if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { @@ -1584,8 +1612,8 @@ fn revolve_sweep( let caps: Vec = rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|_| i)).collect(); let along = (surface.is_some() && surface_contour == Some(contour)).then(|| along_profile(&kept.points, axis, sp.closed)); let layout = along.as_deref().map(|along| (along, &surface_angle as &dyn Fn(usize) -> [f64; 2])); - let kept = keep_profile(&at, &kept, turn, &caps, layout, |face, normal, uv| { - keep(m, face, normal)?; + let kept = keep_profile(&at, &kept, turn, &caps, layout, |face, normal, uv, part, attrs| { + keep(m, face, normal, part, attrs)?; if let (Some(uv), Some(s)) = (uv, surface.as_deref_mut()) { s.push((m.len() - 1, uv)); } diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index a5cf621d9c..53e1cb5786 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -4,28 +4,71 @@ //! //! Coordinates are points with y up and z toward the viewer, about the point the solid turns about //! (the centre of the art's bounds; for Revolve, the axis at the profile's middle). Each face keeps -//! its own corners and normal, so the mesh is shaded flat. Planar faces with holes (caps and the -//! turned plane) are cut into triangles: each hole is joined to its outline by a bridge, then the -//! outline is cut by ear clipping. +//! its own corners. A corner takes its face's normal, with two exceptions. On a bevel, the corners +//! two bands of one bevel share take the mean of the bands' normals, unless the bevel turns there +//! by 60° or more or one of the bands lies flat toward the front or back. On Inflate's puffed +//! front and back, each corner takes the surface's own normal. Planar faces with holes (caps and +//! the turned plane) are cut into triangles: each hole is joined to its outline by a bridge, then +//! the outline is cut by ear clipping. +//! +//! Every corner has texture coordinates from 0 to 1 each way, u to the right and v down, and every +//! triangle names the part of the solid it belongs to ([`MeshPart`]): +//! +//! - Caps, Rotate's plane and Inflate's front and back take each corner's point in the art, before +//! any twist or taper, within the art's bounds. The back is not mirrored. +//! - Extrude & Bevel's bevels and walls, and Inflate's walls, take u along each contour of the +//! outline from its first point (its distance over the contour's length, so its first point is +//! at both 0 and 1) and v across the side from the front cap's edge to the back cap's. +//! - Revolve's side takes u around the sweep from its start and v along each contour of the +//! profile from its first point. Its end caps span the disk they close, and its cut sides take +//! each corner's profile point within the bounds of the profile. +//! +//! An axis with no extent (a contour of no length, art of no width) takes 0.5. + +use std::collections::HashMap; use vectorcraft_geom::{FillRule, PathData, Point, Rect}; -use crate::solid::{Face3, Keep, extrude_faces, inflate_faces, plane_faces}; +use crate::solid::{Attrs, Face3, Keep, extrude_faces, inflate_faces, plane_faces}; use crate::{Extrude, Facet, Inflate, Revolve, V3, View}; /// Most steps the triangulation of one solid may take: a face's ears and bridges each test the /// face's other corners. const MAX_WORK: usize = 400_000_000; +/// The part of a solid a triangle of its mesh belongs to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MeshPart { + /// Extrude & Bevel's front cap, Rotate's plane, and Inflate's front. + Front, + /// Extrude & Bevel's back cap, and Inflate's back, puffed or flat. + Back, + /// The walls of Extrude & Bevel and Inflate, and the side Revolve sweeps. + Side, + /// Extrude & Bevel's bevel between the front cap and the walls. + FrontBevel, + /// Extrude & Bevel's bevel between the walls and the back cap, with the bevel on both sides. + BackBevel, + /// A disk or sector closing an end of Revolve's profile. + Cap, + /// A flat side closing a Revolve sweep of less than 360°. + Cut, +} + /// A triangle mesh. #[derive(Clone, Debug, Default, PartialEq)] pub struct Mesh { /// Corner positions in points: x right, y up, z toward the viewer. pub positions: Vec<[f64; 3]>, - /// One unit normal for each position: the normal of the face the corner belongs to. + /// One unit normal for each position: the normal of the face the corner belongs to, or a + /// smoothed one (see the module's description). pub normals: Vec<[f64; 3]>, + /// Texture coordinates for each position, each from 0 to 1: u to the right, v down. + pub uvs: Vec<[f64; 2]>, /// Corner indices, counterclockwise seen from the side the normals point to. pub triangles: Vec<[u32; 3]>, + /// The part of the solid each triangle belongs to. + pub parts: Vec, } impl Mesh { @@ -33,6 +76,24 @@ impl Mesh { self.triangles.is_empty() } + /// Whether the lists match and hold numbers: a normal and texture coordinates for each + /// position, a part for each triangle, every corner index naming a position, and every + /// position, normal and texture coordinate finite. + pub fn is_consistent(&self) -> bool { + let n = self.positions.len(); + let finite = self.positions.iter().chain(&self.normals).flatten().chain(self.uvs.iter().flatten()).all(|v| v.is_finite()); + self.normals.len() == n + && self.uvs.len() == n + && self.parts.len() == self.triangles.len() + && self.triangles.iter().flatten().all(|&i| usize::try_from(i).is_ok_and(|i| i < n)) + && finite + } + + /// An error when the mesh cannot be written as it is ([`Mesh::is_consistent`]). + pub fn check(&self) -> Result<(), String> { + if self.is_consistent() { Ok(()) } else { Err("The 3D object's mesh is incomplete or holds a value that is not a number".into()) } + } + /// The smallest and largest coordinate on each axis; `None` for an empty mesh. pub fn bounds(&self) -> Option<([f64; 3], [f64; 3])> { let first = *self.positions.first()?; @@ -41,16 +102,22 @@ impl Mesh { })) } - /// The meshes of `parts` as one, in order. - pub fn join(parts: impl IntoIterator) -> Mesh { + /// The meshes of `parts` as one, in order. An error when a mesh cannot be written as it is + /// ([`Mesh::check`]) or the corners would pass what a `u32` index can name. + pub fn join(parts: impl IntoIterator) -> Result { let mut out = Mesh::default(); for m in parts { - let base = out.positions.len() as u32; + m.check()?; + let base = u32::try_from(out.positions.len()).map_err(|_| too_complex())?; + // Every index of `m` is below its count of positions, so the shifted indices fit too. + base.checked_add(u32::try_from(m.positions.len()).map_err(|_| too_complex())?).ok_or_else(too_complex)?; out.positions.extend(m.positions); out.normals.extend(m.normals); + out.uvs.extend(m.uvs); out.triangles.extend(m.triangles.into_iter().map(|t| t.map(|i| i + base))); + out.parts.extend(m.parts); } - out + Ok(out) } } @@ -154,6 +221,11 @@ pub(crate) fn newell(contours: &[Vec]) -> V3 { n } +/// The exact position of `v`, as a key ([`Face3::corner`] matches corners exactly). +fn key(v: V3) -> [u64; 3] { + [v.0.to_bits(), v.1.to_bits(), v.2.to_bits()] +} + /// From the effects' view space (y down) to the mesh's (y up). fn up(v: V3) -> [f64; 3] { [v.0, -v.1, v.2] @@ -176,7 +248,8 @@ fn mesh_on(faces: &[Face3], surface: Option<&[(usize, [Point; 4])]>) -> Result) -> Result vec![[v0, v1, v2], [v0, v2, v3]], None => triangulate(contours, geometric, &mut work)?, }; + // A face with many listed corners looks each one up by its position. + let listed = match &face.attrs { + Attrs::Corners(list) if list.iter().map(Vec::len).sum::() > 16 => { + let mut map = HashMap::new(); + for (c, l) in contours.iter().zip(list) { + for (v, data) in c.iter().zip(l) { + map.entry(key(*v)).or_insert(*data); + } + } + Some(map) + } + _ => None, + }; for [a, b, c] in triangles { let (pa, pb, pc) = (up(a), up(b), up(c)); let cross = V3(pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]).cross(V3(pc[0] - pa[0], pc[1] - pa[1], pc[2] - pa[2])); @@ -212,9 +298,20 @@ fn mesh_on(faces: &[Face3], surface: Option<&[(usize, [Point; 4])]>) -> Result map.get(&key(v)).copied().unwrap_or(([0.5, 0.5], None)), + None => face.corner(v), + }; + // A corner's own normal, when it has a usable one, else the face's. + let own = own.map(V3::unit).filter(|m| m.dot(*m) > 0.5 && [m.0, m.1, m.2].iter().all(|x| x.is_finite())); + out.normals.push(own.map_or([nx, ny, nz], up)); + out.uvs.push(uv); + } out.triangles.push([base, base + 1, base + 2]); + out.parts.push(face.part); if track { on.push(point(a).zip(point(b)).zip(point(c)).map(|((a, b), c)| [a, b, c])); } @@ -497,3 +594,5 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight #[cfg(test)] mod tests; +#[cfg(test)] +mod tests_attributes; diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 907c9f91b2..63a0a21dc2 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -543,10 +543,32 @@ fn join_numbers_each_parts_corners_after_the_last() { square(&mut b, 0.0, 0.0, 10.0, false); let (p, r) = shape(&b); let one = plane_mesh(&p, FillRule::NonZero, r, front()).unwrap(); - let both = Mesh::join([one.clone(), one.clone()]); + let both = Mesh::join([one.clone(), one.clone()]).unwrap(); assert_eq!(both.triangles.len(), 2 * one.triangles.len()); assert!(both.triangles.iter().all(|t| t.iter().all(|i| (*i as usize) < both.positions.len()))); assert_eq!(both.triangles[one.triangles.len()][0], one.triangles[0][0] + one.positions.len() as u32); + assert!(both.is_consistent()); + assert_eq!(both.uvs.len(), 2 * one.uvs.len()); + assert_eq!(both.parts.len(), 2 * one.parts.len()); +} + +#[test] +fn join_refuses_a_mesh_whose_lists_do_not_match() { + let mut b = BezPath::new(); + square(&mut b, 0.0, 0.0, 10.0, false); + let (p, r) = shape(&b); + let one = plane_mesh(&p, FillRule::NonZero, r, front()).unwrap(); + for broken in [ + Mesh { uvs: vec![], ..one.clone() }, + Mesh { parts: vec![], ..one.clone() }, + Mesh { normals: vec![], ..one.clone() }, + Mesh { uvs: vec![[f64::NAN, 0.0]; one.uvs.len()], ..one.clone() }, + Mesh { positions: vec![[f64::INFINITY, 0.0, 0.0]; one.positions.len()], ..one.clone() }, + Mesh { triangles: vec![[0, 1, u32::MAX]], parts: vec![MeshPart::Front], ..one.clone() }, + ] { + assert!(!broken.is_consistent()); + assert!(Mesh::join([one.clone(), broken]).is_err()); + } } /// A mesh's positions and normals as bits, and its triangles. diff --git a/crates/three-d/src/mesh/tests_attributes.rs b/crates/three-d/src/mesh/tests_attributes.rs new file mode 100644 index 0000000000..bbd766a9b9 --- /dev/null +++ b/crates/three-d/src/mesh/tests_attributes.rs @@ -0,0 +1,432 @@ +use std::collections::HashMap; + +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; + +use super::*; +use crate::{Bevel, BevelProfile, BevelShape, Edge}; + +fn rectangle(x: f64, y: f64, w: f64, h: f64) -> (PathData, Rect) { + let mut b = BezPath::new(); + b.move_to((x, y)); + b.line_to((x + w, y)); + b.line_to((x + w, y + h)); + b.line_to((x, y + h)); + b.close_path(); + let p = PathData::from_bezpath(&b); + let r = p.bounds().unwrap(); + (p, r) +} + +/// A rectangle with a square hole: the hole's wall is a contour of its own. +fn holed() -> (PathData, Rect) { + let mut b = BezPath::new(); + for (x, y, s, clockwise) in [(0.0, 0.0, 100.0, false), (40.0, 40.0, 20.0, true)] { + b.move_to((x, y)); + let corners = if clockwise { [(x, y + s), (x + s, y + s), (x + s, y)] } else { [(x + s, y), (x + s, y + s), (x, y + s)] }; + for c in corners { + b.line_to(c); + } + b.close_path(); + } + let p = PathData::from_bezpath(&b); + let r = p.bounds().unwrap(); + (p, r) +} + +/// A vertical line from y 0 to 100, 20 pt from the left edge of its bounds' axis. +fn line_profile() -> (PathData, Rect) { + let mut b = BezPath::new(); + b.move_to((20.0, 0.0)); + b.line_to((20.0, 100.0)); + let p = PathData::from_bezpath(&b); + let r = p.bounds().unwrap(); + (p, r) +} + +fn front() -> View { + View { rotation_x: 0.0, rotation_y: 0.0, rotation_z: 0.0, perspective: 0.0, ..View::default() } +} + +fn turned() -> View { + View { rotation_x: -25.0, rotation_y: 35.0, rotation_z: 10.0, perspective: 0.0, ..View::default() } +} + +fn bevel(shape: BevelShape) -> Bevel { + Bevel { shape, width: 6.0, height: 6.0, ..Bevel::default() } +} + +fn beveled(b: Bevel) -> Extrude { + Extrude { bevel: Some(b), ..Extrude::default() } +} + +fn custom() -> BevelShape { + BevelShape::Custom(BevelProfile::new(&[(0.0, 0.0), (0.5, 0.2), (0.8, 0.5), (1.0, 1.0)]).unwrap()) +} + +fn length(v: [f64; 3]) -> f64 { + v.iter().map(|x| x * x).sum::().sqrt() +} + +fn geometric(m: &Mesh, t: [u32; 3]) -> [f64; 3] { + let [a, b, c] = t.map(|i| m.positions[i as usize]); + let (u, v) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]); + let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + let l = length(n); + n.map(|x| x / l) +} + +/// Every list of `m` matches, every texture coordinate is a number from 0 to 1, and every normal +/// is a unit vector. +fn check(m: &Mesh, what: &str) { + assert!(m.is_consistent(), "{what}"); + assert!(m.uvs.iter().flatten().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{what}"); + assert!(m.normals.iter().all(|n| (length(*n) - 1.0).abs() < 1e-9), "{what}"); + assert!(m.positions.iter().flatten().all(|v| v.is_finite()), "{what}"); +} + +fn parts(m: &Mesh) -> Vec { + let mut out: Vec = vec![]; + for p in &m.parts { + if !out.contains(p) { + out.push(*p); + } + } + out +} + +/// The meshes of every effect and many options. +fn meshes() -> Vec<(String, Mesh)> { + let (square, r) = rectangle(0.0, 0.0, 100.0, 60.0); + let (hole, hr) = holed(); + let mut out = vec![]; + let shapes = [BevelShape::Classic, BevelShape::Rounded, BevelShape::Cove, BevelShape::Step, BevelShape::Ogee, custom()]; + for view in [front(), turned(), View { perspective: 60.0, ..turned() }] { + for shape in shapes { + for b in [ + bevel(shape), + Bevel { inside: true, ..bevel(shape) }, + Bevel { both_sides: true, ..bevel(shape) }, + Bevel { repeat: 3, space: 0.2, ..bevel(shape) }, + ] { + let o = Extrude { bevel: Some(b), ..Extrude::default() }; + out.push((format!("{shape:?} {b:?} {view:?}"), extrude_mesh(&square, FillRule::NonZero, r, o, view).unwrap())); + } + } + for o in [ + Extrude::default(), + Extrude { twist: 90.0, taper: 0.5, bevel: Some(bevel(BevelShape::Rounded)), ..Extrude::default() }, + Extrude { depth: 0.0, ..Extrude::default() }, + Extrude { cap: false, ..Extrude::default() }, + ] { + out.push((format!("{o:?} {view:?}"), extrude_mesh(&hole, FillRule::NonZero, hr, o, view).unwrap())); + } + out.push((format!("plane {view:?}"), plane_mesh(&hole, FillRule::NonZero, hr, view).unwrap())); + let deep = Inflate { depth: 10.0, ..Inflate::default() }; + for o in [Inflate::default(), Inflate { both_sides: true, twist: 30.0, ..deep }, Inflate { cap: false, ..deep }] { + for (k, m) in inflate_meshes(&[(&hole, FillRule::NonZero)], hr, o, view).enumerate() { + out.push((format!("inflate {k} {o:?} {view:?}"), m.unwrap())); + } + } + } + let (line, lr) = line_profile(); + for angle in [360.0, 90.0] { + let o = Revolve { angle, offset: 10.0, edge: Edge::Left, rotation_x: -20.0, rotation_y: 30.0, ..Revolve::default() }; + out.push((format!("revolve line {angle}"), revolve_mesh(&line, FillRule::NonZero, lr, o).unwrap())); + out.push((format!("revolve holed {angle}"), revolve_mesh(&hole, FillRule::NonZero, hr, o).unwrap())); + } + out +} + +#[test] +fn every_corner_has_texture_coordinates_and_every_triangle_a_part() { + for (what, m) in meshes() { + assert!(!m.is_empty(), "{what}"); + check(&m, &what); + assert_eq!(m.uvs.len(), m.positions.len(), "{what}"); + assert_eq!(m.parts.len(), m.triangles.len(), "{what}"); + } +} + +#[test] +fn each_triangle_names_the_part_of_the_solid_it_comes_from() { + let (p, r) = rectangle(0.0, 0.0, 100.0, 60.0); + let both = Extrude { bevel: Some(Bevel { both_sides: true, ..bevel(BevelShape::Rounded) }), ..Extrude::default() }; + let m = extrude_mesh(&p, FillRule::NonZero, r, both, front()).unwrap(); + let mut found = parts(&m); + found.sort_by_key(|p| *p as u8); + assert_eq!(found, [MeshPart::Front, MeshPart::Back, MeshPart::Side, MeshPart::FrontBevel, MeshPart::BackBevel]); + // Straight on, the front cap faces the viewer and the back cap away; the walls face sideways. + for (t, part) in m.triangles.iter().zip(&m.parts) { + let n = geometric(&m, *t); + match part { + MeshPart::Front => assert!(n[2] > 1.0 - 1e-9), + MeshPart::Back => assert!(n[2] < -1.0 + 1e-9), + MeshPart::Side => assert!(n[2].abs() < 1e-9), + MeshPart::FrontBevel => assert!(n[2] > 0.0), + MeshPart::BackBevel => assert!(n[2] < 0.0), + other => panic!("{other:?}"), + } + } + assert!(plane_mesh(&p, FillRule::NonZero, r, turned()).unwrap().parts.iter().all(|p| *p == MeshPart::Front)); + let flat = extrude_mesh(&p, FillRule::NonZero, r, Extrude { depth: 0.0, ..Extrude::default() }, front()).unwrap(); + assert!(flat.parts.iter().all(|p| *p == MeshPart::Front)); + let deep = Inflate { depth: 10.0, ..Inflate::default() }; + let puffed = inflate_meshes(&[(&p, FillRule::NonZero)], r, deep, front()).next().unwrap().unwrap(); + let mut found = parts(&puffed); + found.sort_by_key(|p| *p as u8); + assert_eq!(found, [MeshPart::Front, MeshPart::Back, MeshPart::Side]); + let (line, lr) = line_profile(); + let o = Revolve { angle: 90.0, offset: 10.0, ..Revolve::default() }; + let mut found = parts(&revolve_mesh(&line, FillRule::NonZero, lr, o).unwrap()); + found.sort_by_key(|p| *p as u8); + assert_eq!(found, [MeshPart::Side, MeshPart::Cap, MeshPart::Cut]); +} + +#[test] +fn caps_take_their_art_points_and_the_side_runs_around_the_outline_and_front_to_back() { + let (p, r) = rectangle(0.0, 0.0, 100.0, 60.0); + let m = extrude_mesh(&p, FillRule::NonZero, r, Extrude::default(), front()).unwrap(); + let depth = Extrude::default().depth; + let (mut seams, mut ends) = (HashMap::<[u64; 3], Vec>::new(), [false; 2]); + for (t, part) in m.triangles.iter().zip(&m.parts) { + for &i in t { + let (q, uv) = (m.positions[i as usize], m.uvs[i as usize]); + match part { + // The art at (x, y) lies at (x - 50, 30 - y) in the mesh: the back is not mirrored. + MeshPart::Front | MeshPart::Back => { + assert!((uv[0] - (q[0] + 50.0) / 100.0).abs() < 1e-9 && (uv[1] - (30.0 - q[1]) / 60.0).abs() < 1e-9, "{q:?} {uv:?}"); + } + MeshPart::Side => { + seams.entry(q.map(f64::to_bits)).or_default().push(uv[0]); + // v runs from the front cap's edge to the back cap's. + let v = if q[2] > 0.0 { 0.0 } else { 1.0 }; + assert!((q[2].abs() - depth / 2.0).abs() < 1e-9 && (uv[1] - v).abs() < 1e-9, "{q:?} {uv:?}"); + ends[usize::from(q[2] < 0.0)] = true; + } + other => panic!("{other:?}"), + } + } + } + assert_eq!(ends, [true, true]); + // The outline's first point carries both ends of the side's u: the seam's corners are kept apart. + assert!(seams.values().any(|u| u.contains(&0.0) && u.contains(&1.0))); + // Along the 320 pt outline each corner of the rectangle lies 100, 160 and 260 pt from the first. + let mut along: Vec = seams.values().flatten().copied().collect(); + along.sort_by(f64::total_cmp); + along.dedup_by(|a, b| (*a - *b).abs() < 1e-9); + assert_eq!(along.len(), 5, "{along:?}"); + for (u, expected) in along.iter().zip([0.0, 100.0, 160.0, 260.0, 320.0]) { + assert!((u - expected / 320.0).abs() < 1e-9, "{along:?}"); + } +} + +#[test] +fn revolves_side_runs_around_the_sweep_and_along_the_profile() { + let (line, lr) = line_profile(); + let o = Revolve { offset: 10.0, segments: 16, ..Revolve::default() }; + let m = revolve_mesh(&line, FillRule::NonZero, lr, o).unwrap(); + let mut around = HashMap::<[i64; 3], Vec>::new(); + for (t, part) in m.triangles.iter().zip(&m.parts) { + for &i in t { + let (q, uv) = (m.positions[i as usize], m.uvs[i as usize]); + if *part == MeshPart::Side { + // The sweep's end lands on its start within rounding. + around.entry(q.map(|v| (v * 1e6).round() as i64)).or_default().push(uv[0]); + // The profile runs from y 0 (the mesh's top, at 50) to y 100 (at -50). + assert!((uv[1] - (50.0 - q[1]) / 100.0).abs() < 1e-9, "{q:?} {uv:?}"); + } else { + assert_eq!(*part, MeshPart::Cap); + } + } + } + assert!(around.values().any(|u| u.contains(&0.0) && u.contains(&1.0)), "the sweep's seam is kept apart"); +} + +/// The corners of the bottom edge's front bevel of `m` (an extruded rectangle seen straight on), +/// by position, with their normals. +fn bottom_bevel(m: &Mesh) -> HashMap<[u64; 3], Vec<[f64; 3]>> { + let mut out = HashMap::<[u64; 3], Vec<[f64; 3]>>::new(); + for (t, part) in m.triangles.iter().zip(&m.parts) { + let n = geometric(m, *t); + if *part != MeshPart::FrontBevel || n[0].abs() > 1e-9 || n[1] >= 0.0 { + continue; + } + for &i in t { + out.entry(m.positions[i as usize].map(f64::to_bits)).or_default().push(m.normals[i as usize]); + } + } + out +} + +/// The angle between `a` and `b` in degrees, from their cross and dot products, so that two equal +/// vectors give 0 exactly. +fn angle(a: [f64; 3], b: [f64; 3]) -> f64 { + let cross = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + length(cross).atan2(a[0] * b[0] + a[1] * b[1] + a[2] * b[2]).to_degrees() +} + +#[test] +fn a_rounded_or_custom_bevels_normals_turn_smoothly_across_its_bands() { + let (p, r) = rectangle(0.0, 0.0, 200.0, 100.0); + for shape in [BevelShape::Rounded, custom(), BevelShape::Ogee] { + let o = Extrude { bevel: Some(bevel(shape)), ..Extrude::default() }; + let m = extrude_mesh(&p, FillRule::NonZero, r, o, front()).unwrap(); + let corners = bottom_bevel(&m); + let mut normals: Vec<[f64; 3]> = vec![]; + for (at, list) in &corners { + // Every band that meets at a corner gives it the same normal. + assert!(list.iter().all(|n| angle(*n, list[0]) < 1e-9), "{shape:?} {at:?} {list:?}"); + assert!(list.iter().all(|n| (length(*n) - 1.0).abs() < 1e-12)); + if !normals.iter().any(|n| angle(*n, list[0]) < 1e-9) { + normals.push(list[0]); + } + } + // The normals turn from the front toward the bottom in steps smaller than the profile's. + normals.sort_by(|a, b| b[2].total_cmp(&a[2])); + assert!(normals.len() >= 3, "{shape:?} {normals:?}"); + assert!(normals.windows(2).all(|w| angle(w[0], w[1]) < 45.0), "{shape:?} {normals:?}"); + // The vector facets keep their flat shading. + let facets = crate::extrude(&p, FillRule::NonZero, r, o, front()).unwrap(); + let built = crate::extrude_meshed(&p, FillRule::NonZero, r, o, front()).unwrap(); + assert_eq!(facets, built.facets); + } +} + +#[test] +fn a_steps_sharp_turns_and_a_classic_bevel_stay_hard_edges() { + let (p, r) = rectangle(0.0, 0.0, 200.0, 100.0); + let step = extrude_mesh(&p, FillRule::NonZero, r, Extrude { bevel: Some(bevel(BevelShape::Step)), ..Extrude::default() }, front()).unwrap(); + for (t, part) in step.triangles.iter().zip(&step.parts) { + if *part == MeshPart::FrontBevel { + let n = geometric(&step, *t); + for &i in t { + assert!(angle(step.normals[i as usize], n) < 1e-6, "a Step's flat bands keep their own normals"); + } + } + } + let classic = extrude_mesh(&p, FillRule::NonZero, r, Extrude { bevel: Some(bevel(BevelShape::Classic)), ..Extrude::default() }, front()).unwrap(); + for t in &classic.triangles { + let n = geometric(&classic, *t); + for &i in t { + assert!(angle(classic.normals[i as usize], n) < 1e-6); + } + } +} + +#[test] +fn inflates_puffed_front_takes_the_surfaces_own_normals() { + let (p, r) = rectangle(0.0, 0.0, 100.0, 60.0); + let m = inflate_meshes(&[(&p, FillRule::NonZero)], r, Inflate::default(), front()).next().unwrap().unwrap(); + check(&m, "inflate"); + // Each point of the front has one normal, whichever pieces meet there. + let mut at = HashMap::<[u64; 3], Vec<[f64; 3]>>::new(); + for (t, part) in m.triangles.iter().zip(&m.parts) { + if *part == MeshPart::Front { + for &i in t { + at.entry(m.positions[i as usize].map(f64::to_bits)).or_default().push(m.normals[i as usize]); + } + } + } + assert!(at.values().filter(|list| list.len() > 1).count() > 10); + for list in at.values() { + assert!(list.iter().all(|n| angle(*n, list[0]) < 1e-9), "{list:?}"); + } +} + +/// Whether `p` lies inside the polygon `ring` (even-odd), or within `d` of one of its edges. +fn inside_or_near(rings: &[Vec], p: Point, d: f64) -> bool { + let mut odd = false; + for ring in rings { + for (a, b) in ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()) { + let (dx, dy) = (b.x - a.x, b.y - a.y); + let l2 = dx * dx + dy * dy; + let t = if l2 < 1e-18 { 0.0 } else { (((p.x - a.x) * dx + (p.y - a.y) * dy) / l2).clamp(0.0, 1.0) }; + if p.distance(Point::new(a.x + dx * t, a.y + dy * t)) <= d { + return true; + } + if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) { + odd = !odd; + } + } + } + odd +} + +/// Every corner of `m` seen from `origin` without perspective lies within `d` of some polygon of +/// `drawn`, and every corner of `drawn` within `d` of some triangle of `m`: the mesh's outline +/// and the vector facets' differ by no more than `d`. +fn outlines_match(m: &Mesh, drawn: &[Vec>], origin: Point, d: f64, what: &str) { + let page = |q: [f64; 3]| Point::new(origin.x + q[0], origin.y - q[1]); + let triangles: Vec> = m.triangles.iter().map(|t| t.iter().map(|&i| page(m.positions[i as usize])).collect()).collect(); + for q in &m.positions { + let p = page(*q); + assert!(drawn.iter().any(|f| inside_or_near(f, p, d)), "{what}: mesh corner {p:?}"); + } + for p in drawn.iter().flatten().flatten() { + assert!(triangles.iter().any(|t| inside_or_near(std::slice::from_ref(t), *p, d)), "{what}: facet corner {p:?}"); + } +} + +/// The largest distance between the outline of a mesh and that of the vector facets of the same +/// solid, in points. +const OUTLINE_TOLERANCE: f64 = 0.05; + +#[test] +fn the_meshs_outline_stays_within_a_twentieth_of_a_point_of_the_vector_facets() { + let (p, r) = rectangle(0.0, 0.0, 100.0, 60.0); + let (hole, hr) = holed(); + for shape in [BevelShape::Classic, BevelShape::Rounded, BevelShape::Step, custom()] { + for o in [ + Extrude { bevel: Some(bevel(shape)), ..Extrude::default() }, + Extrude { bevel: Some(Bevel { inside: true, both_sides: true, ..bevel(shape) }), ..Extrude::default() }, + ] { + for (path, bounds) in [(&p, r), (&hole, hr)] { + let m = extrude_mesh(path, FillRule::NonZero, bounds, o, turned()).unwrap(); + let facets = crate::extrude(path, FillRule::NonZero, bounds, o, turned()).unwrap(); + let drawn: Vec>> = facets.into_iter().map(|f| f.contours).collect(); + outlines_match(&m, &drawn, bounds.center(), OUTLINE_TOLERANCE, &format!("{shape:?} {o:?}")); + } + } + } + let (line, lr) = line_profile(); + for angle in [360.0, 120.0] { + let o = Revolve { angle, offset: 10.0, rotation_x: -20.0, rotation_y: 30.0, ..Revolve::default() }; + let m = revolve_mesh(&line, FillRule::NonZero, lr, o).unwrap(); + let drawn: Vec>> = crate::revolve(&line, lr, o).unwrap().into_iter().map(|f| vec![f.points]).collect(); + let origin = crate::revolve_projection(lr, o.sanitized()).origin; + outlines_match(&m, &drawn, origin, OUTLINE_TOLERANCE, &format!("revolve {angle}")); + } +} + +#[test] +fn hostile_input_gives_an_error_or_a_consistent_mesh() { + let (p, r) = rectangle(0.0, 0.0, 100.0, 60.0); + // A closed outline with no area. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((50.0, 0.0)); + b.line_to((100.0, 0.0)); + b.close_path(); + let flat = PathData::from_bezpath(&b); + let fr = Rect::new(0.0, 0.0, 100.0, 0.0); + for m in [ + extrude_mesh(&flat, FillRule::NonZero, fr, Extrude::default(), turned()), + extrude_mesh(&flat, FillRule::NonZero, fr, Extrude { bevel: Some(bevel(BevelShape::Rounded)), ..Extrude::default() }, turned()), + plane_mesh(&flat, FillRule::NonZero, fr, turned()), + extrude_mesh(&p, FillRule::NonZero, r, Extrude { depth: 0.0, ..Extrude::default() }, turned()), + extrude_mesh(&p, FillRule::NonZero, r, Extrude { depth: f64::NAN, twist: f64::NAN, ..Extrude::default() }, turned()), + extrude_mesh(&p, FillRule::NonZero, r, beveled(Bevel { width: f64::NAN, height: f64::INFINITY, ..bevel(custom()) }), turned()), + extrude_mesh(&p, FillRule::NonZero, r, beveled(Bevel { repeat: usize::MAX, ..bevel(BevelShape::Rounded) }), turned()), + revolve_mesh(&p, FillRule::NonZero, r, Revolve { segments: usize::MAX, ..Revolve::default() }), + revolve_mesh(&flat, FillRule::NonZero, fr, Revolve::default()), + ] + .into_iter() + .flatten() + { + check(&m, "hostile"); + } + let nan = Rect::new(f64::NAN, 0.0, 100.0, 60.0); + assert!(extrude_mesh(&p, FillRule::NonZero, nan, Extrude::default(), turned()).is_err()); + assert!(plane_mesh(&p, FillRule::NonZero, nan, turned()).is_err()); + assert!(revolve_mesh(&p, FillRule::NonZero, nan, Revolve::default()).is_err()); +} diff --git a/crates/three-d/src/shadow.rs b/crates/three-d/src/shadow.rs index 38d2be50c7..8a89f5e3cc 100644 --- a/crates/three-d/src/shadow.rs +++ b/crates/three-d/src/shadow.rs @@ -261,7 +261,7 @@ impl ShadowCaster { let p = self.projection?; let light = p.light()?; let s = shadow.sanitized(); - let corners = || self.within(faces).flat_map(|(contours, _)| contours.iter().flatten()); + let corners = || self.within(faces).flat_map(|face| face.contours.iter().flatten()); let first = *corners().next()?; let (lo, hi) = corners() .fold((first, first), |(lo, hi), v| (V3(lo.0.min(v.0), lo.1.min(v.1), lo.2.min(v.2)), V3(hi.0.max(v.0), hi.1.max(v.1), hi.2.max(v.2)))); @@ -299,8 +299,8 @@ impl ShadowCaster { }; let to_page = |q: Point| p.project(add(foot, add(scale(u, q.x), scale(w, q.y)))); let mut bp = BezPath::new(); - for (contours, _) in self.within(faces) { - let flat: Vec> = contours.iter().map(|c| c.iter().map(|v| cast(*v)).collect()).collect(); + for face in self.within(faces) { + let flat: Vec> = face.contours.iter().map(|c| c.iter().map(|v| cast(*v)).collect()).collect(); let turn: f64 = flat.iter().map(|c| signed_area(c)).sum(); // A face edge-on to the light casts nothing. if flat_area(turn, flat.iter().flatten()) { diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 71f039724f..ca3a272dd0 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -25,9 +25,9 @@ mod side; pub(crate) use build::EXTRUDED; #[cfg(test)] pub(crate) use build::PLANES; +pub(crate) use build::{Attrs, Face3, Keep, PlaneUv, extrude_faces, plane_faces, rings_bounds}; #[cfg(test)] use build::{Camera, cuts, edge_distance, newell, section}; -pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; pub use build::{extrude, extrude_side_size, extrude_surfaces, plane}; pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; pub(crate) use inflate::inflate_faces; diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index d883ad14b8..69c0d114a4 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -10,6 +10,7 @@ use super::{ Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, MapCell, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, SolidSurface, SurfaceKind, V3, View, eye_distance, perspective_scale, }; +use crate::mesh::MeshPart; use crate::shadow::Projection; /// Turns 3D points into document points and shades faces for one view. @@ -61,9 +62,109 @@ impl Camera { } } -/// A face of a solid before projection: its contours in view space (holes running the other way) -/// and its outward normal. -pub(crate) type Face3 = (Vec>, V3); +/// A face of a solid before projection: its contours in view space (holes running the other way), +/// its outward normal, the part of the solid it belongs to, and where its corners lie on the +/// part's texture ([`Attrs`]). +#[derive(Clone, Debug)] +pub(crate) struct Face3 { + pub(crate) contours: Vec>, + pub(crate) normal: V3, + pub(crate) part: MeshPart, + pub(crate) attrs: Attrs, +} + +impl Face3 { + /// The texture coordinates of corner `v` of the face, and its own normal when it has one (a + /// corner of a smoothed bevel or of a puffed surface). A point that is no corner of the face + /// lies at the middle of the texture. + pub(crate) fn corner(&self, v: V3) -> ([f64; 2], Option) { + match &self.attrs { + Attrs::Planar(plane) => (plane.at(v), None), + Attrs::Corners(list) => self + .contours + .iter() + .zip(list) + .flat_map(|(c, l)| c.iter().zip(l)) + .find(|(c, _)| **c == v) + .map_or(([0.5, 0.5], None), |(_, (uv, n))| (*uv, *n)), + } + } +} + +/// Where the corners of a face lie on its part's texture, from 0 to 1 each way (u to the right, v +/// down), and the normals of the corners that have their own. +#[derive(Clone, Debug)] +pub(crate) enum Attrs { + /// Each corner's place on a plane ([`PlaneUv`]); every corner takes the face's normal. + Planar(PlaneUv), + /// For each corner of each contour, in order, its texture coordinates and its own normal + /// (`None` takes the face's). + Corners(Vec)>>), +} + +/// A plane's texture coordinates: a point `p` on it lies at `origin + x·s + y·t`, and `(s, t)` +/// within `area` goes to 0..1 each way. `x` and `y` are square to each other. An axis on which +/// `area` has no extent gives 0.5. +#[derive(Clone, Copy, Debug)] +pub(crate) struct PlaneUv { + pub(crate) origin: V3, + pub(crate) x: V3, + pub(crate) y: V3, + pub(crate) area: Rect, +} + +impl PlaneUv { + pub(crate) fn at(&self, p: V3) -> [f64; 2] { + let d = p.sub(self.origin); + let along = |axis: V3| d.dot(axis) / axis.dot(axis); + [share(along(self.x), self.area.x0, self.area.x1), share(along(self.y), self.area.y0, self.area.y1)] + } +} + +/// Where `v` lies from `lo` (0) to `hi` (1), within 0..1: 0.5 when the two are equal or `v` is not +/// finite. +pub(crate) fn share(v: f64, lo: f64, hi: f64) -> f64 { + let w = hi - lo; + if w > 1e-12 && v.is_finite() { ((v - lo) / w).clamp(0.0, 1.0) } else { 0.5 } +} + +/// The bounds of the points of `rings`, or an empty rectangle at the origin when they have none. +pub(crate) fn rings_bounds<'a>(rings: impl IntoIterator) -> Rect { + let mut points = rings.into_iter().flatten(); + let Some(first) = points.next() else { return Rect::ZERO }; + points.fold(Rect::from_points(*first, *first), |b, p| b.union_pt(*p)) +} + +/// The texture coordinate along each point of `ring` and back to its first point: the distance +/// along the ring from its first point over the ring's length, so the first point takes 0 and the +/// last entry (the first point again) 1. A ring of no length takes 0.5 throughout. +pub(crate) fn along_ring(ring: &[Point]) -> Vec { + let n = ring.len(); + let mut at = Vec::with_capacity(n + 1); + let mut sum = 0.0; + for i in 0..=n { + at.push(sum); + if let (Some(a), Some(b)) = (ring.get(i % n.max(1)), ring.get((i + 1) % n.max(1))) { + sum += a.distance(*b); + } + } + let total = at.last().copied().unwrap_or(0.0); + at.iter().map(|d| if total > 1e-12 { (d / total).clamp(0.0, 1.0) } else { 0.5 }).collect() +} + +/// The texture coordinates and corner normals of the faces of one band ([`Builder::curved_band`]): +/// the coordinate along the ring at each of its points and back at its first ([`along_ring`]), the +/// coordinate across the band at its two rings, and, for each edge of the rings, the normal of its +/// corners on each ring when they are smoothed (`None` takes the face's). +pub(super) struct BandMesh<'a> { + pub(super) part: MeshPart, + pub(super) u: &'a [f64], + pub(super) v: [f64; 2], + pub(super) normals: Option>, +} + +/// The smoothed normals of the corners of each edge on a band's two rings ([`BandMesh`]). +pub(super) type RowNormals<'a> = (&'a [Option], &'a [Option]); /// What a solid's builder makes: its facets, its faces before projection when a mesh is asked for /// (an error when they pass [`MAX_SOLID_FACES`] while the facets are built too), and the @@ -145,8 +246,22 @@ impl<'a> Builder<'a> { } } + /// Whether the builder keeps faces for a mesh. + pub(super) fn keeps_mesh(&self) -> bool { + self.mesh.is_some() + } + /// Add a face of view-space contours with outward normal `n` (view space), drawn in `order`. - pub(super) fn face(&mut self, contours: Vec>, n: V3, order: Order) -> Result<(), String> { + /// For a mesh it belongs to `part`, and `attrs` gives where its corners lie on the part's + /// texture, from its contours. + pub(super) fn face( + &mut self, + contours: Vec>, + n: V3, + order: Order, + part: MeshPart, + attrs: impl FnOnce(&[Vec]) -> Attrs, + ) -> Result<(), String> { let count: usize = contours.iter().map(Vec::len).sum(); if count < 3 { return Ok(()); @@ -155,7 +270,8 @@ impl<'a> Builder<'a> { self.facet(&contours, count, n, order)?; } let Some(mesh) = &mut self.mesh else { return Ok(()) }; - mesh.push((contours, n.unit())); + let attrs = attrs(&contours); + mesh.push(Face3 { contours, normal: n.unit(), part, attrs }); if mesh.len() > MAX_SOLID_FACES { if !self.draw { return Err(TOO_COMPLEX_SURFACE.into()); @@ -245,15 +361,23 @@ impl<'a> Builder<'a> { } /// A planar surface triangle with shared, smooth outward normals. Culling and sorting - /// still use its geometry, rather than the normals used only for lighting. - pub(super) fn smooth_triangle(&mut self, vertices: [V3; 3], normals: [V3; 3], back: bool) -> Result<(), String> { + /// still use its geometry, rather than the normals used only for lighting. For a mesh it + /// belongs to `part`, with its corners at `uv` on the part's texture and their normals. + pub(super) fn smooth_triangle( + &mut self, + vertices: [V3; 3], + normals: [V3; 3], + back: bool, + part: MeshPart, + uv: [[f64; 2]; 3], + ) -> Result<(), String> { let contours = vec![vertices.to_vec()]; let n = newell(&contours); let n = if back { V3(-n.0, -n.1, -n.2) } else { n }; let centre = vertices.iter().fold(V3::default(), |s, v| V3(s.0 + v.0 / 3.0, s.1 + v.1 / 3.0, s.2 + v.2 / 3.0)); let flip = !self.closed && self.camera.facing(centre, n.unit()) <= 0.0; let before = self.facets.len(); - self.face(contours, n, Order::Depth)?; + self.face(contours, n, Order::Depth, part, |_| Attrs::Corners(vec![uv.iter().zip(normals).map(|(uv, n)| (*uv, Some(n))).collect()]))?; if self.facets.len() == before || !self.camera.view.shade { return Ok(()); } @@ -270,15 +394,17 @@ impl<'a> Builder<'a> { /// The band between two partner rings (same length), as one quad per edge, or for a twisted /// wall with `cuts` (see [`cuts`]) as `cuts[i]` quads along edge `i`. `outward` is the - /// direction (before rotation) the band faces away from the solid, for orienting normals. - pub(super) fn band(&mut self, a: &[V3], b: &[V3], cuts: &[usize], outward: impl Fn(usize) -> V3) -> Result<(), String> { - self.curved_band(a, b, cuts, outward, None, None) + /// direction (before rotation) the band faces away from the solid, for orienting normals. For a + /// mesh the quads take their part, texture coordinates and corner normals from `mesh`. + pub(super) fn band(&mut self, a: &[V3], b: &[V3], cuts: &[usize], outward: impl Fn(usize) -> V3, mesh: &BandMesh) -> Result<(), String> { + self.curved_band(a, b, cuts, outward, None, None, mesh) } /// [`Builder::band`], with `curves` the pieces of curve the rings' edges follow and the /// outlines at `a` and `b`: a quad whose edge is not cut keeps its edges along the profile curved. /// With `side`, each quad carries where its corners lie on the side unrolled flat /// ([`Facet::surface`]). + #[allow(clippy::too_many_arguments)] pub(super) fn curved_band( &mut self, a: &[V3], @@ -287,6 +413,7 @@ impl<'a> Builder<'a> { outward: impl Fn(usize) -> V3, mut curves: Option, side: Option, + mesh: &BandMesh, ) -> Result<(), String> { let n = a.len().min(b.len()); // At 0 and 1, the corners themselves. @@ -316,7 +443,17 @@ impl<'a> Builder<'a> { normal = V3(-normal.0, -normal.1, -normal.2); } let before = self.facets.len(); - self.face(vec![quad], normal, order)?; + let attrs = |_: &[Vec]| { + let (u0, u1) = (mesh.u.get(i).copied().unwrap_or(0.5), mesh.u.get(i + 1).copied().unwrap_or(0.5)); + let (ua, ub) = (u0 + (u1 - u0) * s0, u0 + (u1 - u0) * s1); + let [va, vb] = mesh.v; + // A cut edge's pieces keep their own normals. + let normals = mesh.normals.filter(|_| pieces == 1); + let na = normals.and_then(|(na, _)| na.get(i).copied().flatten()); + let nb = normals.and_then(|(_, nb)| nb.get(i).copied().flatten()); + Attrs::Corners(vec![vec![([ua, va], na), ([ub, va], na), ([ub, vb], nb), ([ua, vb], nb)]]) + }; + self.face(vec![quad], normal, order, mesh.part, attrs)?; if self.facets.len() > before && let Some(f) = self.facets.last_mut() { @@ -648,6 +785,92 @@ fn steps(o: &Extrude) -> Vec { out } +/// The face a band between steps `s0` and `s1` borders: +1 between two front bevel steps, -1 when +/// it reaches a back bevel step, and 0 for a wall. +fn band_face(s0: &Step, s1: &Step) -> f64 { + if s1.face < 0.0 { + -1.0 + } else if s0.face > 0.0 && s1.face > 0.0 { + 1.0 + } else { + 0.0 + } +} + +/// The part of the mesh a band bordering `face` ([`band_face`]) belongs to. +fn band_part(face: f64) -> MeshPart { + if face > 0.0 { + MeshPart::FrontBevel + } else if face < 0.0 { + MeshPart::BackBevel + } else { + MeshPart::Side + } +} + +/// The texture coordinate across the side at each step, front to back: the distance from the +/// front cap's edge through the bevels and walls (inset and depth together) over the whole +/// distance to the back cap's edge. With no distance every step takes 0.5. +fn step_coordinates(steps: &[Step], depth: f64) -> Vec { + let mut at = Vec::with_capacity(steps.len()); + let mut sum = 0.0; + for (k, s) in steps.iter().enumerate() { + if let Some(p) = k.checked_sub(1).and_then(|k| steps.get(k)) { + sum += (s.inset - p.inset).hypot((s.t - p.t) * depth); + } + at.push(sum); + } + at.iter().map(|d| if sum > 1e-12 { (d / sum).clamp(0.0, 1.0) } else { 0.5 }).collect() +} + +/// The largest angle, in degrees, between two neighboring bands of one bevel whose shared corners +/// are smoothed for a mesh. A sharper turn (a Step profile's) stays a hard edge. +pub(crate) const BEVEL_CREASE: f64 = 60.0; + +/// For a mesh, the normal of each corner of each edge of `ring` at each step (one list per step, +/// one entry per edge) where the bands on either side are smoothed: two bands of the same bevel, +/// front or back, that turn by less than [`BEVEL_CREASE`], neither of them lying flat toward the +/// front or back (as a cap does). Such a corner takes the mean of the two bands' unit normals; +/// every other corner is `None` and takes its face's normal. `placed` holds the ring at each step +/// in view space. +fn smoothed_rows(camera: &Camera, ring: &[Point], steps: &[Step], placed: &[Vec]) -> Vec>> { + let n = ring.len(); + let front = camera.rotate(V3(0.0, 0.0, 1.0)); + // Each band's unit outward normal at each edge, as [`Builder::curved_band`] orients it. + let bands: Vec<(MeshPart, Vec)> = placed + .windows(2) + .zip(steps.windows(2)) + .map(|(pair, s)| { + let face = band_face(&s[0], &s[1]); + let normals = (0..n) + .map(|i| { + let j = (i + 1) % n; + let (Some(a), Some(c)) = (pair.first(), pair.get(1)) else { return V3::default() }; + let quad = [a.get(i), a.get(j), c.get(j), c.get(i)].into_iter().flatten().copied().collect::>(); + let normal = newell(std::slice::from_ref(&quad)).unit(); + if normal.dot(camera.rotate(outward(ring, i, face))) < 0.0 { V3(-normal.0, -normal.1, -normal.2) } else { normal } + }) + .collect(); + (band_part(face), normals) + }) + .collect(); + let crease = BEVEL_CREASE.to_radians().cos(); + let flat = |v: V3| v.dot(front).abs() > 1.0 - 1e-6; + (0..steps.len()) + .map(|k| { + let pair = k.checked_sub(1).and_then(|p| bands.get(p)).zip(bands.get(k)); + let Some(((_, n0), (_, n1))) = pair.filter(|((p0, _), (p1, _))| p0 == p1 && *p0 != MeshPart::Side) else { return vec![None; n] }; + n0.iter() + .zip(n1) + .map(|(a, b)| { + let whole = a.dot(*a) > 0.5 && b.dot(*b) > 0.5; + (whole && !flat(*a) && !flat(*b) && a.dot(*b) > crease).then(|| V3(a.0 + b.0, a.1 + b.1, a.2 + b.2).unit()) + }) + .collect() + }) + .collect() +} + /// Extrude & Bevel: the shape's outline extruded backwards, with optional twist, taper, bevels /// and caps. pub fn extrude(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude, view: View) -> Result, String> { @@ -737,9 +960,14 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio Some((k, side::along_ring(rings.get(k)?)?, y)) }) .flatten(); + // For a mesh: the texture coordinate across the side at each step, and the parts of the bands. + let across = step_coordinates(&steps, o.depth); + let part_of = |s0: &Step, s1: &Step| band_part(band_face(s0, s1)); for (r, ((ring, traced), pieces)) in rings.iter().zip(&traced).zip(&pieces).enumerate() { let unrolled = unrolled.as_ref().filter(|(k, ..)| *k == r); let placed: Vec> = steps.iter().map(|s| ring_at(ring, s)).collect(); + let u = along_ring(ring); + let rows = if b.keeps_mesh() { smoothed_rows(&camera, ring, &steps, &placed) } else { vec![] }; for (k, pair) in placed.windows(2).enumerate() { let ([a, c], Some(s0), Some(s1)) = (pair, steps.get(k), steps.get(k + 1)) else { continue }; b.cells = layout.as_ref().and_then(|(sides, spans)| { @@ -753,32 +981,34 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio let edges = sides.edges.get(r)?.iter().map(|e| e.map(|(section, u0, u1)| (base + section, u0, u1))).collect(); Some(BandCells { edges, across: (v0, v1) }) }); - // A band between two front bevel steps borders the front, one reaching a back bevel - // step the back; the rest are walls. - let face = if s1.face < 0.0 { - -1.0 - } else if s0.face > 0.0 && s1.face > 0.0 { - 1.0 - } else { - 0.0 - }; + let face = band_face(s0, s1); // The edges a band shares with a cap follow the cap's curves; the edges between two bands // stay straight, within the sampling tolerance. let (near, far) = (along.get(k).filter(|_| k == 0), along.get(k + 1).filter(|_| k + 2 == steps.len())); let curves = (near.is_some() || far.is_some()).then(|| WallCurves { spans: &traced.spans, near, far, budget: &mut budget }); let side = unrolled.and_then(|(_, x, y)| Some(SideBand { x, y: [*y.get(k)?, *y.get(k + 1)?] })); - b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side)?; + let normals = rows.get(k).zip(rows.get(k + 1)).map(|(na, nb)| (na.as_slice(), nb.as_slice())); + let v = [across.get(k).copied().unwrap_or(0.5), across.get(k + 1).copied().unwrap_or(0.5)]; + let mesh = BandMesh { part: part_of(s0, s1), u: &u, v, normals }; + b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side, &mesh)?; } } b.cells = None; if o.cap { // A cap turned toward the viewer covers the walls it overlaps, even those nearer than its // center: twisted walls, and the walls of a fill inside the solid of its stroke. - let caps = [(steps.first(), along.first(), 1.0, PlanarFace::Front), (steps.last(), along.last(), -1.0, PlanarFace::Back)]; - for (s, along, n, end) in caps { - let Some(s) = s else { continue }; + let caps = [ + (steps.first(), maps.first(), along.first(), 1.0, PlanarFace::Front, MeshPart::Front), + (steps.last(), maps.last(), along.last(), -1.0, PlanarFace::Back, MeshPart::Back), + ]; + // Each cap's corners take their art points, before any twist or taper, in the art's bounds. + let area = rings_bounds(rings.iter().copied()); + for (s, map, along, n, end, part) in caps { + let (Some(s), Some(map)) = (s, map) else { continue }; let before = b.len(); - b.face(rings.iter().map(|r| ring_at(r, s)).collect(), camera.rotate(V3(0.0, 0.0, n)), Order::Last)?; + let (x, y, origin) = map.frame(); + let plane = Attrs::Planar(PlaneUv { origin, x, y, area }); + b.face(rings.iter().map(|r| ring_at(r, s)).collect(), camera.rotate(V3(0.0, 0.0, n)), Order::Last, part, |_| plane)?; b.end(before, end); if let Some(along) = along { let traced: Vec<&Ring> = traced.iter().collect(); @@ -986,9 +1216,12 @@ pub(crate) fn plane_faces(path: &PathData, rule: FillRule, bounds: Rect, view: V // it is drawn last, as a cap is, and planes drawn in one order keep the order they are given in. let up = camera.rotate(V3(0.0, 0.0, 1.0)); let n = if camera.facing(V3::default(), up) < 0.0 { V3(-up.0, -up.1, -up.2) } else { up }; - b.face(contours, n, Order::Last)?; - b.end(0, PlanarFace::Front); let m = Placing::new(&camera, bounds.center(), Turn::new(bounds, 0.0, 1.0, 0.0), 0.0); + // The plane's corners take their art points in the art's bounds. + let (x, y, origin) = m.frame(); + let plane = Attrs::Planar(PlaneUv { origin, x, y, area: rings_bounds(rings.iter().map(|r| r.points.as_slice())) }); + b.face(contours, n, Order::Last, MeshPart::Front, |_| plane)?; + b.end(0, PlanarFace::Front); let at = |span: &Span, t: f64| camera.project(m.place(span.curve.eval(t))); let map = |p: Point| camera.project(m.place(p)); let along = Along { at: &at, map: Some(&map), affine: camera.eye.is_none(), tolerance: CURVE_TOLERANCE }; diff --git a/crates/three-d/src/solid/inflate.rs b/crates/three-d/src/solid/inflate.rs index 812cf88a42..5e11fd4b59 100644 --- a/crates/three-d/src/solid/inflate.rs +++ b/crates/three-d/src/solid/inflate.rs @@ -1,7 +1,11 @@ -use super::build::{Builder, Built, Camera, Keep, Order, Turn, check_bounds, cuts, fit, newell, outward}; +use super::build::{ + Attrs, BandMesh, Builder, Built, Camera, Keep, Order, Placing, PlaneUv, Turn, along_ring, check_bounds, cuts, fit, newell, outward, rings_bounds, + share, +}; use super::membrane::{Edges, MAX_MATERIAL_SEGMENTS, Membrane, cell_triangles, clip, crossings, filled, material}; use super::rings::{MAX_SOLID_POINTS, TOO_COMPLEX_SURFACE, curve_pieces, signed_area, solid_rings}; use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, PlanarFace, Point, Rect, V3, Vec2, View}; +use crate::mesh::MeshPart; /// The slices the sides are cut into: more to follow a twist or taper. fn slices(o: &Inflate) -> usize { @@ -278,6 +282,12 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee if n.dot(n) > 0.5 { n } else { V3(0.0, 0.0, 1.0) } }; let smooth = view.shade && view.has_colored_lights(); + // For a mesh, a point of the front or back takes its art point in the shape's bounds, and on a + // puffed surface its own normal, front or back (turned as the back is). + let area = rings_bounds(rings.iter().map(Vec::as_slice)); + let uv = |q: Point| [share(q.x, area.x0, area.x1), share(q.y, area.y0, area.y1)]; + let puffed = height > 0.0; + let back_normal = |n: V3, turn: &Turn| V3(turn.cos * n.0 - turn.sin * n.1, turn.sin * n.0 + turn.cos * n.1, -n.2); let camera = Camera::new(view, bounds, o.depth + 2.0 * height.max(reach)); // A graphic's offsets are from the center of the bounds the solid is built with. let center = bounds.center(); @@ -481,9 +491,12 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee let before = b.facets.len(); let outward = newell(&[front.to_vec()]); if smoothed { - b.smooth_triangle(front, points.map(|q| camera.rotate(normal(q))), false)?; + b.smooth_triangle(front, points.map(|q| camera.rotate(normal(q))), false, MeshPart::Front, points.map(uv))?; } else { - b.face(vec![front.to_vec()], outward, order)?; + let attrs = |_: &[Vec]| { + Attrs::Corners(vec![points.iter().map(|q| (uv(*q), puffed.then(|| camera.rotate(normal(*q))))).collect()]) + }; + b.face(vec![front.to_vec()], outward, order, MeshPart::Front, attrs)?; } if o.map_surface { mark_surface(&mut b, before, points, center, outward, PlanarFace::Front); @@ -496,15 +509,16 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee // normal is reversed. let outward = V3(-n.0, -n.1, -n.2); if smoothed { - let normals = points.map(|q| { - let n = normal(q); - // A uniform taper scales all three coordinates equally; - // twist turns the back normal about the shape's z-axis. - camera.rotate(V3(back_turn.cos * n.0 - back_turn.sin * n.1, back_turn.sin * n.0 + back_turn.cos * n.1, -n.2)) - }); - b.smooth_triangle(back, normals, true)?; + // A uniform taper scales all three coordinates equally; twist + // turns the back normal about the shape's z-axis. + let normals = points.map(|q| camera.rotate(back_normal(normal(q), &back_turn))); + b.smooth_triangle(back, normals, true, MeshPart::Back, points.map(uv))?; } else { - b.face(vec![back.to_vec()], outward, order)?; + let attrs = |_: &[Vec]| { + let corner = |q: &Point| (uv(*q), puffed.then(|| camera.rotate(back_normal(normal(*q), &back_turn)))); + Attrs::Corners(vec![points.iter().map(corner).collect()]) + }; + b.face(vec![back.to_vec()], outward, order, MeshPart::Back, attrs)?; } if o.map_surface { mark_surface(&mut b, before, points, center, outward, PlanarFace::Back); @@ -521,7 +535,11 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee pieces.iter().zip(&lifts).map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(*q, half + h)).collect()).collect(); let n = newell(&front); let order = if flat { Order::Last } else { Order::Depth }; - b.face(front, n, order)?; + let corners = |side: &dyn Fn(Point) -> Option| -> Attrs { + Attrs::Corners(pieces.iter().map(|p| p.iter().map(|q| (uv(*q), side(*q))).collect()).collect()) + }; + let front_normal = |q: Point| puffed.then(|| camera.rotate(normal(q))); + b.face(front, n, order, MeshPart::Front, |_| corners(&front_normal))?; if o.both_sides && o.cap { // The back winds the same way round as the front, so its outward normal is // reversed. @@ -531,7 +549,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee .map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(back_turn.apply(*q), -half - h * back_turn.scale)).collect()) .collect(); let n = newell(&back); - b.face(back, V3(-n.0, -n.1, -n.2), order)?; + let back_side = |q: Point| puffed.then(|| camera.rotate(back_normal(normal(q), &back_turn))); + b.face(back, V3(-n.0, -n.1, -n.2), order, MeshPart::Back, |_| corners(&back_side))?; } } } @@ -539,9 +558,11 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee } if !o.both_sides && o.cap { let back: Vec> = rings.iter().map(|r| r.iter().map(|p| camera.place(back_turn.apply(*p), -half)).collect()).collect(); + let (x, y, origin) = Placing::new(&camera, bounds.center(), back_turn, -half).frame(); + let plane = Attrs::Planar(PlaneUv { origin, x, y, area }); // The back turned toward the viewer covers the walls it overlaps, even those nearer than // its center: twisted walls, and the walls of a fill inside the solid of its stroke. - b.face(back, camera.rotate(V3(0.0, 0.0, -1.0)), Order::Last)?; + b.face(back, camera.rotate(V3(0.0, 0.0, -1.0)), Order::Last, MeshPart::Back, |_| plane)?; } if o.depth > 0.0 { // The sides, cut into slices that follow a twist or taper. @@ -558,10 +579,14 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee if b.len().saturating_add(edges.saturating_mul(slices)) > MAX_SOLID_FACES { return Err(TOO_COMPLEX_SURFACE.into()); } + // For a mesh, the sides run across from the front (0) to the back (1). + let across = |k: usize| k as f64 / slices.max(1) as f64; let sides = |b: &mut Builder<'_>, pieces: &[Vec]| -> Result<(), String> { for (ring, pieces) in rings.iter().zip(pieces) { + let u = along_ring(ring); for k in 0..slices { - b.band(&at(ring, k), &at(ring, k + 1), pieces, |i| outward(ring, i, 0.0))?; + let mesh = BandMesh { part: MeshPart::Side, u: &u, v: [across(k), across(k + 1)], normals: None }; + b.band(&at(ring, k), &at(ring, k + 1), pieces, |i| outward(ring, i, 0.0), &mesh)?; } } Ok(()) diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index d4b86d7b10..a4db35adb0 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -232,7 +232,7 @@ fn a_face_reaching_past_the_eye_has_no_plane() { for (far, has_plane) in [(eye / 2.0, true), (2.0 * eye, false)] { let mut builder = Builder::new(&camera, false, false, Keep::Facets); let corners = vec![V3(-10.0, -10.0, 0.0), V3(10.0, -10.0, 0.0), V3(0.0, 10.0, far)]; - builder.face(vec![corners], V3(0.0, -far, 20.0), Order::Depth).unwrap(); + builder.face(vec![corners], V3(0.0, -far, 20.0), Order::Depth, crate::MeshPart::Front, |_| super::Attrs::Corners(vec![])).unwrap(); assert_eq!(builder.facets.len(), 1, "{far}"); assert_eq!(builder.facets[0].plane.is_some(), has_plane, "{far}"); } diff --git a/crates/three-d/src/tests/cut_sides.rs b/crates/three-d/src/tests/cut_sides.rs index 184ce53085..0016daf1e0 100644 --- a/crates/three-d/src/tests/cut_sides.rs +++ b/crates/three-d/src/tests/cut_sides.rs @@ -276,8 +276,8 @@ fn the_cut_sides_kept_for_a_mesh_have_a_corner_at_every_corner_of_the_side() { // cut side's alone, which faces back against the sweep. let in_plane = |all: bool| { let start = |n: &V3| (n.0.abs() + n.1.abs() + (n.2 + 1.0).abs()) < 1e-9; - let kept = faces.iter().filter(|(_, n)| all || start(n)); - kept.flat_map(|(contours, _)| contours.iter().flatten().copied()).filter(|v| v.2.abs() < 1e-9).collect::>() + let kept = faces.iter().filter(|f| all || start(&f.normal)); + kept.flat_map(|f| f.contours.iter().flatten().copied()).filter(|v| v.2.abs() < 1e-9).collect::>() }; let cut = in_plane(false); assert!(!cut.is_empty()); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..06cf20131d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7269,6 +7269,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg a 3D effect on a group's fill or stroke draws nothing un efecte 3D al farciment o al traç d’un grup no dibuixa res @msg a 3D effect on a group's fill or stroke draws nothing to export un efecte 3D al farciment o al traç d’un grup no dibuixa res per exportar @msg The 3D object is too complex to export L’objecte 3D és massa complex per exportar-lo +@msg The 3D object's mesh is incomplete or holds a value that is not a number La malla de l’objecte 3D és incompleta o conté un valor que no és un nombre @msg give one element indica un element @msg the element needs an id, the filter's name l’element necessita un id, el nom del filtre @msg an SVG filter's id is at most {MAX_NAME} characters l’id d’un filtre SVG té com a màxim {MAX_NAME} caràcters diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..999627f8f6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6860,6 +6860,7 @@ mark-style Japanese Japonské @msg a 3D effect on a group's fill or stroke draws nothing 3D efekt na výplni nebo tahu skupiny nic nekreslí @msg a 3D effect on a group's fill or stroke draws nothing to export 3D efekt na výplni nebo tahu skupiny nekreslí nic k exportu @msg The 3D object is too complex to export 3D objekt je pro export příliš složitý +@msg The 3D object's mesh is incomplete or holds a value that is not a number Síť 3D objektu je neúplná nebo obsahuje hodnotu, která není číslo @msg the element needs an id, the filter's name prvek potřebuje id, název filtru @msg an SVG filter's id is at most {MAX_NAME} characters id filtru SVG má nejvýše {MAX_NAME} znaků @msg <{_1}> isn't an element of an SVG filter <{_1}> není prvkem filtru SVG diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..56be9a99e0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -410,6 +410,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg a 3D effect on a group's fill or stroke draws nothing en 3D-effekt på en gruppes udfyldning eller streg tegner intet @msg a 3D effect on a group's fill or stroke draws nothing to export en 3D-effekt på en gruppes udfyldning eller streg tegner intet at eksportere @msg The 3D object is too complex to export 3D-objektet er for komplekst til at blive eksporteret +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3D-objektets net er ufuldstændigt eller indeholder en værdi, der ikke er et tal @msg give one element angiv ét -element @msg the element needs an id, the filter's name -elementet skal have et id, filterets navn @msg an SVG filter's id is at most {MAX_NAME} characters et SVG-filters id er højst {MAX_NAME} tegn diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..53c60f59a6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6427,6 +6427,7 @@ lighting Light Licht @msg a 3D effect on a group's fill or stroke draws nothing ein 3D-Effekt auf der Fläche oder Kontur einer Gruppe zeichnet nichts @msg a 3D effect on a group's fill or stroke draws nothing to export ein 3D-Effekt auf der Fläche oder Kontur einer Gruppe zeichnet nichts, das exportiert werden kann @msg The 3D object is too complex to export Das 3D-Objekt ist zu komplex für den Export +@msg The 3D object's mesh is incomplete or holds a value that is not a number Das Netz des 3D-Objekts ist unvollständig oder enthält einen Wert, der keine Zahl ist @msg the element needs an id, the filter's name das -Element braucht eine id, den Namen des Filters @msg an SVG filter's id is at most {MAX_NAME} characters die id eines SVG-Filters hat höchstens {MAX_NAME} Zeichen @msg <{_1}> isn't an element of an SVG filter <{_1}> ist kein Element eines SVG-Filters diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..c6612ad3a9 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6242,6 +6242,7 @@ variable-list-end {0}, {1} {0} και {1} @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 3D object's mesh is incomplete or holds a value that is not a number Το πλέγμα του αντικειμένου 3D είναι ελλιπές ή περιέχει τιμή που δεν είναι αριθμός @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} χαρακτήρες diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..3a4b1d39f7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6832,6 +6832,7 @@ mark-style Japanese Japonesas @msg a 3D effect on a group's fill or stroke draws nothing un efecto 3D en el relleno o el trazo de un grupo no dibuja nada @msg a 3D effect on a group's fill or stroke draws nothing to export un efecto 3D en el relleno o el trazo de un grupo no dibuja nada que exportar @msg The 3D object is too complex to export El objeto 3D es demasiado complejo para exportarlo +@msg The 3D object's mesh is incomplete or holds a value that is not a number La malla del objeto 3D está incompleta o contiene un valor que no es un número @msg give one element indique un elemento @msg the element needs an id, the filter's name el elemento necesita un id, el nombre del filtro @msg an SVG filter's id is at most {MAX_NAME} characters el id de un filtro SVG tiene como máximo {MAX_NAME} caracteres diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..379eb37892 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6760,6 +6760,7 @@ mark-style Japanese Japanilainen @msg a 3D effect on a group's fill or stroke draws nothing ryhmän täytön tai viivan 3D-tehoste ei piirrä mitään @msg a 3D effect on a group's fill or stroke draws nothing to export ryhmän täytön tai viivan 3D-tehoste ei piirrä mitään vietävää @msg The 3D object is too complex to export 3D-objekti on liian monimutkainen vietäväksi +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3D-objektin verkko on puutteellinen tai sisältää arvon, joka ei ole luku @msg give one element anna yksi -elementti @msg the element needs an id, the filter's name -elementti tarvitsee id:n, suotimen nimen @msg an SVG filter's id is at most {MAX_NAME} characters SVG-suotimen id on enintään {MAX_NAME} merkkiä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..bf54abd6ee 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6443,6 +6443,7 @@ lighting Light Lumière @msg a 3D effect on a group's fill or stroke draws nothing un effet 3D sur le fond ou le contour d’un groupe ne dessine rien @msg a 3D effect on a group's fill or stroke draws nothing to export un effet 3D sur le fond ou le contour d’un groupe ne dessine rien à exporter @msg The 3D object is too complex to export L’objet 3D est trop complexe pour être exporté +@msg The 3D object's mesh is incomplete or holds a value that is not a number Le maillage de l’objet 3D est incomplet ou contient une valeur qui n’est pas un nombre @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) l’objet n’a aucun effet 3D (Extrusion et biseautage, Révolution, Gonfler ou Rotation) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` doit être un objet ne contenant que `mode`, avec la valeur shaded ou wireframe @msg its 3D effect builds no solid son effet 3D ne construit aucun volume diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..e3b622ca0f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9174,6 +9174,7 @@ liquify-list-end {0}, {1} {0} और {1} @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 3D object's mesh is incomplete or holds a value that is not a number 3D ऑब्जेक्ट का मेश अधूरा है या उसमें ऐसा मान है जो संख्या नहीं है @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 SVG फ़िल्टर की id अधिकतम {MAX_NAME} वर्णों की होती है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..6caee13e40 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6845,6 +6845,7 @@ variable-list-end {0}, {1} {0} és {1} @msg a 3D effect on a group's fill or stroke draws nothing a csoport kitöltésén vagy körvonalán lévő 3D effektus nem rajzol semmit @msg a 3D effect on a group's fill or stroke draws nothing to export a csoport kitöltésén vagy körvonalán lévő 3D effektus nem rajzol semmi exportálhatót @msg The 3D object is too complex to export A 3D objektum túl összetett az exportáláshoz +@msg The 3D object's mesh is incomplete or holds a value that is not a number A 3D objektum hálója hiányos, vagy olyan értéket tartalmaz, amely nem szám @msg the element needs an id, the filter's name a elemnek id kell, a szűrő neve @msg an SVG filter's id is at most {MAX_NAME} characters egy SVG-szűrő id-je legfeljebb {MAX_NAME} karakter @msg <{_1}> isn't an element of an SVG filter a(z) <{_1}> nem SVG-szűrő eleme diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..4f2d3f71de 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -311,6 +311,7 @@ @msg a 3D effect on a group's fill or stroke draws nothing efek 3D pada isian atau goresan grup tidak menggambar apa pun @msg a 3D effect on a group's fill or stroke draws nothing to export efek 3D pada isian atau goresan grup tidak menggambar apa pun untuk diekspor @msg The 3D object is too complex to export Objek 3D terlalu rumit untuk diekspor +@msg The 3D object's mesh is incomplete or holds a value that is not a number Objek 3D memiliki mesh yang tidak lengkap atau berisi nilai yang bukan angka @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objek tidak memiliki efek 3D (Ekstrusi & bevel, Revolusi, Gelembungkan, atau Putar) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` harus berupa objek yang hanya berisi `mode`, bernilai shaded atau wireframe @msg its 3D effect builds no solid efek 3D-nya tidak membangun bentuk padat diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..eeaae620f1 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6474,6 +6474,7 @@ lighting Light Luce @msg a 3D effect on a group's fill or stroke draws nothing un effetto 3D sul riempimento o sulla traccia di un gruppo non disegna nulla @msg a 3D effect on a group's fill or stroke draws nothing to export un effetto 3D sul riempimento o sulla traccia di un gruppo non disegna nulla da esportare @msg The 3D object is too complex to export L'oggetto 3D è troppo complesso per essere esportato +@msg The 3D object's mesh is incomplete or holds a value that is not a number La mesh dell'oggetto 3D è incompleta o contiene un valore che non è un numero @msg the element needs an id, the filter's name l'elemento richiede un id, il nome del filtro @msg an SVG filter's id is at most {MAX_NAME} characters l'id di un filtro SVG ha al massimo {MAX_NAME} caratteri @msg <{_1}> isn't an element of an SVG filter <{_1}> non è un elemento di un filtro SVG diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..89218ca5bf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6523,6 +6523,7 @@ lighting Light ライト @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 3D object's mesh is incomplete or holds a value that is not a number 3D オブジェクトのメッシュが不完全か、数値でない値を含んでいます @msg the element needs an id, the filter's name 要素には id (フィルターの名前) が必要です @msg an SVG filter's id is at most {MAX_NAME} characters SVG フィルターの id は {MAX_NAME} 文字までです @msg <{_1}> isn't an element of an SVG filter <{_1}> は SVG フィルターの要素ではありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..e41a0119b6 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8198,6 +8198,7 @@ arrowhead Feather ბუმბული @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 3D object's mesh is incomplete or holds a value that is not a number 3D ობიექტის ბადე არასრულია ან შეიცავს მნიშვნელობას, რომელიც რიცხვი არ არის @msg feConvolveMatrix's order feConvolveMatrix-ის order @msg feMorphology's radius feMorphology-ის radius @msg a blur's stdDeviation გაბუნდოვნების stdDeviation diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..dfb2913999 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6444,6 +6444,7 @@ lighting Light 광원 @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 3D object's mesh is incomplete or holds a value that is not a number 3D 개체의 메시가 불완전하거나 숫자가 아닌 값을 포함합니다 @msg the element needs an id, the filter's name 요소에는 필터 이름인 id가 필요합니다 @msg an SVG filter's id is at most {MAX_NAME} characters SVG 필터의 id는 최대 {MAX_NAME}자입니다 @msg <{_1}> isn't an element of an SVG filter <{_1}>은(는) SVG 필터의 요소가 아닙니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..5a2b732600 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8608,6 +8608,7 @@ mark-style Japanese Japans @msg a 3D effect on a group's fill or stroke draws nothing een 3D-effect op de vulling of contour van een groep tekent niets @msg a 3D effect on a group's fill or stroke draws nothing to export een 3D-effect op de vulling of contour van een groep tekent niets om te exporteren @msg The 3D object is too complex to export Het 3D-object is te complex om te exporteren +@msg The 3D object's mesh is incomplete or holds a value that is not a number Het net van het 3D-object is onvolledig of bevat een waarde die geen getal is @msg the element needs an id, the filter's name het -element heeft een id nodig, de naam van het filter @msg an SVG filter's id is at most {MAX_NAME} characters de id van een SVG-filter is hoogstens {MAX_NAME} tekens lang @msg <{_1}> isn't an element of an SVG filter <{_1}> is geen element van een SVG-filter diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..81851f0615 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6686,6 +6686,7 @@ mark-style Japanese Japońskie @msg a 3D effect on a group's fill or stroke draws nothing efekt 3D na wypełnieniu lub obrysie grupy niczego nie rysuje @msg a 3D effect on a group's fill or stroke draws nothing to export efekt 3D na wypełnieniu lub obrysie grupy nie rysuje niczego do eksportu @msg The 3D object is too complex to export Obiekt 3D jest zbyt złożony, aby go wyeksportować +@msg The 3D object's mesh is incomplete or holds a value that is not a number Siatka obiektu 3D jest niekompletna lub zawiera wartość, która nie jest liczbą @msg the element needs an id, the filter's name element wymaga id, czyli nazwy filtra @msg an SVG filter's id is at most {MAX_NAME} characters id filtra SVG ma najwyżej {MAX_NAME} znaków @msg <{_1}> isn't an element of an SVG filter <{_1}> nie jest elementem filtra SVG diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..cee5fae3aa 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6808,6 +6808,7 @@ mark-style Japanese Japonesas @msg a 3D effect on a group's fill or stroke draws nothing um efeito 3D no preenchimento ou traçado de um grupo não desenha nada @msg a 3D effect on a group's fill or stroke draws nothing to export um efeito 3D no preenchimento ou traçado de um grupo não desenha nada para exportar @msg The 3D object is too complex to export O objeto 3D é complexo demais para ser exportado +@msg The 3D object's mesh is incomplete or holds a value that is not a number A malha do objeto 3D está incompleta ou contém um valor que não é um número @msg the element needs an id, the filter's name o elemento precisa de um id, o nome do filtro @msg an SVG filter's id is at most {MAX_NAME} characters o id de um filtro SVG tem no máximo {MAX_NAME} caracteres @msg <{_1}> isn't an element of an SVG filter <{_1}> não é um elemento de filtro SVG diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..2f72bcfb4d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6471,6 +6471,7 @@ lighting Light Свет @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 3D object's mesh is incomplete or holds a value that is not a number Сетка 3D-объекта неполна или содержит значение, которое не является числом @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 diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..480faf82a3 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6337,6 +6337,7 @@ lighting Light Ljus @msg a 3D effect on a group's fill or stroke draws nothing en 3D-effekt på en grupps fyllning eller linje ritar ingenting @msg a 3D effect on a group's fill or stroke draws nothing to export en 3D-effekt på en grupps fyllning eller linje ritar ingenting att exportera @msg The 3D object is too complex to export 3D-objektet är för komplext för att exporteras +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3D-objektets nät är ofullständigt eller innehåller ett värde som inte är ett tal @msg give one element ange ett -element @msg the element needs an id, the filter's name -elementet behöver ett id, filtrets namn @msg an SVG filter's id is at most {MAX_NAME} characters ett SVG-filters id har högst {MAX_NAME} tecken diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..0ec642e48f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6164,6 +6164,7 @@ lighting Light Işık @msg a 3D effect on a group's fill or stroke draws nothing bir grubun dolgusundaki veya konturundaki 3 boyutlu efekt hiçbir şey çizmez @msg a 3D effect on a group's fill or stroke draws nothing to export bir grubun dolgusundaki veya konturundaki 3 boyutlu efekt dışa aktarılacak hiçbir şey çizmez @msg The 3D object is too complex to export 3 boyutlu nesne dışa aktarmak için çok karmaşık +@msg The 3D object's mesh is incomplete or holds a value that is not a number 3 boyutlu nesnenin ağı eksik veya sayı olmayan bir değer içeriyor @msg the element needs an id, the filter's name öğesinin, filtrenin adı olan bir id değeri olmalıdır @msg an SVG filter's id is at most {MAX_NAME} characters bir SVG filtresinin id değeri en fazla {MAX_NAME} karakterdir @msg <{_1}> isn't an element of an SVG filter <{_1}> bir SVG filtresi öğesi değildir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..9d684ea4a8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6454,6 +6454,7 @@ lighting Light Світло @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 3D object's mesh is incomplete or holds a value that is not a number Сітка 3D-об’єкта неповна або містить значення, яке не є числом @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 diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..45fab60c7b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6205,6 +6205,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg a 3D effect on a group's fill or stroke draws nothing hiệu ứng 3D trên phần tô hoặc nét của nhóm không vẽ gì @msg a 3D effect on a group's fill or stroke draws nothing to export hiệu ứng 3D trên phần tô hoặc nét của nhóm không vẽ gì để xuất @msg The 3D object is too complex to export Đối tượng 3D quá phức tạp để xuất +@msg The 3D object's mesh is incomplete or holds a value that is not a number Lưới của đối tượng 3D chưa đầy đủ hoặc chứa giá trị không phải là số @msg give one element hãy chỉ định một phần tử @msg the element needs an id, the filter's name phần tử cần có id, là tên của bộ lọc @msg an SVG filter's id is at most {MAX_NAME} characters id của bộ lọc SVG có tối đa {MAX_NAME} ký tự diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..d10f494a61 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6723,6 +6723,7 @@ lighting Light 光源 @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 3D object's mesh is incomplete or holds a value that is not a number 3D 对象的网格不完整,或含有非数字的值 @msg the element needs an id, the filter's name 元素需要 id,即滤镜的名称 @msg an SVG filter's id is at most {MAX_NAME} characters SVG 滤镜的 id 最多 {MAX_NAME} 个字符 @msg <{_1}> isn't an element of an SVG filter <{_1}> 不是 SVG 滤镜的元素 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..fa9a5b7d81 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6572,6 +6572,7 @@ lighting Light 光源 @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 3D object's mesh is incomplete or holds a value that is not a number 3D 物件的網格不完整,或含有非數字的值 @msg the element needs an id, the filter's name 元素需要 id,也就是濾鏡的名稱 @msg an SVG filter's id is at most {MAX_NAME} characters SVG 濾鏡的 id 最多 {MAX_NAME} 個字元 @msg <{_1}> isn't an element of an SVG filter <{_1}> 不是 SVG 濾鏡的元素 diff --git a/docs/effects-parity.md b/docs/effects-parity.md index a3ba859915..f5f0dea3e1 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -183,7 +183,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Extrude & Bevel's walls and bevels and around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate, or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes and the custom bevels with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art for Extrude & Bevel (Classic) and Revolve (Classic): one document symbol on each numbered surface, surface navigation with visible and hidden marks and a red outline on the artboard, move, scale and rotate on the surface laid out flat, Scale to Fit, Clear, Clear All, Shade Artwork, Invisible Geometry, kept by Expand Appearance and exports, `threeD.mapArt` ([map artwork to a 3D object](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=189)) | | Turntable (30.0 beta) | none | -| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit; no graphics on Revolve's side, no materials and no shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | +| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit, and the graphics on Revolve's side as a texture of the side unrolled; every corner carries texture coordinates and a normal, smoothed across a curved bevel and over Inflate's puff ([three-d.md](three-d.md#3d-meshes)); no materials and no lighting ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering, diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..5cc001c03a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10678,7 +10678,13 @@ fill's, each stroke's, a group's members') is its own mesh, with a two-sided mat (a gradient's stops averaged, a pattern gray); a solid with mapped graphics is split into a textured mesh for each face that carries them and a plain mesh for the rest, as described below. The mesh holds the solid's faces before they are projected onto the page, those turned away from the viewer included, at the object's 3D rotation, y up, about the point the object turns -about: in points (USD's layer gives `metersPerUnit`), in meters in glTF. Files that would share a name get `-2`, `-3` and so on. +about: in points (USD's layer gives `metersPerUnit`), in meters in glTF. Each corner's normal is its face's, except +where two bands of one bevel meet at a turn of less than 60° (neither band lying flat toward the front or back) and on +Inflate's puffed front and back: there the normals are smoothed, and an app that reads them shades a rounded bevel or a +puff without facets ([three-d.md](three-d.md#3d-meshes)). Every corner also has texture coordinates from 0 to 1 +(`vt`, `TEXCOORD_0`, `primvars:st`), laid out for each kind of face as three-d.md describes. A mesh whose lists do not +match, or that holds a value that is not a number, stops the export with "The 3D object's mesh is incomplete or holds a +value that is not a number", and nothing is written. Files that would share a name get `-2`, `-3` and so on. Graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (`threeD.mapGraphic`) are exported as a PNG texture of that face: the face's color with its graphics drawn over it, flat and unlit, on a mesh of the face's own triangles with texture coordinates and a material that shows the texture. A face that is not opaque keeps its opacity diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..488b9b4b36 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1690,6 +1690,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`. + - The meshes of Extrude & Bevel, Inflate, Rotate and Revolve carry texture coordinates for every corner, normals smoothed across the bands of a curved bevel (a turn of 60° or more stays a hard edge, VectorCraft's own value) and over Inflate's puff, and a part for each triangle (front, back, side, front bevel, back bevel, end cap, cut side); exported OBJ, glTF and USD files write the new normals and every corner's texture coordinates, refuse a mesh whose lists do not match or hold a value that is not a number, and the vector facets stay the same bit for bit ([three-d.md](three-d.md#3d-meshes)). Tests `mesh::tests_attributes::every_corner_has_texture_coordinates_and_every_triangle_a_part`, `a_rounded_or_custom_bevels_normals_turn_smoothly_across_its_bands`, `a_steps_sharp_turns_and_a_classic_bevel_stay_hard_edges`, `the_meshs_outline_stays_within_a_twentieth_of_a_point_of_the_vector_facets`, `mesh3d::tests::a_mesh_whose_lists_do_not_match_or_hold_no_number_is_refused`. - Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). The graphics wrapped around Revolve's side export the same way, as a texture of the side unrolled as the canvas lays it out, on a mesh of the side's triangles, with its end caps and cut sides plain. Materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`, `a_revolved_sides_corners_lie_where_the_canvas_places_the_unrolled_side`, `a_revolved_sides_layout_matches_its_drawn_faces_at_every_turn`, `export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format`, `a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side`. - The 3D and Materials panel works out whether Export 3D Object is available once for each document revision and reuses it on later frames. The button shows the same state. With 200,000 paths selected, working it out on every frame took a median 61.6 ms of thread CPU time per frame in a release build on Linux (57.1 ms with a path of a compound path with Extrude & Bevel selected last); the first frame after a change still takes about as long, and later frames take about 2 ns (`panels::three_d::tests::export_3d_object_state_kept_for_a_revision_equals_a_fresh_one`, `export_3d_object_state_is_worked_out_once_per_revision`, `export_3d_object_state_timing`). - Checking an Extrude & Bevel (both kinds) or Inflate effect builds each solid the effect draws once, about the bounds the effect draws it about; a shape with no fill still has its profile built on its own. Tests `solids::tests::the_check_builds_each_drawn_solid_once`, `the_check_builds_the_profile_of_a_shape_with_no_fill`. diff --git a/docs/three-d.md b/docs/three-d.md index 2327eb1c24..afbbb2a996 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -95,6 +95,37 @@ pages describe it. rotation and light rings on the artboard are part of the options dialog only. The panel's Lighting tab has the lighting widget instead ([Lighting widget](#lighting-widget)). +## 3D meshes + +The meshes that Export 3D Object writes come from the `three-d` crate's `Mesh`, built from the same faces the effect +draws. The vector facets on the canvas and in SVG and PDF do not change with what follows. Besides positions, +normals and triangles, a mesh carries: + +- **Normals.** A corner takes its face's normal. Where two bands of one bevel meet, the shared corners take the mean of + the two bands' normals, unless the bevel turns there by 60° or more (a Step profile's turns) or one of the bands lies + flat toward the front or back; caps, walls and the edges between a bevel and a cap or wall stay hard. On Inflate's + puffed front and back each corner takes the surface's own normal. The bevel settings shape its profile into a + rounded curve or an ornamental one ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html)); + the smoothing rule and the 60° crease are VectorCraft's own. +- **Texture coordinates** for every corner, each from 0 to 1, u to the right and v down, as glTF 2.0 places + `TEXCOORD_0` (). Caps, Rotate's plane and Inflate's + front and back take each corner's art point, before any twist or taper, in the art's bounds; the back is not + mirrored. Extrude & Bevel's bevels and walls and Inflate's walls take u along each contour of the outline from its + first point, as the distance over the contour's length, so the seam at the first point has corners at both 0 and 1, + and v across the side from the front cap's edge to the back cap's. Revolve's side takes u around the sweep from its + start and v along each contour of the profile; its end caps span the disk they close, and its cut sides take each + corner's profile point in the profile's bounds. An axis with no extent takes 0.5. These layouts are VectorCraft's + own. +- **A part for each triangle**: `Front` (a front cap, Rotate's plane, Inflate's front), `Back`, `Side` (walls and + Revolve's swept side), `FrontBevel`, `BackBevel`, `Cap` (Revolve's end caps) and `Cut` (the flat sides of a Revolve + of less than 360°). + +The exported files write the normals and the texture coordinates of every corner: OBJ's `vt` (up from the bottom), +glTF's `TEXCOORD_0` and USD's `primvars:st` (up from the bottom). A face with mapped graphics writes the coordinates +of its texture instead, laid out as the graphics are ([Graphics](#graphics)). The files do not write the parts. A +mesh whose lists do not match, or that holds a value that is not a number, stops the export with an error before any +file is written. + ## Extrude & Bevel The art is the front face; its outline is extruded backwards by **Depth** (0–2,000 pt), so seen straight on the From 555b6192283c61fd23e2a9e3faad39c3ddf286ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:34:20 -0800 Subject: [PATCH 069/178] 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 070/178] 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 071/178] 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 1ab09c8978191fd1f64c3c50e2db5df30168ddf2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:56:57 -0800 Subject: [PATCH 072/178] Scripts: UnitValue measurements convert and calculate with their units Scripts get the global UnitValue constructor: a number with one of the length units (inches, feet, yards, miles, millimeters, centimeters, meters, kilometers, points, picas, traditional points and picas, ciceros), pixels or percent. as() and convert() give or change the unit, baseUnit sets what one pixel and 100% measure, and the arithmetic, comparison and unary operators calculate with the object's number. With two objects the right one is converted to the left one's unit. Conversions go through exact ratios to the inch, so 1 in is exactly 72 pt. An unknown unit or text makes an invalid object; converting it or using it with an operator, a result that is not finite and a comparison with a number that is not finite throw a RangeError. A realm without UnitValue keeps the standard operators. docs/mcp.md describes the class. --- crates/engine/src/script/mod.rs | 1 + crates/engine/src/tests/script_dollar.rs | 13 +- .../tests/it/script_host_vs_scriptcheck.rs | 4 +- crates/js/src/heap.rs | 6 + crates/js/src/interp.rs | 16 + crates/js/src/lib.rs | 3 + crates/js/src/realm.rs | 11 + crates/js/src/unit_value.rs | 522 ++++++++++++++++++ crates/js/src/unit_value_tests.rs | 359 ++++++++++++ docs/mcp.md | 21 + docs/target-app-parity.md | 1 + 11 files changed, 954 insertions(+), 3 deletions(-) create mode 100644 crates/js/src/unit_value.rs create mode 100644 crates/js/src/unit_value_tests.rs diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..378b41b9b7 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2073,6 +2073,7 @@ impl Session { })); } (if fresh { realm.add_script_extensions() } else { Ok(()) }) + .and_then(|()| if fresh { realm.add_unit_values() } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) diff --git a/crates/engine/src/tests/script_dollar.rs b/crates/engine/src/tests/script_dollar.rs index 849d5b9080..bef2cf5c93 100644 --- a/crates/engine/src/tests/script_dollar.rs +++ b/crates/engine/src/tests/script_dollar.rs @@ -1,5 +1,5 @@ -//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize` and -//! `toSource`, and what of them one run keeps to itself. +//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize`, `toSource` +//! and `UnitValue`, and what of them one run keeps to itself. use std::time::Duration; @@ -140,6 +140,15 @@ fn to_source_writes_plain_data() { assert!(thrown(&mut s, "toSource(vc)").starts_with("TypeError"), "a host object is not plain data"); } +#[test] +fn unit_values_convert_and_calculate_in_a_run() { + let mut s = Session::new(); + assert_eq!(value(&mut s, "UnitValue('1 in').as('pt')"), json!(72)); + assert_eq!(value(&mut s, "String(new UnitValue(1, 'm') + new UnitValue(10, 'cm'))"), json!("1.1 m")); + assert_eq!(value(&mut s, "[UnitValue(98, 'cm') < UnitValue(1, 'm'), UnitValue(98, 'cm') == 98]"), json!([true, true])); + assert!(thrown(&mut s, "UnitValue(1, 'in').as('furlong')").starts_with("Error")); +} + #[test] fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() { let mut s = Session::new(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..52aa59e27d 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -43,8 +43,10 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// Reading a file or a folder, a file dialog and a message to the person do not change anything /// outside it. const INSIDE: &[(&str, &str)] = &[ - ("", "$ File Folder alert confirm localize prompt toSource"), + ("", "$ File Folder UnitValue alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), + ("UnitValue.", "baseUnit baseUnit= length prototype"), + ("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="), ("localize.", "length"), ("toSource.", "length"), ( diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..60362f0c90 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,8 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// A `UnitValue` object and its measurement ([`crate::unit_value`]). + UnitValue(Box), } /// What an XML value is. @@ -322,6 +324,7 @@ impl Class { Class::String(_) => "String", Class::RegExp(_) => "RegExp", Class::Date(_) => "Date", + Class::UnitValue(_) => "UnitValue", } } } @@ -395,6 +398,8 @@ pub(crate) const XML_LIST_BYTES: usize = 96; pub(crate) const XML_REF_BYTES: usize = 8; /// The estimated bytes of a namespace an XML node holds. pub(crate) const XML_NS_BYTES: usize = 48; +/// The estimated bytes of the measurement a `UnitValue` object holds. +pub(crate) const UNIT_VALUE_BYTES: usize = 32; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; @@ -680,6 +685,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::UnitValue(_) => extra = UNIT_VALUE_BYTES, _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..315788b7c7 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -253,6 +253,9 @@ pub(crate) struct Interp { pub(crate) install_error: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, + /// `UnitValue`, once a host has added it ([`crate::Realm::add_unit_values`]). Until then the + /// operators take no object as a measurement. + pub(crate) unit_values: Option, /// The clock and time zone `Date` reads. pub(crate) date_host: crate::date_builtins::DateHost, /// The bytes native code holds outside the heap's cells through [`HeldBytes`]. @@ -518,6 +521,7 @@ impl Interp { held_bytes: 0, install_error: None, files: None, + unit_values: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), flattened: std::cell::Cell::new(0), @@ -774,6 +778,7 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.objects.extend(self.unit_values.iter().map(crate::unit_value::Classes::object)); roots.envs.push(self.global_env); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. @@ -2873,6 +2878,11 @@ impl Interp { fn op_unary(&mut self, op: Op) -> JsResult<()> { let v = self.peek(0)?; + if self.unit_values.is_some() + && let Some(r) = crate::unit_value::unary(self, op, &v)? + { + return self.replace(1, r); + } let r = match op { Op::Neg => Value::Number(-self.to_number(&v)?), Op::Plus | Op::ToNumber => Value::Number(self.to_number(&v)?), @@ -2892,6 +2902,12 @@ impl Interp { } pub(crate) fn binary(&mut self, op: BinaryOp, a: &Value, b: &Value) -> JsResult { + if self.unit_values.is_some() + && (matches!(a, Value::Object(_)) || matches!(b, Value::Object(_))) + && let Some(r) = crate::unit_value::binary(self, op, a, b)? + { + return Ok(r); + } let num = |interp: &mut Self, f: fn(f64, f64) -> f64| -> JsResult { let x = interp.to_number(a)?; let y = interp.to_number(b)?; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..c0acf50e37 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -69,6 +69,7 @@ mod regexp_builtins; mod regexp_vm; mod string_builtins; mod token; +mod unit_value; mod value; mod xml; mod xml_builtins; @@ -213,4 +214,6 @@ mod tests; #[cfg(test)] mod text_tests; #[cfg(test)] +mod unit_value_tests; +#[cfg(test)] mod xml_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index d675e82ec7..52ddea823b 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -529,6 +529,17 @@ impl Realm { } } + /// Adds the global constructor `UnitValue`, measurements with a magnitude and a unit, and has + /// the arithmetic, comparison and unary operators calculate with its objects + /// ([`crate::unit_value`]). A realm without it keeps the standard operators. A second call + /// changes nothing. + pub fn add_unit_values(&mut self) -> Result<(), RunError> { + match crate::unit_value::install(&mut self.interp) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Defines the global function `name`, whose arguments arrive converted as `args` says /// ([`crate::HostItem::Converted`]). Unlike a host object, a script may replace or delete it, as /// it may a built-in function. diff --git a/crates/js/src/unit_value.rs b/crates/js/src/unit_value.rs new file mode 100644 index 0000000000..03a33ab3e6 --- /dev/null +++ b/crates/js/src/unit_value.rs @@ -0,0 +1,522 @@ +//! `UnitValue`, the measurement class the help page +//! +//! describes, added to a realm by [`crate::Realm::add_unit_values`]. +//! +//! An object holds a magnitude, a unit and the base that pixels and percentages convert through. +//! The length units convert through exact ratios to the inch; a pixel is one base and 100% is one +//! base. The base is an absolute length greater than 0, copied into each new object from +//! `UnitValue.baseUnit` (1 point, which is 1/72 inch, until a script sets it), and an object's own `baseUnit` may +//! replace it. A unit the table does not list, text that is not a number followed by a unit, and a +//! magnitude that is not finite make an invalid object: its `type` is `?`, its `value` 0, and it +//! cannot be converted or calculated with. +//! +//! In a realm with `UnitValue`, the operators take its objects as follows. `+`, `-`, `*`, `/` and +//! `%` with a `UnitValue` and a number calculate with the magnitude and give a new `UnitValue` in +//! its unit; with two, the right one is converted to the left one's unit first and the result is in +//! the left one's unit. `<`, `<=`, `==` and `!=` compare magnitudes the same way, `>` is the +//! negation of `<=` and `>=` the negation of `<`. Unary `+` and `-` give the magnitude and its +//! negation, `~` inverts the magnitude's 32-bit integer, and `!` is true for a magnitude that is not +//! 0. Any other operand, and every other operator, works as in standard JavaScript, as do all +//! operators in a realm without `UnitValue`. A calculation whose result is not finite (a division +//! by 0 included), a comparison with a number that is not finite, and a conversion of an invalid +//! object or any of these operators applied to one throw a `RangeError`; a unit the table does not list throws an +//! `Error`. + +use crate::ast::BinaryOp; +use crate::builtins::{arg, constructor, method, native}; +use crate::bytecode::Op; +use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, Prop, UNIT_VALUE_BYTES, key}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::{Value, is_str_space, number_to_str, string_to_number, to_int32}; + +/// The units of the table, in its order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Unit { + In, + Ft, + Yd, + Mi, + Mm, + Cm, + M, + Km, + Pt, + Pc, + Tpt, + Tpc, + Ci, + Px, + Percent, +} + +/// Each unit with its abbreviation, singular and plural names, and its length in inches as a ratio +/// (0 for the units that convert through the base). +const UNITS: [(Unit, &str, &str, &str, u64, u64); 15] = [ + (Unit::In, "in", "inch", "inches", 1, 1), + (Unit::Ft, "ft", "foot", "feet", 12, 1), + (Unit::Yd, "yd", "yard", "yards", 36, 1), + (Unit::Mi, "mi", "mile", "miles", 63_360, 1), + (Unit::Mm, "mm", "millimeter", "millimeters", 5, 127), + (Unit::Cm, "cm", "centimeter", "centimeters", 50, 127), + (Unit::M, "m", "meter", "meters", 5_000, 127), + (Unit::Km, "km", "kilometer", "kilometers", 5_000_000, 127), + (Unit::Pt, "pt", "point", "points", 1, 72), + (Unit::Pc, "pc", "pica", "picas", 1, 6), + (Unit::Tpt, "tpt", "traditional point", "traditional points", 100, 7_227), + (Unit::Tpc, "tpc", "traditional pica", "traditional picas", 1_200, 7_227), + (Unit::Ci, "ci", "cicero", "ciceros", 111, 625), + (Unit::Px, "px", "pixel", "pixels", 0, 0), + (Unit::Percent, "%", "percent", "percent", 0, 0), +]; + +/// The longest unit name in the table, in code units. +const LONGEST_NAME: usize = 18; + +/// The longest text the constructor reads as a magnitude and a unit, in code units; longer text +/// makes an invalid object without being read. +const LONGEST_TEXT: usize = 64; + +impl Unit { + fn row(self) -> Option<&'static (Unit, &'static str, &'static str, &'static str, u64, u64)> { + UNITS.iter().find(|row| row.0 == self) + } + + fn abbreviation(self) -> &'static str { + self.row().map_or("?", |row| row.1) + } + + /// The unit's length in inches as a ratio, `None` for pixels and percentages. + fn inches(self) -> Option<(u64, u64)> { + let &(_, _, _, _, n, d) = self.row()?; + (n != 0).then_some((n, d)) + } + + /// The unit with this abbreviation, singular or plural name. + fn named(units: &[u16]) -> Option { + if units.is_empty() || units.len() > LONGEST_NAME { + return None; + } + let name = String::from_utf16(units).ok()?; + UNITS.iter().find(|(_, a, s, p, _, _)| name == *a || name == *s || name == *p).map(|row| row.0) + } +} + +/// The length that pixels and percentages convert through: a finite magnitude greater than 0 in a +/// unit with a length. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Base { + value: f64, + unit: Unit, +} + +/// 1/72 inch, kept as 1 point so that conversions through it are exact. +const DEFAULT_BASE: Base = Base { value: 1.0, unit: Unit::Pt }; + +/// What a `UnitValue` object holds. `unit` is `None` for an invalid object. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Measure { + value: f64, + unit: Option, + base: Base, +} + +/// The prototype of `UnitValue` objects and the current `UnitValue.baseUnit`, kept by the realm. +#[derive(Clone, Debug)] +pub(crate) struct Classes { + proto: ObjId, + base: Base, +} + +impl Classes { + /// The object a collection keeps. + pub(crate) fn object(&self) -> ObjId { + self.proto + } +} + +fn greatest_common_divisor(mut a: u64, mut b: u64) -> u64 { + while b != 0 { + (a, b) = (b, a % b); + } + a +} + +/// `value` in unit `from`, given in unit `to`; both have a length. +fn between(value: f64, from: (u64, u64), to: (u64, u64)) -> f64 { + // The products stay below 2^53, so the ratio's terms are exact. + let (n, d) = (from.0 * to.1, from.1 * to.0); + let g = greatest_common_divisor(n, d).max(1); + #[allow(clippy::cast_precision_loss)] + let (n, d) = ((n / g) as f64, (d / g) as f64); + let scaled = value * n; + // A large value is divided first, so a result that is finite does not overflow on the way. + if scaled.is_finite() { scaled / d } else { value / d * n } +} + +fn invalid(i: &mut Interp, what: &str) -> Abrupt { + i.throw(ErrorType::Range, &format!("{what}: an invalid UnitValue cannot be converted or calculated with")) +} + +fn finite_value(i: &mut Interp, what: &str) -> Abrupt { + i.throw(ErrorType::Range, &format!("{what}: the value must be a finite number")) +} + +fn not_finite(i: &mut Interp, what: &str) -> Abrupt { + i.throw(ErrorType::Range, &format!("{what}: the result is not a finite number")) +} + +/// The magnitude of `m` in unit `to`, through `m`'s own base. +fn convert(i: &mut Interp, m: &Measure, to: Unit, what: &str) -> JsResult { + let Some(from) = m.unit else { + return Err(invalid(i, what)); + }; + let base = m.base; + let base_inches = base.unit.inches().unwrap_or((1, 1)); + let r = match (from, to) { + (a, b) if a == b => m.value, + (Unit::Px, Unit::Percent) => m.value * 100.0, + (Unit::Percent, Unit::Px) => m.value / 100.0, + (Unit::Px | Unit::Percent, _) => { + let to = to.inches().unwrap_or((1, 1)); + let bases = if from == Unit::Px { m.value } else { m.value / 100.0 }; + // A large base is applied after the unit ratio, so a result that is finite does not + // overflow on the way. + let scaled = bases * base.value; + if scaled.is_finite() { between(scaled, base_inches, to) } else { between(bases, base_inches, to) * base.value } + } + (_, Unit::Px | Unit::Percent) => { + let from = from.inches().unwrap_or((1, 1)); + let lengths = between(m.value, from, base_inches); + let bases = if lengths.is_finite() { lengths / base.value } else { between(m.value / base.value, from, base_inches) }; + if to == Unit::Px { bases } else { bases * 100.0 } + } + (_, _) => between(m.value, from.inches().unwrap_or((1, 1)), to.inches().unwrap_or((1, 1))), + }; + if r.is_finite() { Ok(r) } else { Err(not_finite(i, what)) } +} + +/// The measure of `v` when it is a `UnitValue` object. +pub(crate) fn measure(i: &Interp, v: &Value) -> Option { + let o = v.as_object()?; + match &i.heap.object(o)?.class { + Class::UnitValue(m) => Some(**m), + _ => None, + } +} + +fn this_measure(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Measure)> { + if let (Some(o), Some(m)) = (this.as_object(), measure(i, this)) { + return Ok((o, m)); + } + Err(i.type_error(&format!("{what}: the object is not a UnitValue"))) +} + +fn store(i: &mut Interp, o: ObjId, m: Measure) { + if let Some(obj) = i.heap.object_mut(o) + && let Class::UnitValue(slot) = &mut obj.class + { + **slot = m; + } +} + +fn classes(i: &Interp) -> JsResult { + i.unit_values.clone().ok_or_else(|| Abrupt::Internal("UnitValue is not installed".into())) +} + +/// A new `UnitValue` object holding `m`. +fn make(i: &mut Interp, m: Measure) -> JsResult { + let proto = classes(i)?.proto; + i.reserve_heap(OBJECT_BYTES + UNIT_VALUE_BYTES)?; + i.heap.bytes = i.heap.bytes.saturating_add(UNIT_VALUE_BYTES); + Ok(Value::Object(i.heap.alloc_object(Object::new(Class::UnitValue(Box::new(m)), Some(proto))))) +} + +/// The unit `v` names, or an `Error` naming `what`. +fn unit_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let s = i.to_str(v)?; + let unit = if s.len() > LONGEST_NAME { None } else { Unit::named(&s.flat()) }; + unit.ok_or_else(|| i.throw(ErrorType::Error, &format!("{what}: the unit is not known"))) +} + +/// A magnitude followed by a unit, with spaces around and between them allowed: `12 pt`, +/// `-1.5e2 traditional points`, `10%`. +fn parse_text(units: &[u16]) -> Option<(f64, Unit)> { + let start = units.iter().position(|&u| !is_str_space(u)).unwrap_or(units.len()); + let end = units.iter().rposition(|&u| !is_str_space(u)).map_or(start, |e| e + 1); + let text = units.get(start..end)?; + let digit = |u: u16| (u16::from(b'0')..=u16::from(b'9')).contains(&u); + let at = |k: usize| text.get(k).copied().unwrap_or(0); + let mut k = 0; + if at(k) == u16::from(b'+') || at(k) == u16::from(b'-') { + k += 1; + } + let mut digits = 0; + while digit(at(k)) { + k += 1; + digits += 1; + } + if at(k) == u16::from(b'.') { + k += 1; + while digit(at(k)) { + k += 1; + digits += 1; + } + } + if digits == 0 { + return None; + } + if at(k) == u16::from(b'e') || at(k) == u16::from(b'E') { + let mut e = k + 1; + if at(e) == u16::from(b'+') || at(e) == u16::from(b'-') { + e += 1; + } + if digit(at(e)) { + while digit(at(e)) { + e += 1; + } + k = e; + } + } + let (number, rest) = text.split_at_checked(k)?; + let value = string_to_number(number); + let u = rest.iter().position(|&u| !is_str_space(u)).unwrap_or(rest.len()); + let unit = Unit::named(rest.get(u..)?)?; + value.is_finite().then_some((value, unit)) +} + +/// `new UnitValue(value, unit)`, `new UnitValue("value unit")`, `new UnitValue(unitValue)` and the +/// same without `new`. +fn unit_value_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let base = classes(i)?.base; + let bad = Measure { value: 0.0, unit: None, base }; + let first = arg(args, 0); + let m = if args.len() >= 2 { + let value = i.to_number(&first)?; + let s = i.to_str(&arg(args, 1))?; + let unit = if s.len() > LONGEST_NAME { None } else { Unit::named(&s.flat()) }; + match unit { + Some(unit) if value.is_finite() => Measure { value, unit: Some(unit), base }, + _ => bad, + } + } else if let Some(m) = measure(i, &first) { + m + } else if matches!(first, Value::Undefined | Value::Number(_)) { + bad + } else { + let s = i.to_str(&first)?; + match if s.len() > LONGEST_TEXT { None } else { parse_text(&s.flat()) } { + Some((value, unit)) => Measure { value, unit: Some(unit), base }, + None => bad, + } + }; + make(i, m) +} + +fn get_value(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, m) = this_measure(i, &this, "UnitValue.value")?; + Ok(Value::Number(m.value)) +} + +fn set_value(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = this_measure(i, &this, "UnitValue.value")?; + let value = i.to_number(&arg(args, 0))?; + if !value.is_finite() { + return Err(finite_value(i, "UnitValue.value")); + } + // The conversion may have run script code that changed the object, so it is read again. + let (_, mut m) = this_measure(i, &this, "UnitValue.value")?; + m.value = value; + store(i, o, m); + Ok(Value::Undefined) +} + +fn get_type(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, m) = this_measure(i, &this, "UnitValue.type")?; + Ok(Value::str(m.unit.map_or("?", Unit::abbreviation))) +} + +fn set_type(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = this_measure(i, &this, "UnitValue.type")?; + let unit = unit_arg(i, &arg(args, 0), "UnitValue.type")?; + let (_, mut m) = this_measure(i, &this, "UnitValue.type")?; + m.unit = Some(unit); + store(i, o, m); + Ok(Value::Undefined) +} + +/// The base `v` gives: `null` gives the default, and any other value must be a valid `UnitValue` +/// with a length greater than 0. +fn base_arg(i: &mut Interp, v: &Value, null: Base, what: &str) -> JsResult { + if matches!(v, Value::Null) { + return Ok(null); + } + match measure(i, v) { + Some(Measure { value, unit: Some(unit), .. }) if unit.inches().is_some() && value.is_finite() && value > 0.0 => Ok(Base { value, unit }), + _ => Err(i.throw(ErrorType::Range, &format!("{what}: the base must be null or a UnitValue of a length greater than 0"))), + } +} + +fn base_object(i: &mut Interp, base: Base) -> JsResult { + let class = classes(i)?.base; + make(i, Measure { value: base.value, unit: Some(base.unit), base: class }) +} + +fn get_base(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, m) = this_measure(i, &this, "UnitValue.baseUnit")?; + base_object(i, m.base) +} + +fn set_base(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, mut m) = this_measure(i, &this, "UnitValue.baseUnit")?; + let class = classes(i)?.base; + m.base = base_arg(i, &arg(args, 0), class, "UnitValue.baseUnit")?; + store(i, o, m); + Ok(Value::Undefined) +} + +fn get_class_base(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + let base = classes(i)?.base; + base_object(i, base) +} + +fn set_class_base(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let base = base_arg(i, &arg(args, 0), DEFAULT_BASE, "UnitValue.baseUnit")?; + if let Some(c) = i.unit_values.as_mut() { + c.base = base; + } + Ok(Value::Undefined) +} + +/// `unitValue.as(unit)`: the magnitude in `unit`, leaving the object as it is. +fn unit_as(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_measure(i, &this, "UnitValue.as")?; + let unit = unit_arg(i, &arg(args, 0), "UnitValue.as")?; + let (_, m) = this_measure(i, &this, "UnitValue.as")?; + convert(i, &m, unit, "UnitValue.as").map(Value::Number) +} + +/// `unitValue.convert(unit)`: changes the object to `unit` and gives `true`. A failure throws and +/// leaves the object as it was. +fn unit_convert(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_measure(i, &this, "UnitValue.convert")?; + let unit = unit_arg(i, &arg(args, 0), "UnitValue.convert")?; + let (o, mut m) = this_measure(i, &this, "UnitValue.convert")?; + m.value = convert(i, &m, unit, "UnitValue.convert")?; + m.unit = Some(unit); + store(i, o, m); + Ok(Value::Bool(true)) +} + +/// `unitValue.toString()`: the magnitude and the abbreviation, `12 pt`; an invalid object gives +/// `UnitValue 0.00000`. +fn unit_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, m) = this_measure(i, &this, "UnitValue.toString")?; + Ok(Value::str(&match m.unit { + Some(unit) => format!("{} {}", number_to_str(m.value).to_rust_string(), unit.abbreviation()), + None => format!("UnitValue {:.5}", m.value), + })) +} + +/// Defines the accessor `name` on `on`, not enumerable. +fn accessor(i: &mut Interp, on: ObjId, name: &'static str, get: NativeFn, set: NativeFn) -> JsResult<()> { + let g = native(i, name, get, 0, NativeKind::Plain, false)?; + i.rooted(&[Value::Object(g)], |i| { + let s = native(i, name, set, 1, NativeKind::Plain, false)?; + i.define(on, key(name), Prop::Accessor { get: Some(g), set: Some(s), flags: CONFIGURABLE }) + }) +} + +/// Adds the global constructor `UnitValue` ([`crate::Realm::add_unit_values`]). A second call +/// changes nothing. +pub(crate) fn install(i: &mut Interp) -> JsResult<()> { + if i.unit_values.is_some() { + return Ok(()); + } + let object_proto = i.intrinsics.object_proto; + i.reserve_heap(OBJECT_BYTES)?; + let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.unit_values = Some(Classes { proto, base: DEFAULT_BASE }); + let ctor = native(i, "UnitValue", unit_value_ctor, 2, NativeKind::Plain, true)?; + constructor(i, "UnitValue", ctor, proto)?; + accessor(i, ctor, "baseUnit", get_class_base, set_class_base)?; + accessor(i, proto, "value", get_value, set_value)?; + accessor(i, proto, "type", get_type, set_type)?; + accessor(i, proto, "baseUnit", get_base, set_base)?; + method(i, proto, "as", unit_as, 1)?; + method(i, proto, "convert", unit_convert, 1)?; + method(i, proto, "toString", unit_to_string, 0) +} + +/// Unary `op` on `v` when `v` is a `UnitValue`; `None` otherwise. +pub(crate) fn unary(i: &mut Interp, op: Op, v: &Value) -> JsResult> { + let Some(m) = measure(i, v) else { return Ok(None) }; + if !matches!(op, Op::Neg | Op::Plus | Op::BitNot | Op::Not) { + return Ok(None); + } + if m.unit.is_none() { + return Err(invalid(i, "UnitValue")); + } + Ok(Some(match op { + Op::Neg => Value::Number(-m.value), + Op::Plus => Value::Number(m.value), + Op::BitNot => Value::Number(f64::from(!to_int32(m.value))), + _ => Value::Bool(m.value != 0.0), + })) +} + +/// Binary `op` on `a` and `b` when one is a `UnitValue` and the other a number or a `UnitValue`, +/// for the arithmetic and comparison operators; `None` otherwise. +pub(crate) fn binary(i: &mut Interp, op: BinaryOp, a: &Value, b: &Value) -> JsResult> { + let arithmetic = matches!(op, BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod); + let comparison = matches!(op, BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq | BinaryOp::Eq | BinaryOp::NotEq); + if !arithmetic && !comparison { + return Ok(None); + } + let what = "UnitValue"; + let (x, y, owner) = match (measure(i, a), measure(i, b), a, b) { + (Some(l), Some(r), _, _) => { + let Some(unit) = l.unit else { + return Err(invalid(i, what)); + }; + let y = convert(i, &r, unit, what)?; + (l.value, y, l) + } + (Some(l), None, _, Value::Number(n)) => (l.value, *n, l), + (None, Some(r), Value::Number(n), _) => (*n, r.value, r), + (l, r, _, _) => { + if l.or(r).is_some_and(|m| m.unit.is_none()) { + return Err(invalid(i, what)); + } + return Ok(None); + } + }; + if owner.unit.is_none() { + return Err(invalid(i, what)); + } + if comparison { + if !x.is_finite() || !y.is_finite() { + return Err(finite_value(i, what)); + } + // Without NaN, `x > y` is the negation of `x <= y` and `x >= y` the negation of `x < y`. + return Ok(Some(Value::Bool(match op { + BinaryOp::Lt => x < y, + BinaryOp::LtEq => x <= y, + BinaryOp::Gt => x > y, + BinaryOp::GtEq => x >= y, + BinaryOp::Eq => x == y, + _ => x != y, + }))); + } + // A division by 0 gives an infinite result or NaN, which is refused below. + let r = match op { + BinaryOp::Add => x + y, + BinaryOp::Sub => x - y, + BinaryOp::Mul => x * y, + BinaryOp::Div => x / y, + _ => x % y, + }; + if !r.is_finite() { + return Err(not_finite(i, what)); + } + make(i, Measure { value: r, ..owner }).map(Some) +} diff --git a/crates/js/src/unit_value_tests.rs b/crates/js/src/unit_value_tests.rs new file mode 100644 index 0000000000..6e4f2ee33e --- /dev/null +++ b/crates/js/src/unit_value_tests.rs @@ -0,0 +1,359 @@ +//! `UnitValue` and the operators in a realm that has it. + +use super::*; + +fn realm() -> Realm { + let mut r = Realm::new(); + r.add_unit_values().unwrap(); + r +} + +fn number(r: &mut Realm, source: &str) -> f64 { + match r.run(source) { + Ok(JsValue::Number(n)) => n, + other => panic!("{source}: {other:?}"), + } +} + +fn text(r: &mut Realm, source: &str) -> String { + match r.run(source) { + Ok(JsValue::String(s)) => s, + other => panic!("{source}: {other:?}"), + } +} + +fn boolean(r: &mut Realm, source: &str) -> bool { + match r.run(source) { + Ok(JsValue::Bool(b)) => b, + other => panic!("{source}: {other:?}"), + } +} + +/// The name of the error `statement` throws, or `none`. +fn error_name(r: &mut Realm, statement: &str) -> String { + text(r, &format!("(function () {{ try {{ {statement}; return 'none'; }} catch (e) {{ return e.name; }} }})()")) +} + +fn close(got: f64, want: f64, what: &str) { + assert!((got - want).abs() <= 1e-12 * want.abs().max(1.0), "{what}: {got} is not {want}"); +} + +/// Each length unit with its length in inches. +const LENGTHS: [(&str, f64); 13] = [ + ("in", 1.0), + ("ft", 12.0), + ("yd", 36.0), + ("mi", 63_360.0), + ("mm", 1.0 / 25.4), + ("cm", 1.0 / 2.54), + ("m", 1.0 / 0.0254), + ("km", 1000.0 / 0.0254), + ("pt", 1.0 / 72.0), + ("pc", 1.0 / 6.0), + ("tpt", 1.0 / 72.27), + ("tpc", 12.0 / 72.27), + ("ci", 12.7872 / 72.0), +]; + +#[test] +fn every_length_unit_converts_to_every_other_and_back() { + let mut r = realm(); + for (from, a) in LENGTHS { + for (to, b) in LENGTHS { + let there = number(&mut r, &format!("UnitValue(3, '{from}').as('{to}')")); + close(there, 3.0 * a / b, &format!("3 {from} in {to}")); + let back = number(&mut r, &format!("UnitValue({there}, '{to}').as('{from}')")); + close(back, 3.0, &format!("3 {from} through {to} and back")); + } + } +} + +#[test] +fn the_table_relations_are_exact() { + let mut r = realm(); + for (source, want) in [ + ("UnitValue(1, 'in').as('pt')", 72.0), + ("UnitValue(1, 'ft').as('in')", 12.0), + ("UnitValue(1, 'yd').as('ft')", 3.0), + ("UnitValue(1, 'mi').as('m')", 1609.344), + ("UnitValue(1, 'm').as('cm')", 100.0), + ("UnitValue(1, 'km').as('m')", 1000.0), + ("UnitValue(10, 'mm').as('cm')", 1.0), + ("UnitValue(2.54, 'cm').as('in')", 1.0), + ("UnitValue(1, 'pc').as('pt')", 12.0), + ("UnitValue(1, 'tpc').as('tpt')", 12.0), + ("UnitValue(72.27, 'tpt').as('in')", 1.0), + ("UnitValue(1, 'ci').as('pt')", 12.7872), + ("UnitValue(1, 'in').as('px')", 72.0), + ] { + assert_eq!(number(&mut r, source), want, "{source}"); + } +} + +#[test] +fn units_are_named_by_abbreviation_singular_or_plural() { + let mut r = realm(); + for (name, abbreviation) in [ + ("inch", "in"), + ("inches", "in"), + ("feet", "ft"), + ("millimeter", "mm"), + ("centimeters", "cm"), + ("traditional point", "tpt"), + ("traditional picas", "tpc"), + ("ciceros", "ci"), + ("pixel", "px"), + ("percent", "%"), + ] { + assert_eq!(text(&mut r, &format!("UnitValue(1, '{name}').type")), abbreviation, "{name}"); + assert_eq!(text(&mut r, &format!("UnitValue('2 {name}').type")), abbreviation, "2 {name}"); + } +} + +#[test] +fn the_constructor_takes_a_number_and_unit_text_or_another_unit_value() { + let mut r = realm(); + assert_eq!(text(&mut r, "String(new UnitValue(12, 'pt'))"), "12 pt"); + assert_eq!(text(&mut r, "String(UnitValue('12 cm'))"), "12 cm"); + assert_eq!(text(&mut r, "String(UnitValue(' -1.5e1 centimeters '))"), "-15 cm"); + assert_eq!(text(&mut r, "String(UnitValue('10%'))"), "10 %"); + assert_eq!(text(&mut r, "String(UnitValue('12', 'in'))"), "12 in"); + assert!(boolean(&mut r, "UnitValue(1, 'in') instanceof UnitValue")); + assert_eq!(text(&mut r, "Object.prototype.toString.call(UnitValue(1, 'in'))"), "[object UnitValue]"); + let copy = "var a = UnitValue(5, 'px'); a.baseUnit = UnitValue(1, 'mm'); var b = UnitValue(a); a.value = 1; \ + [a === b, b.value, b.type, b.as('mm')].join()"; + assert_eq!(text(&mut r, copy), "false,5,px,5", "a copy is a new object with the same value, unit and base"); +} + +#[test] +fn an_unknown_unit_or_text_makes_an_invalid_unit_value() { + let mut r = realm(); + for source in [ + "UnitValue(12, 'furlong')", + "UnitValue('12')", + "UnitValue('pt')", + "UnitValue('12 pt extra')", + "UnitValue(12)", + "UnitValue()", + "UnitValue(NaN, 'pt')", + "UnitValue(Infinity, 'pt')", + "UnitValue(12, 'PT')", + ] { + assert_eq!(text(&mut r, &format!("var u = {source}; u.type + ' ' + u.value")), "? 0", "{source}"); + assert_eq!(text(&mut r, &format!("String({source})")), "UnitValue 0.00000", "{source}"); + } + for statement in [ + "UnitValue(1, 'zz').as('pt')", + "UnitValue(1, 'zz').convert('pt')", + "UnitValue(1, 'zz') + 1", + "UnitValue(1, 'in') + UnitValue(1, 'zz')", + "UnitValue('bad') == 0", + "1 > UnitValue('bad')", + "+UnitValue('bad')", + "-UnitValue('bad')", + "~UnitValue('bad')", + "!UnitValue('bad')", + "UnitValue('bad') + 'x'", + "'x' < UnitValue('bad')", + "UnitValue('bad') == null", + ] { + assert_eq!(error_name(&mut r, statement), "RangeError", "{statement}"); + } +} + +#[test] +fn as_leaves_the_object_and_convert_changes_it() { + let mut r = realm(); + assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); [u.as('pt'), String(u)].join()"), "72,1 in"); + assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); [u.convert('pt'), String(u)].join()"), "true,72 pt"); + assert_eq!(error_name(&mut r, "UnitValue(1, 'in').as('furlong')"), "Error"); + assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); try { u.convert('furlong'); } catch (e) {} String(u)"), "1 in"); + assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); try { u.type = 'furlong'; } catch (e) {} String(u)"), "1 in"); + assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); u.type = 'points'; u.value = 3; String(u)"), "3 pt"); + assert_eq!(error_name(&mut r, "UnitValue(1, 'in').value = NaN"), "RangeError"); + assert_eq!(error_name(&mut r, "UnitValue.prototype.as.call({}, 'pt')"), "TypeError"); +} + +#[test] +fn pixels_and_percentages_convert_through_the_base() { + let mut r = realm(); + assert_eq!(number(&mut r, "UnitValue(72, 'px').as('in')"), 1.0); + assert_eq!(number(&mut r, "var p = UnitValue(10, 'px'); p.baseUnit = UnitValue(0.75, 'pt'); p.as('pt')"), 7.5); + close(number(&mut r, "var p = UnitValue(10, 'px'); p.baseUnit = UnitValue(1/96, 'in'); p.as('in')"), 10.0 / 96.0, "10 px at 96 per inch"); + assert_eq!(text(&mut r, "String(UnitValue.baseUnit)"), "1 pt"); + assert_eq!(number(&mut r, "var p = UnitValue(40, '%'); p.baseUnit = UnitValue(10, 'ft'); p.as('ft')"), 4.0); + assert_eq!(number(&mut r, "var m = UnitValue(10, 'm'); m.baseUnit = UnitValue(1, 'km'); m.as('%')"), 1.0); + assert_eq!(number(&mut r, "var p = UnitValue(3, 'px'); p.baseUnit = UnitValue(2, 'pt'); p.as('%')"), 300.0); + assert_eq!(number(&mut r, "var p = UnitValue(50, '%'); p.as('px')"), 0.5); + let class = "var before = UnitValue(1, 'in'); UnitValue.baseUnit = UnitValue(0.5, 'pt'); \ + var after = UnitValue(1, 'in'); var r = [before.as('px'), after.as('px'), String(UnitValue.baseUnit.type)]; \ + UnitValue.baseUnit = null; r.push(UnitValue(1, 'in').as('px')); r.join()"; + assert_eq!(text(&mut r, class), "72,144,pt,72", "the class base applies to objects made after it is set, and null restores it"); + assert_eq!(number(&mut r, "var p = UnitValue(1, 'in'); p.baseUnit = UnitValue(1, 'cm'); p.baseUnit = null; p.as('px')"), 72.0); + let large = "var p = UnitValue(100, '%'); p.baseUnit = UnitValue(1e308, 'pt'); var q = UnitValue(2, 'px'); \ + q.baseUnit = UnitValue(1e308, 'pt'); var l = UnitValue(1e308, 'km'); l.baseUnit = UnitValue(1e300, 'pt'); \ + [p.as('pt'), q.as('in'), l.as('px')].join()"; + let got: Vec = text(&mut r, large).split(',').map(|s| s.parse().unwrap()).collect(); + close(got[0], 1e308, "100% of a large base"); + close(got[1], 1e308 / 72.0 * 2.0, "2 px of a large base in inches"); + close(got[2], 1e308 / 1e300 * 1000.0 * 5000.0 / 127.0 * 72.0, "a large length in pixels of a large base"); +} + +#[test] +fn a_base_must_be_a_length_greater_than_zero() { + let mut r = realm(); + for base in ["UnitValue(0, 'pt')", "UnitValue(-1, 'pt')", "UnitValue(1, 'px')", "UnitValue(1, '%')", "UnitValue(1, 'zz')"] { + assert_eq!(error_name(&mut r, &format!("UnitValue.baseUnit = {base}")), "RangeError", "{base}"); + assert_eq!(error_name(&mut r, &format!("UnitValue(1, 'px').baseUnit = {base}")), "RangeError", "{base}"); + } + assert_eq!(error_name(&mut r, "UnitValue.baseUnit = 5"), "RangeError"); + assert_eq!(error_name(&mut r, "UnitValue(1, 'px').baseUnit = '1 pt'"), "RangeError"); + assert_eq!(number(&mut r, "UnitValue(1, 'in').as('px')"), 72.0, "a refused base leaves the class base as it was"); +} + +#[test] +fn arithmetic_gives_a_new_unit_value_in_the_left_unit() { + let mut r = realm(); + for (source, want) in [ + ("UnitValue(1, 'm') + UnitValue(10, 'cm')", "1.1 m"), + ("UnitValue(10, 'cm') + UnitValue(1, 'm')", "110 cm"), + ("UnitValue(10, 'cm') * 20", "200 cm"), + ("20 * UnitValue(10, 'cm')", "200 cm"), + ("10 - UnitValue(3, 'pt')", "7 pt"), + ("UnitValue(10, 'pt') - 3", "7 pt"), + ("20 / UnitValue(4, 'pt')", "5 pt"), + ("UnitValue(20, 'pt') / 4", "5 pt"), + ("UnitValue(7, 'pt') % 4", "3 pt"), + ("UnitValue(1, 'in') - UnitValue(36, 'pt')", "0.5 in"), + ] { + assert_eq!(text(&mut r, &format!("String({source})")), want, "{source}"); + } + assert_eq!(text(&mut r, "var u = UnitValue(1, 'pt'); u += 2; String(u)"), "3 pt", "compound assignment uses the operator"); + assert_eq!(text(&mut r, "var u = UnitValue(1, 'in'); var v = u + 1; String(u)"), "1 in", "the operands do not change"); + assert_eq!(text(&mut r, "var u = UnitValue(2, 'px'); u.baseUnit = UnitValue(1, 'mm'); (u * 3).as('mm') + ''"), "6", "the result keeps the base"); + assert_eq!(text(&mut r, "UnitValue(1, 'pt') + 'x'"), "1 ptx", "a string concatenates as in standard JavaScript"); +} + +#[test] +fn comparisons_use_the_numbers_and_greater_is_the_negation() { + let mut r = realm(); + for (source, want) in [ + ("UnitValue(98, 'cm') < UnitValue(1, 'm')", true), + ("UnitValue(98, 'cm') < 1", false), + ("UnitValue(98, 'cm') == 98", true), + ("98 == UnitValue(98, 'cm')", true), + ("UnitValue(1, 'in') == UnitValue(72, 'pt')", true), + ("UnitValue(1, 'in') != UnitValue(72, 'pt')", false), + ("UnitValue(1, 'in') === UnitValue(72, 'pt')", false), + ("var u = UnitValue(1, 'in'); u === u", true), + ("UnitValue(1, 'in') <= UnitValue(72, 'pt')", true), + ("UnitValue(1, 'in') >= UnitValue(72, 'pt')", true), + ("UnitValue(1, 'in') > UnitValue(72, 'pt')", false), + ("UnitValue(1, 'in') > UnitValue(71, 'pt')", true), + ("UnitValue(1, 'in') >= UnitValue(73, 'pt')", false), + ("2 > UnitValue(1, 'pt')", true), + ("2 >= UnitValue(3, 'pt')", false), + ] { + assert_eq!(boolean(&mut r, source), want, "{source}"); + } + for statement in [ + "UnitValue(1, 'pt') < NaN", + "UnitValue(1, 'pt') > NaN", + "NaN == UnitValue(1, 'pt')", + "UnitValue(1, 'pt') < Infinity", + "UnitValue(1, 'in') < UnitValue(1, 'zz')", + ] { + assert_eq!(error_name(&mut r, statement), "RangeError", "{statement}"); + } +} + +#[test] +fn unary_operators_use_the_number() { + let mut r = realm(); + assert_eq!(text(&mut r, "var u = UnitValue(2.5, 'pt'); [+u, -u, ~u, !u, !UnitValue(0, 'pt'), typeof u].join()"), "2.5,-2.5,-3,true,false,object"); +} + +#[test] +fn results_that_are_not_finite_and_division_by_zero_throw() { + let mut r = realm(); + for statement in [ + "UnitValue(1e308, 'pt') * 10", + "UnitValue(1, 'pt') / 0", + "1 / UnitValue(0, 'pt')", + "UnitValue(1, 'pt') % 0", + "UnitValue(1, 'pt') + NaN", + "UnitValue(1e308, 'mi').as('pt')", + "UnitValue(1, 'pt') + UnitValue(1e308, 'mi')", + ] { + assert_eq!(error_name(&mut r, statement), "RangeError", "{statement}"); + } + assert_eq!(number(&mut r, "UnitValue(1e300, 'pt').as('mi') * 0"), 0.0); + close(number(&mut r, "UnitValue(1e307, 'km').as('mi')"), 1e307 * 1000.0 / 1609.344, "a large value that fits after the division"); +} + +#[test] +fn a_realm_without_unit_values_keeps_the_standard_operators() { + let mut r = Realm::new(); + assert_eq!(text(&mut r, "typeof UnitValue"), "undefined"); + let mut r = realm(); + let plain = "var o = {valueOf: function () { return 4; }}; [o + 1, o * 2, o < 5, o == 4].join()"; + assert_eq!(text(&mut r, plain), "5,8,true,true", "other objects use their valueOf"); + let named = "function P() {} P.prototype['+'] = function () { return 'called'; }; String(new P() + 1)"; + assert_eq!(text(&mut r, named), "[object Object]1", "a method named for an operator is not called"); +} + +#[test] +fn hostile_input_ends_in_an_error_or_a_limit() { + let mut r = realm(); + let long = "var s = 'pt'; for (var i = 0; i < 17; i++) s += s; "; + assert_eq!(text(&mut r, &format!("{long} UnitValue(1, s).type")), "?"); + assert_eq!(text(&mut r, &format!("{long} UnitValue('1 ' + s).type")), "?"); + assert_eq!(error_name(&mut r, &format!("{long} UnitValue(1, 'in').as(s)")), "Error"); + let loop_text = "var o = {toString: function () { return String(UnitValue(o)); }}; UnitValue(o)"; + match r.run(loop_text) { + Err(e) => assert!(matches!(e.kind, RunErrorKind::Limit(_) | RunErrorKind::Thrown), "{e:?}"), + other => panic!("{other:?}"), + } + let value_of = "var o = {valueOf: function () { return UnitValue(1, 'pt') * o; }}; UnitValue(1, 'pt') * o"; + match r.run(value_of) { + Err(e) => assert!(matches!(e.kind, RunErrorKind::Limit(_) | RunErrorKind::Thrown), "{e:?}"), + other => panic!("{other:?}"), + } + assert_eq!(text(&mut r, "String(UnitValue(3, 'pt'))"), "3 pt", "the realm runs on"); +} + +#[test] +fn unit_values_survive_a_collection() { + let mut r = realm(); + r.run("var keep = UnitValue(2, 'in'); for (var i = 0; i < 1000; i++) UnitValue(i, 'pt');").unwrap(); + r.collect_garbage(); + assert_eq!(text(&mut r, "String(keep + UnitValue(72, 'pt')) + ' ' + String(UnitValue(1, 'pc'))"), "3 in 1 pc"); +} + +#[test] +fn each_measurement_counts_toward_the_heap() { + let mut r = realm(); + // The growth from 100 objects to 200, so the script's own code and strings cancel out. + let mut per_hundred = |make: &str| { + let mut grown = |count: usize| { + r.run("var kept = [];").unwrap(); + let before = r.collect_garbage(); + r.run(&format!("for (var i = 0; i < {count}; i++) kept.push({make});")).unwrap(); + r.collect_garbage() - before + }; + grown(200) - grown(100) + }; + // The first runs also leave bindings and names the later ones reuse. + per_hundred("{}"); + let plain = per_hundred("{}"); + let measures = per_hundred("UnitValue(i, 'pt')"); + assert_eq!(measures - plain, 100 * crate::heap::UNIT_VALUE_BYTES); +} + +#[test] +fn a_second_install_changes_nothing() { + let mut r = realm(); + r.run("UnitValue.baseUnit = UnitValue(1, 'mm'); var Kept = UnitValue;").unwrap(); + r.add_unit_values().unwrap(); + assert!(boolean(&mut r, "Kept === UnitValue && UnitValue(1, 'mm').as('px') === 1")); +} diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..2da5bbb538 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2727,6 +2727,27 @@ itself throws a `TypeError`. So does a property that is not writable or not conf would make each of them writable, configurable and extensible again (VectorCraft's own rule). A value deeper than 64 levels, with more than 1,048,576 entries or with text longer than 16,777,216 characters throws a `RangeError`. +`UnitValue` holds a measurement: a number and a unit +(https://extendscript.docsforadobe.dev/extendscript-tools-features/specifying-measurement-values/). Scripts make one +with or without `new`, as `UnitValue(12, 'pt')`, `UnitValue('12 pt')` or `UnitValue(other)` (a copy). The units are +`in`, `ft`, `yd`, `mi`, `mm`, `cm`, `m`, `km`, `pt`, `pc`, `tpt`, `tpc`, `ci`, `px` and `%`, each also written as its +singular or plural name (`inch`, `inches`, `traditional point`); `type` gives the abbreviation. `as(unit)` gives the +number in another unit and `convert(unit)` changes the object to it and returns `true`. A pixel is one `baseUnit` and +100% is one `baseUnit`; new objects take `UnitValue.baseUnit`, which is `1 pt` (1/72 inch) until a script sets it, `null` sets +it back, and an object's own `baseUnit` replaces it for that object. `toString()` gives the number and the abbreviation, +such as `12 pt`. With a `UnitValue` and a number, `+`, `-`, `*`, `/` and `%` calculate with the object's number and +give a new `UnitValue` in its unit; with two, the right one is converted to the left one's unit and the result is in +the left one's unit. `<`, `<=`, `==` and `!=` compare the numbers the same way, `>` is true when `<=` is false and +`>=` when `<` is false, and `===` compares objects as usual. Unary `+` and `-` give the number and its negation, `~` +inverts its 32-bit integer, and `!` is true for a number that is not 0. Other operands, and the other operators, +work as in standard JavaScript. VectorCraft's own rules: an unknown unit, text that is not a number and a unit (or +longer than 64 characters), and a number that is not finite make an object whose `type` is `?` and whose `value` is +0, which prints as `UnitValue 0.00000`; converting it, using it with any of these operators, a result that is not finite (a division +by 0 included) and a comparison with a number that is not finite throw a `RangeError`; an unknown unit given to `as`, `convert` or `type` throws an +`Error` and leaves the object as it was; `value` takes only a finite number; and `baseUnit` takes only `null` or a +length greater than 0 (not pixels or percentages). Two units of length convert through their exact ratio to the inch, +so `UnitValue(1, 'in').as('pt')` is exactly 72. + The run is one transaction. When the script ends, each document it changed gets one undo step named Run Script. A run that changes no document adds no undo step. The journal records each command the run finished, as it records commands run one at a time. A preference the run changed takes the run's value, and a preference changed in the app diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..3d8f84381f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1028,6 +1028,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`. + - Scripts: `UnitValue` measurements ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/specifying-measurement-values/)): the constructor with a number and a unit, with text such as `12 pt`, or with another `UnitValue`; the length units, `px` and `%` by abbreviation, singular or plural; `value`, `type` and `baseUnit` on the class and on each object; `as` and `convert`; and the arithmetic, comparison and unary operators with a number or another `UnitValue`, the right one converted to the left one's unit, with `>` and `>=` as the negations of `<=` and `<`. Realms without `UnitValue` keep the standard operators. VectorCraft's own rules: an invalid object has `type` `?` and value 0, and converting it or using it with these operators, a result that is not finite (a division by 0 included), a comparison with a number that is not finite and a base that is not a length greater than 0 throw. `crates/js/src/unit_value_tests.rs`, `crates/engine/src/tests/script_dollar.rs`. - Scripts: a canceled request stops a run that sleeps in `$.sleep`, waits at a dialog or waits for approval to grow at the run's next slice, before its wake time or an answer, and every document goes back to its state before the run. VectorCraft's own rule. `crates/engine/src/tests/script_dollar.rs`, `crates/engine/src/tests/script_dialogs.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: the Script Console panel's report line reads as `script.console` gives it, `time unavailable` included on a platform without a clock; counts of host calls, dropped lines and cut lines take the singular for one, in each language's own plural forms; and a run that is no longer available still gets its end line (`crates/engine/src/tests/script_console.rs`, `crates/ui-egui/src/panels/tests_script_console.rs`). - Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. From 7e5b421db26f7eb25e5be6b8813f5a7b5610e023 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:25:38 -0800 Subject: [PATCH 073/178] Scripts: UnitValue pixels and percentages use the left object's base With two UnitValues and a left one in px or %, the right one is now converted with the left one's baseUnit, so a 1 px value with a 2 pt base plus 1 in gives 37 px. Conversions keep their intermediate values in range, so a result that is a finite number no longer fails because a step on the way overflows or reaches 0. --- crates/js/src/unit_value.rs | 89 +++++++++++++++++++++++-------- crates/js/src/unit_value_tests.rs | 35 ++++++++++++ docs/mcp.md | 4 +- 3 files changed, 105 insertions(+), 23 deletions(-) diff --git a/crates/js/src/unit_value.rs b/crates/js/src/unit_value.rs index 03a33ab3e6..f971e27b07 100644 --- a/crates/js/src/unit_value.rs +++ b/crates/js/src/unit_value.rs @@ -12,8 +12,8 @@ //! //! In a realm with `UnitValue`, the operators take its objects as follows. `+`, `-`, `*`, `/` and //! `%` with a `UnitValue` and a number calculate with the magnitude and give a new `UnitValue` in -//! its unit; with two, the right one is converted to the left one's unit first and the result is in -//! the left one's unit. `<`, `<=`, `==` and `!=` compare magnitudes the same way, `>` is the +//! its unit; with two, the right one is converted to the left one's unit first, with the left one's +//! base for `px` and `%`, and the result is in the left one's unit. `<`, `<=`, `==` and `!=` compare magnitudes the same way, `>` is the //! negation of `<=` and `>=` the negation of `<`. Unary `+` and `-` give the magnitude and its //! negation, `~` inverts the magnitude's 32-bit integer, and `!` is true for a magnitude that is not //! 0. Any other operand, and every other operator, works as in standard JavaScript, as do all @@ -141,16 +141,45 @@ fn greatest_common_divisor(mut a: u64, mut b: u64) -> u64 { a } -/// `value` in unit `from`, given in unit `to`; both have a length. -fn between(value: f64, from: (u64, u64), to: (u64, u64)) -> f64 { +/// The ratio of a length in unit `from` to the same length in unit `to`, as a reduced fraction. +fn ratio(from: Unit, to: Unit) -> (f64, f64) { + let (from, to) = (from.inches().unwrap_or((1, 1)), to.inches().unwrap_or((1, 1))); // The products stay below 2^53, so the ratio's terms are exact. let (n, d) = (from.0 * to.1, from.1 * to.0); let g = greatest_common_divisor(n, d).max(1); #[allow(clippy::cast_precision_loss)] - let (n, d) = ((n / g) as f64, (d / g) as f64); - let scaled = value * n; - // A large value is divided first, so a result that is finite does not overflow on the way. - if scaled.is_finite() { scaled / d } else { value / d * n } + (((n / g) as f64), ((d / g) as f64)) +} + +/// `x` as a significand in [0.5, 1) and a power of 2; zero, infinities and NaN as themselves. +fn split(x: f64) -> (f64, i32) { + if x == 0.0 || !x.is_finite() { + return (x, 0); + } + let (x, shift) = if x.is_normal() { (x, 0) } else { (x * 2f64.powi(64), -64) }; + let bits = x.to_bits(); + #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] + let exponent = ((bits >> 52) & 0x7ff) as i32 - 1022; + (f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), exponent + shift) +} + +/// The product of `factors` divided by each of `divisors`, in that order. Each step rounds as +/// plain multiplication and division do, but no step overflows or reaches 0 on the way, so only +/// a result outside the range of numbers is infinite or 0. +fn product(factors: &[f64], divisors: &[f64]) -> f64 { + let (mut m, mut e) = (1.0, 0); + for (&x, divide) in factors.iter().map(|x| (x, false)).chain(divisors.iter().map(|x| (x, true))) { + let (xm, xe) = split(x); + let (rm, re) = split(if divide { m / xm } else { m * xm }); + (m, e) = (rm, if divide { e - xe } else { e + xe } + re); + } + while e > 1000 { + (m, e) = (m * 2f64.powi(1000), e - 1000); + } + while e < -1000 { + (m, e) = (m * 2f64.powi(-1000), e + 1000); + } + m * 2f64.powi(e) } fn invalid(i: &mut Interp, what: &str) -> Abrupt { @@ -171,26 +200,22 @@ fn convert(i: &mut Interp, m: &Measure, to: Unit, what: &str) -> JsResult { return Err(invalid(i, what)); }; let base = m.base; - let base_inches = base.unit.inches().unwrap_or((1, 1)); let r = match (from, to) { (a, b) if a == b => m.value, (Unit::Px, Unit::Percent) => m.value * 100.0, (Unit::Percent, Unit::Px) => m.value / 100.0, (Unit::Px | Unit::Percent, _) => { - let to = to.inches().unwrap_or((1, 1)); - let bases = if from == Unit::Px { m.value } else { m.value / 100.0 }; - // A large base is applied after the unit ratio, so a result that is finite does not - // overflow on the way. - let scaled = bases * base.value; - if scaled.is_finite() { between(scaled, base_inches, to) } else { between(bases, base_inches, to) * base.value } + let (n, d) = ratio(base.unit, to); + if from == Unit::Px { product(&[m.value, base.value, n], &[d]) } else { product(&[m.value, base.value, n], &[100.0, d]) } } (_, Unit::Px | Unit::Percent) => { - let from = from.inches().unwrap_or((1, 1)); - let lengths = between(m.value, from, base_inches); - let bases = if lengths.is_finite() { lengths / base.value } else { between(m.value / base.value, from, base_inches) }; - if to == Unit::Px { bases } else { bases * 100.0 } + let (n, d) = ratio(from, base.unit); + if to == Unit::Px { product(&[m.value, n], &[d, base.value]) } else { product(&[m.value, n, 100.0], &[d, base.value]) } + } + (_, _) => { + let (n, d) = ratio(from, to); + product(&[m.value, n], &[d]) } - (_, _) => between(m.value, from.inches().unwrap_or((1, 1)), to.inches().unwrap_or((1, 1))), }; if r.is_finite() { Ok(r) } else { Err(not_finite(i, what)) } } @@ -478,7 +503,29 @@ pub(crate) fn binary(i: &mut Interp, op: BinaryOp, a: &Value, b: &Value) -> JsRe let Some(unit) = l.unit else { return Err(invalid(i, what)); }; - let y = convert(i, &r, unit, what)?; + // Pixels and percentages of the left object are measured with its own base. + let y = match unit { + Unit::Px | Unit::Percent if r.base != l.base || !matches!(r.unit, Some(Unit::Px | Unit::Percent)) => match r.unit { + Some(from @ (Unit::Px | Unit::Percent)) => { + let (n, d) = ratio(r.base.unit, l.base.unit); + let mut factors = vec![r.value, r.base.value, n]; + let mut divisors = vec![d, l.base.value]; + if from == Unit::Percent { + divisors.push(100.0); + } + if unit == Unit::Percent { + factors.push(100.0); + } + let y = product(&factors, &divisors); + if !y.is_finite() { + return Err(not_finite(i, what)); + } + y + } + _ => convert(i, &Measure { base: l.base, ..r }, unit, what)?, + }, + _ => convert(i, &r, unit, what)?, + }; (l.value, y, l) } (Some(l), None, _, Value::Number(n)) => (l.value, *n, l), diff --git a/crates/js/src/unit_value_tests.rs b/crates/js/src/unit_value_tests.rs index 6e4f2ee33e..d7f3a642e8 100644 --- a/crates/js/src/unit_value_tests.rs +++ b/crates/js/src/unit_value_tests.rs @@ -38,6 +38,11 @@ fn close(got: f64, want: f64, what: &str) { assert!((got - want).abs() <= 1e-12 * want.abs().max(1.0), "{what}: {got} is not {want}"); } +/// `got` is within a millionth of `want`, which is not 0, however small `want` is. +fn relative(got: f64, want: f64, what: &str) { + assert!((got / want - 1.0).abs() <= 1e-6, "{what}: {got} is not {want}"); +} + /// Each length unit with its length in inches. const LENGTHS: [(&str, f64); 13] = [ ("in", 1.0), @@ -234,6 +239,36 @@ fn arithmetic_gives_a_new_unit_value_in_the_left_unit() { assert_eq!(text(&mut r, "UnitValue(1, 'pt') + 'x'"), "1 ptx", "a string concatenates as in standard JavaScript"); } +#[test] +fn the_left_objects_base_measures_its_pixels_and_percentages() { + let mut r = realm(); + let pair = "var l = UnitValue(1, 'px'); l.baseUnit = UnitValue(2, 'pt'); var m = UnitValue(1, 'px'); \ + m.baseUnit = UnitValue(4, 'pt'); var p = UnitValue(50, '%'); p.baseUnit = UnitValue(1, 'in');"; + assert_eq!(text(&mut r, &format!("{pair} String(l + UnitValue(1, 'in'))")), "37 px"); + assert_eq!(text(&mut r, &format!("{pair} String(l + m)")), "3 px"); + close(number(&mut r, &format!("{pair} (p + l).value")), 50.0 + 200.0 / 72.0, "2 pt as a percentage of 1 in"); + assert!(boolean(&mut r, &format!("{pair} l < m && m > l && l == UnitValue(2, 'pt')"))); + let large = "var b = UnitValue(0, 'px'); b.baseUnit = UnitValue(1e308, 'pt'); var c = UnitValue(1e300, 'px'); \ + c.baseUnit = UnitValue(1e10, 'pt'); [(b + UnitValue(1e304, 'km')).value, (b + c).value].join()"; + let got: Vec = text(&mut r, large).split(',').map(|s| s.parse().unwrap()).collect(); + close(got[0], 1e304 / 1e308 * 1000.0 * 5000.0 / 127.0 * 72.0, "a large length in pixels of a large base"); + close(got[1], 1e300 / 1e308 * 1e10, "large pixels of one large base in pixels of another"); + let small = "var s = UnitValue(0, 'px'); s.baseUnit = UnitValue(1e-300, 'pt'); var t = UnitValue(1e-200, 'px'); \ + t.baseUnit = UnitValue(1e-200, 'pt'); (s + t).value"; + let units = "var u = UnitValue(0, 'px'); u.baseUnit = UnitValue(1e20, 'pt'); var v = UnitValue(1e308, 'px'); \ + v.baseUnit = UnitValue(1e10, 'km'); (u + v).value"; + close(number(&mut r, units), 1e298 * 1000.0 * 5000.0 / 127.0 * 72.0, "large pixels of a base in a larger unit"); + let apart = "var w = UnitValue(0, 'px'); w.baseUnit = UnitValue(7e-16, 'km'); var x = UnitValue(1e-20, 'px'); \ + x.baseUnit = UnitValue(1e308, 'pt'); (w + x).value"; + close(number(&mut r, apart), 1e288 / (1000.0 * 5000.0 / 127.0 * 72.0) / 7e-16, "bases too far apart for their ratio"); + relative(number(&mut r, small), 1e-100, "small pixels of one small base in pixels of another"); + let tiny = "var y = UnitValue(0, 'px'); y.baseUnit = UnitValue(1e-200, 'km'); var z = UnitValue(1e-320, 'px'); (y + z).value"; + relative(number(&mut r, tiny), 1e-320 * 1e200 / (1000.0 * 5000.0 / 127.0 * 72.0), "a tiny value in pixels of a tiny base"); + let tinier = "var y = UnitValue(0, 'px'); y.baseUnit = UnitValue(1e-320, 'pt'); var z = UnitValue(1e-320, 'px'); \ + z.baseUnit = UnitValue(1e-10, 'pt'); (y + z).value"; + relative(number(&mut r, tinier), 1e-10, "a tiny value of a small base in pixels of a tiny base"); +} + #[test] fn comparisons_use_the_numbers_and_greater_is_the_negation() { let mut r = realm(); diff --git a/docs/mcp.md b/docs/mcp.md index 2da5bbb538..e3721e054f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2736,8 +2736,8 @@ number in another unit and `convert(unit)` changes the object to it and returns 100% is one `baseUnit`; new objects take `UnitValue.baseUnit`, which is `1 pt` (1/72 inch) until a script sets it, `null` sets it back, and an object's own `baseUnit` replaces it for that object. `toString()` gives the number and the abbreviation, such as `12 pt`. With a `UnitValue` and a number, `+`, `-`, `*`, `/` and `%` calculate with the object's number and -give a new `UnitValue` in its unit; with two, the right one is converted to the left one's unit and the result is in -the left one's unit. `<`, `<=`, `==` and `!=` compare the numbers the same way, `>` is true when `<=` is false and +give a new `UnitValue` in its unit; with two, the right one is converted to the left one's unit, with the left one's +`baseUnit` for `px` and `%`, and the result is in the left one's unit. `<`, `<=`, `==` and `!=` compare the numbers the same way, `>` is true when `<=` is false and `>=` when `<` is false, and `===` compares objects as usual. Unary `+` and `-` give the number and its negation, `~` inverts its 32-bit integer, and `!` is true for a number that is not 0. Other operands, and the other operators, work as in standard JavaScript. VectorCraft's own rules: an unknown unit, text that is not a number and a unit (or From 7d3094afe6b42f7b0d538966b9a9c0834fabcb01 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:43:20 -0800 Subject: [PATCH 074/178] Scripts: .js scripts run let, const, arrows, templates, default and rest parameters and spread vectorcraft-js gains Options::es2015, which reads and runs these ECMAScript 2015 forms: let and const with block scope and their temporal dead zone, a new let binding for each loop iteration, function declarations scoped to their block (with the Annex B.3.3 variable outside strict mode code), arrow functions, template literals and tagged templates, default and rest parameters, and spread in array literals, calls and new. Spread reads arrays, strings by code point and objects with a length, by index, and throws a TypeError for anything else until iterators are added. Eval code outside strict mode code cannot declare a var that clashes with a let or const around it, or with a parameter inside a default value. Spread, template objects and the new scopes take fuel and count against the heap limit, and nested arrows and templates count against the depth limit. script.run sets the option for a .js file; eval, Function, #include files, $.evalFile and a kept #targetengine read code the way the running script does. A .jsx file and a source string stay ES5.1. The test262 runner gains an ES2015 subset run, read without and with the option. docs/mcp.md and docs/target-app-parity.md describe the new forms. --- crates/engine/src/script/include.rs | 17 +- crates/engine/src/script/mod.rs | 9 +- crates/engine/src/tests/script_run.rs | 34 ++ crates/js/src/ast.rs | 57 +++ crates/js/src/builtins.rs | 2 +- crates/js/src/bytecode.rs | 81 +++- crates/js/src/compiler.rs | 549 +++++++++++++++++++++--- crates/js/src/es2015_tests.rs | 466 +++++++++++++++++++++ crates/js/src/heap.rs | 32 +- crates/js/src/interp.rs | 577 ++++++++++++++++++++++++-- crates/js/src/interp_tests.rs | 8 + crates/js/src/lexer.rs | 95 ++++- crates/js/src/lib.rs | 23 +- crates/js/src/parser.rs | 503 ++++++++++++++++++++-- crates/js/src/realm.rs | 6 + crates/js/src/token.rs | 15 + crates/js/src/xml.rs | 2 +- crates/js/tests/test262.rs | 169 +++++++- docs/mcp.md | 10 +- docs/target-app-parity.md | 1 + 20 files changed, 2507 insertions(+), 149 deletions(-) create mode 100644 crates/js/src/es2015_tests.rs diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 4223d829ba..a024949a35 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -217,6 +217,15 @@ pub(crate) struct Files { levels: usize, /// The files `$.evalFile` is running, the script first. frames: Vec, + /// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way. + es2015: bool, +} + +/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in +/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as +/// ECMAScript 5.1 with the ExtendScript extensions. +pub(crate) fn es2015_script(path: Option<&str>) -> bool { + path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js")) } /// The output being built: its UTF-16 text, the line it is on, the units since that line began, @@ -311,9 +320,15 @@ impl Files { chain: real.into_iter().collect(), levels: 0, frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }], + es2015: es2015_script(path), } } + /// The options a file of this run is parsed with, preprocessor lines aside. + pub(crate) fn options(&self) -> Options { + Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() } + } + /// The `JSINCLUDE` folders of this process: absolute folders separated by `;`. pub(crate) fn jsinclude_env() -> Vec { #[cfg(test)] @@ -456,7 +471,7 @@ impl Files { return Ok(()); } let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column }; - let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() }; + let options = Options { preprocessor_lines: true, ..self.options() }; let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?; let mut cursor = 0usize; for d in &program.directives { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..a01453a627 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1475,7 +1475,7 @@ fn eval_file(host: &Host, args: Vec) -> std::result::Result 0 { host.placed(error, f.file, f.line, f.column) } else { error } })?; // A file without preprocessor lines is parsed here first, so its syntax error names its place. - let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() }; + let options = host.files.borrow().options(); if let Err(e) = vectorcraft_js::parse(&expanded.source, &options) { host.files.borrow_mut().end_eval(); let (_, file, line, column) = expanded.map.locate(e.line, e.column); @@ -1967,11 +1967,16 @@ impl Session { // A realm made here gets the script extensions, `$` and the dialogs; a kept one has them // from its first run, and they act for the run that calls them. let fresh = realm.is_none(); - let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() }; + // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read + // code the way the script does. + let es2015 = include::es2015_script(request.file.as_deref()); + let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() }; let strict = options.strict; + // A kept engine reads each run's code the way that run's script does. let mut realm = match realm { Some(mut realm) => { realm.set_limits(limits); + realm.set_es2015(es2015); realm } None => { diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index bf8154f9a7..7b0e4bc2f8 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -297,6 +297,40 @@ fn files_are_checked_before_they_are_read() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { + let dir = fresh_folder("es2015"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + write("lib.jsxinc", "const k = 2;\nvar twice = n => n * k;\n"); + write("more.jsx", "let m = `m${k}`;\nm;\n"); + let modern = "#include \"lib.jsxinc\"\nlet x = [1, ...[2]];\nvc.log(`${twice(x[1])}`);\nvc.log(eval('let e = 5; e'));\nvc.log(new Function('a = 6', 'return a')());\nvc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n"; + let r = s.execute("script.run", &path(&write("modern.js", modern))).unwrap(); + assert_eq!(r["log"], json!(["4", 5, 6, "m2"]), "{r}"); + let upper = s.execute("script.run", &path(&write("UPPER.JS", "let u = 1; vc.log(u);"))).unwrap(); + assert_eq!(upper["log"], json!([1]), "{upper}"); + for (name, text) in [("legacy.jsx", "let x = 1;"), ("arrow.jsx", "var f = () => 1;"), ("template.jsx", "vc.log(`t`);")] { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + // Script text given without a file keeps the ExtendScript language. + assert!(run(&mut s, "const c = 1;").unwrap_err().to_string().contains("SyntaxError")); + // A named engine reads each run the way that run's script does. + s.execute("script.run", &path(&write("first.jsx", "#targetengine kept\nvar kept = 1;"))).unwrap(); + let modern = s.execute("script.run", &path(&write("second.js", "#targetengine kept\nlet k2 = kept + 1;\nvc.log(k2);"))).unwrap(); + assert_eq!(modern["log"], json!([2]), "{modern}"); + let legacy = s.execute("script.run", &path(&write("third.jsx", "#targetengine kept\nvc.log(k2);\nconst c = 1;"))); + assert!(legacy.unwrap_err().to_string().contains("SyntaxError")); + let legacy = s.execute("script.run", &path(&write("fourth.jsx", "#targetengine kept\nvc.log(k2 + kept);"))).unwrap(); + assert_eq!(legacy["log"], json!([3]), "{legacy}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A new empty folder for test `name`. fn fresh_folder(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index 8d9ffc06c0..c015e3fa38 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -200,6 +200,40 @@ pub enum Expr { object: ExprId, predicate: ExprId, }, + /// An arrow function. + Arrow(FunctionId), + /// A template literal: its pieces (one more than its substitutions) and its substitutions, + /// in source order. + Template { + quasis: Vec, + exprs: Vec, + }, + /// A tagged template (`` tag`a${b}c` ``): `tag` called with the template object and the + /// substitutions. + TaggedTemplate { + tag: ExprId, + quasis: Vec, + exprs: Vec, + }, + /// `...expression` in an array literal or an argument list, and as the last of an arrow + /// function's parenthesized parameters while they are read. + Spread(ExprId), +} + +/// A piece of a template literal's text between its substitutions. +#[derive(Clone, Debug, PartialEq)] +pub struct TemplatePiece { + /// The text with its escapes read. + pub cooked: Vec, + /// The text as written. + pub raw: Vec, +} + +/// Which lexical declaration a name has. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LexKind { + Let, + Const, } /// A piece of an XML literal, in source order. @@ -247,12 +281,17 @@ pub enum ForInTarget { /// `for (var x in o)`, with the declaration's initializer if it has one. Var(VarDecl), Expr(ExprId), + /// `for (let x in o)` or `for (const x in o)`: a new binding for each name. + Lexical(LexKind, Name), } #[derive(Clone, Debug, PartialEq)] pub enum ForInit { Var(Vec), Expr(ExprId), + /// `let` or `const` declarations, in a scope of the loop's own with a new copy of each `let` + /// binding for each iteration. + Lexical(LexKind, Vec), } #[derive(Clone, Debug, PartialEq)] @@ -272,6 +311,8 @@ pub struct CatchClause { #[derive(Clone, Debug, PartialEq)] pub enum Stmt { Var(Vec), + /// `let` or `const` declarations (a `const` always has an initializer). + Lexical(LexKind, Vec), FunctionDecl(FunctionId), Expr(ExprId), Block(Vec), @@ -334,13 +375,20 @@ pub enum FunctionKind { Expression, Getter, Setter, + /// An arrow function; one with an expression body has a body of one `return` statement. + Arrow, } #[derive(Clone, Debug, PartialEq)] pub struct Function { pub kind: FunctionKind, pub name: Option, + /// The parameters before a rest parameter. pub params: Vec, + /// Each parameter's default value, in the order of `params` (empty when none has one). + pub defaults: Vec>, + /// The rest parameter (`...name`). + pub rest: Option, pub body: Vec, /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. @@ -348,6 +396,13 @@ pub struct Function { pub span: Span, } +impl Function { + /// The parameters are plain names: no default value and no rest parameter. + pub fn simple_params(&self) -> bool { + self.rest.is_none() && self.defaults.iter().all(Option::is_none) + } +} + /// The arenas of a parsed script. #[derive(Clone, Debug, Default, PartialEq)] pub struct Ast { @@ -412,6 +467,8 @@ pub struct Program { /// Its preprocessor lines, in source order. pub directives: Vec, pub(crate) lines: crate::LineTable, + /// It was read with [`crate::Options::es2015`]. + pub(crate) es2015: bool, } impl Program { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..f2c02bdf4c 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -503,7 +503,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)), }; interp.charge_code(&code, 0)?; - let env = interp.global_env; + let env = interp.global_scope(); interp.make_closure(code, env).map(Value::Object) } diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 6992fd5606..28db7edf3d 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -178,6 +178,49 @@ pub(crate) enum Op { ForEachValue(u32), /// `value` → nothing: sets the default XML namespace of the running code. SetDefaultNamespace, + /// Enters a block's environment: the `let` and `const` names of `scopes[i]`, not yet + /// initialized, and its function declarations. + PushBlock(u32), + /// Replaces the current environment with a copy of it, for a `for` loop's next iteration. + CopyEnv, + /// `value` → nothing: initializes the nearest binding of `names[i]`, a `let`, a `const` or + /// a parameter of a function with default or rest parameters. + InitVar(u32), + /// Pushes the value of the parameter `names[i]` of the running function, initialized or not. + LoadParam(u32), + /// Ends the parameters of a function with default or rest parameters: enters the environment + /// of its body's variables and function declarations, and of its `let` and `const` names. + BodyEnv, + /// `value` → nothing: assigns the function declared in a block outside strict mode code to + /// the variable `names[i]` of the running code (ECMA-262 2015 Annex B.3.3). + AnnexB(u32), + /// `array value` → `array`, with the elements of the value appended (spread). + ArraySpread, + /// `function this array` → result: a call with the array's elements as its arguments, a + /// direct eval when `eval` is true and the function is the global `eval`. + CallSpread(bool), + /// `function array` → the new object, constructed with the array's elements as arguments. + NewSpread, + /// `value` → its string (a template literal's substitution). + ToStr, + /// Pushes the template object of `templates[i]`, the same object for each evaluation. + TemplateObject(u32), +} + +/// The names a block declares, entered with [`Op::PushBlock`]. +#[derive(Debug, Default)] +pub(crate) struct BlockScope { + /// The `let` and `const` names, each with whether it is a `const`. + pub(crate) lets: Vec<(Key, bool)>, + /// The function declarations: their names and indices in `functions`. + pub(crate) funcs: Vec<(Key, u32)>, +} + +/// A tagged template's strings: as read and as written. +#[derive(Debug)] +pub(crate) struct Template { + pub(crate) cooked: Vec, + pub(crate) raw: Vec, } /// What code is: a function body, a script, or eval code. @@ -239,6 +282,23 @@ pub(crate) struct Code { pub(crate) source: Rc, /// Where the function's text starts and ends in the source. pub(crate) span: (u32, u32), + /// The block scopes [`Op::PushBlock`] enters. + pub(crate) scopes: Vec, + /// The scope of the `let` and `const` names at the top of the body, script or eval code. + pub(crate) top_scope: Option, + /// The tagged templates [`Op::TemplateObject`] makes objects of. + pub(crate) templates: Vec