From ac365436ac3394471fb1661359f30a4d171f2f60 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 15:46:39 -0800 Subject: [PATCH 001/101] Shapes: the Circle tool draws a circle from its center through a point MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With From Center on (a Control bar checkbox, or the tool option fromCenter), the Circle tool's first point is the circle's center and its outline passes through the second point, which follows the pointer. A drag from the center, or a click on the center and a click on the outline, draws the circle. The second point snaps to Smart Guides and anchor points as the tool's other points do, so a circle centered on one corner of a rectangle can pass exactly through the opposite corner, with the diagonal as its radius. Shift keeps the second point at 45° steps from the center, and Alt rounds the diameter to the rulers' ticks. A second click on the center places nothing. The setting in force when the first point is placed applies to that circle, and the setting is saved with the preferences. Each circle is one undo step. shape.circleThroughPoints takes center: [x, y] with one point in points and draws the circle at the center through that point. A point on the center, and coordinates whose distance overflows, are refused with their own messages. tool.setOption refuses a fromCenter that is not true or false and any other Circle tool option; both errors are translated. Requested by Auriga on the community Discord. Part of #7178. --- ROADMAP.md | 1 + crates/engine/src/cmd/create.rs | 44 +++++-- crates/engine/src/tests/circle_through.rs | 63 ++++++++++ crates/engine/src/tests/toolsettings.rs | 18 +++ crates/engine/src/tooling.rs | 3 + crates/tools/src/circle.rs | 133 +++++++++++++++++----- crates/tools/src/circle/tests.rs | 124 +++++++++++++++++++- crates/tools/src/settings.rs | 2 + crates/ui-egui/src/chrome/tests.rs | 25 +++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tests.rs | 17 +++ crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/toolbar.rs | 22 +++- docs/mcp.md | 15 +++ 40 files changed, 524 insertions(+), 43 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index e9d2cc56b5..8d6ee9ceb7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -139,6 +139,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates 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-17: Circle tool, From Center (a Control bar checkbox, `tool.setOption` `fromCenter`): the first point is the circle's center and the outline passes through the pointer, which snaps to Smart Guides and anchor points, so a circle centered on one corner of a rectangle can pass through the opposite corner; `shape.circleThroughPoints {center, points: [[x, y]]}` draws it. One undo step per circle. A VectorCraft addition: 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. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues 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/create.rs b/crates/engine/src/cmd/create.rs index e9fcad8883..7a5a3633af 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -62,7 +62,7 @@ pub fn specs() -> Vec { "Circle Through Points", [], None, - "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", + "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), center?: [x, y] (the circle's center; `points` then holds the one point its edge passes through, [[x, y]])} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, a point on `center`, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", has_doc, circle_through_points ), @@ -418,12 +418,32 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { /// undo step, named as an Ellipse tool drag is. fn circle_through_points(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.circleThroughPoints"; - let points = match p.get("points").filter(|v| !v.is_null()) { - Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, - None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, + const SAME: &str = "no circle passes through these points: two are the same or all three lie on one line"; + let (center, radius) = match p.get("center").filter(|v| !v.is_null()) { + // From a center: the circle at `center` whose edge passes through the one point. + Some(c) => { + let one = p.get("points").and_then(Value::as_array).and_then(|v| match v.as_slice() { + [q] => pair(q), + _ => None, + }); + let (c, q) = pair(c).zip(one).ok_or_else(|| bad(C, "`center` must be an [x, y] pair of numbers, with one [x, y] pair in `points`"))?; + let r = c.distance(q); + if r == 0.0 { + return Err(bad(C, "the point in `points` is on `center`")); + } + if !r.is_finite() { + return Err(bad(C, "result would exceed the canvas (coordinates out of range)")); + } + (c, r) + } + None => { + let points = match p.get("points").filter(|v| !v.is_null()) { + Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, + None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, + }; + shapes::circle_through_points(&points).ok_or_else(|| bad(C, SAME))? + } }; - let (center, radius) = shapes::circle_through_points(&points) - .ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?; let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; // Not pixel-aligned: the circle stays through the points. @@ -434,13 +454,17 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The point an `[x, y]` pair of finite numbers gives. +fn pair(v: &Value) -> Option { + match v.as_array().map(Vec::as_slice) { + Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)), + _ => None, + } +} + /// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two /// finite numbers. fn two_or_three_points(v: &Value) -> Option> { - let pair = |v: &Value| match v.as_array().map(Vec::as_slice) { - Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)), - _ => None, - }; match v.as_array() { Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(), _ => None, diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index e91c48e76a..462838a979 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -123,6 +123,47 @@ fn two_points_are_the_ends_of_a_diameter() { assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); } +/// With `center`, the circle is centered there and its edge passes through the one point in +/// `points`: from the bottom-right corner (200, 200) of a 100 pt square through its top-left +/// corner (100, 100), the radius is the square's diagonal, in one undo step. A point on the center +/// and a circle past the canvas are refused, and so is a `center` or `points` that is not one +/// `[x, y]` pair of finite numbers; nothing is drawn and no undo step is recorded. +#[test] +fn a_center_and_a_point_on_the_edge_give_the_circle() { + let mut s = session(); + let undo = undo_len(&s); + let out = s.execute(C, &json!({"center": [200, 200], "points": [[100, 100]]})).unwrap(); + let r = 100.0 * std::f64::consts::SQRT_2; + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(200.0), Some(200.0)), "{out}"); + assert!((out["radius"].as_f64().unwrap() - r).abs() < 1e-12, "{out}"); + let id = id_of(&out); + assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(200.0 - r, 200.0 - r, 200.0 + r, 200.0 + r))); + assert!(farthest_from_path(&s, id, &[Point::new(100.0, 100.0)]) < r * 3e-4); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert_eq!(undo_len(&s), undo + 1); + let (undo, count) = (undo_len(&s), object_count(&s)); + let e = s.execute(C, &json!({"center": [30, 30], "points": [[30, 30]]})).unwrap_err().to_string(); + assert!(e.contains("the point in `points` is on `center`"), "{e}"); + // Past the canvas, and finite coordinates whose distance overflows to infinity. + for (center, point) in [(json!([0, 0]), json!([4_100_000, 0])), (json!([-1e308, -1e308]), json!([1e308, 1e308]))] { + let e = s.execute(C, &json!({ "center": center, "points": [point] })).unwrap_err().to_string(); + assert!(e.contains("result would exceed the canvas"), "{center} {point}: {e}"); + } + for (center, points) in [ + (json!([0, 0]), json!([[10, 0], [0, 10]])), + (json!([0, 0]), json!([])), + (json!([0, 0]), Value::Null), + (json!([0, 0]), json!([[10, "0"]])), + (json!([0]), json!([[10, 0]])), + (json!("0,0"), json!([[10, 0]])), + (json!([0, 0, 1]), json!([[10, 0]])), + ] { + let e = s.execute(C, &json!({ "center": center, "points": points })).unwrap_err().to_string(); + assert!(e.contains("`center` must be an [x, y] pair of numbers, with one [x, y] pair in `points`"), "{center} {points}: {e}"); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + /// Points that are not two or three pairs of finite numbers are an error, not a fallback. #[test] fn malformed_points_are_refused() { @@ -214,6 +255,28 @@ fn click(s: &mut Session, mods: Mods, x: f64, y: f64) { } } +/// The Circle tool with From Center set through `tool.setOption`: a click on the center and a +/// click on the edge draw the circle, in one undo step. `fromCenter` must be true or false, and +/// the tool has no other option; a refused value changes nothing. +#[test] +fn the_circle_tool_draws_from_its_center() { + let mut s = session(); + s.select_tool("circle", view()).unwrap(); + let e = s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": "yes"})).unwrap_err(); + assert!(e.contains("`fromCenter` must be true or false"), "{e}"); + assert!(s.set_tool_option_cmd(&json!({"key": "radius", "value": 5})).is_err()); + assert_eq!(s.tool_options()["fromCenter"], json!(false)); + s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": true})).unwrap(); + assert_eq!(s.tool_options()["fromCenter"], json!(true)); + let undo = undo_len(&s); + click(&mut s, Mods::default(), 200.0, 200.0); + click(&mut s, Mods::default(), 100.0, 100.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + let r = 100.0 * std::f64::consts::SQRT_2; + assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(200.0 - r, 200.0 - r, 200.0 + r, 200.0 + r))); +} + /// With the Ellipse tool, three Shift-clicks draw the circle through the three points, in one /// undo step; Escape drops the points placed so far. #[test] diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index a9d9e3f5bd..55513238de 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -30,6 +30,24 @@ fn blob_tip_options_report_and_persist() { assert_eq!((next.tool_options()["angle"].as_f64(), next.tool_options()["roundness"].as_f64()), (Some(45.0), Some(0.0))); } +/// The Circle tool's From Center survives a tool switch and is saved with the preferences. +#[test] +fn circle_from_center_persists() { + let mut s = session(); + select(&mut s, "circle"); + assert_eq!(s.tool_options(), json!({"fromCenter": false})); + s.set_tool_option("fromCenter", &json!(true)); + select(&mut s, "selection"); + select(&mut s, "circle"); + assert_eq!(s.tool_options(), json!({"fromCenter": true})); + select(&mut s, "selection"); + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved).unwrap()); + select(&mut next, "circle"); + assert_eq!(next.tool_options(), json!({"fromCenter": true})); +} + #[test] fn options_survive_a_tool_switch() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 8b8cf4628b..d17caea3dd 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1369,6 +1369,9 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; + if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::circle::ID { + vectorcraft_tools::circle::check_options(&values)?; + } if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID { use vectorcraft_tools::cropimage as crop; // The most the selected image can be cropped to, when one is selected. diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 76e5a2df36..96594a3391 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -15,8 +15,16 @@ //! circle passes through the points (two are the same, three lie on one line) or the circle would //! reach past the canvas, the tool shows none and the release draws nothing; for three different //! points on one line, or a circle past the canvas, the pointer shows "Circle too large". +//! +//! With the option From Center (`fromCenter`, in the Control bar) on, the first point is the +//! circle's center and the outline passes through the second: a drag from the center, or a click +//! on the center and then on a point of the outline, draws the circle whose radius is the distance +//! between them (`shape.circleThroughPoints` with `center`). The second point snaps to anchors and +//! Smart Guides as the others do, so the outline can pass exactly through another object's anchor. +//! Shift keeps the second point at 45° steps from the center, and Alt rounds the diameter to the +//! rulers' ticks. The option in force when the first point is placed applies to that circle. -use serde_json::{Value, json}; +use serde_json::{Map, Value, json}; use vectorcraft_doc::MAX_COORD; use vectorcraft_geom::{Point, Rect, Vec2, shapes}; @@ -57,35 +65,76 @@ pub struct CircleTool { press: Option, /// Where the pointer is, snapped: the point the next press or release places. pointer: Option, + /// The option From Center (`fromCenter`): the first point is the center. + from_center: bool, + /// Is the circle being drawn drawn from its center (From Center when its first point was + /// placed)? + centered: bool, } -/// The command the tool runs for `points`. -fn command(points: &[Point]) -> (String, Value) { - let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); - ("shape.circleThroughPoints".into(), json!({ "points": pairs })) +/// The command the tool runs for `points`: with `centered`, the first point is the center and +/// the second is on the outline. +fn command(points: &[Point], centered: bool) -> (String, Value) { + let pair = |p: &Point| json!([p.x, p.y]); + match points { + [c, p] if centered => ("shape.circleThroughPoints".into(), json!({ "center": pair(c), "points": [pair(p)] })), + _ => ("shape.circleThroughPoints".into(), json!({ "points": points.iter().map(pair).collect::>() })), + } +} + +/// Is the circle at `c` with radius `r` inside the canvas? +fn on_canvas(c: Point, r: f64) -> bool { + [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD) } /// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints` /// draws it: none where no circle passes through them or it would reach past the canvas. pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> { - let on_canvas = |(c, r): &(Point, f64)| [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD); - shapes::circle_through_points(points).filter(on_canvas) + shapes::circle_through_points(points).filter(|(c, r)| on_canvas(*c, *r)) } -/// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on -/// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and -/// when that rounding leaves no distance. -fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point { - let d = first.distance(p); +/// The circle `points` give: with `centered`, the circle at the first point whose outline passes +/// through the second, as `shape.circleThroughPoints` with `center` draws it (none for a second +/// point on the center or a circle past the canvas); otherwise [`circle_of`]. +fn circle_for(points: &[Point], centered: bool) -> Option<(Point, f64)> { + match *points { + [c, p] if centered => { + let r = c.distance(p); + (c.is_finite() && r.is_finite() && r > 0.0 && on_canvas(c, r)).then_some((c, r)) + } + _ if centered => None, + _ => circle_of(points), + } +} + +/// With Alt, `p` moved along the line from `first` so that the diameter (their distance, or twice +/// it from a center) is on the nearest ruler tick at the current zoom, in the General unit; `p` +/// itself without Alt, and when that rounding leaves no distance. +fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods, centered: bool) -> Point { + let per = if centered { 2.0 } else { 1.0 }; + let d = first.distance(p) * per; let rounded = cx.unit.snap_to_ruler_tick(d, cx.zoom); if mods.alt && d > 0.0 && rounded > 0.0 && rounded.is_finite() { first + (p - first) * (rounded / d) } else { p } } /// Are the points two or more different points through which no circle is drawn: three on one /// line, or a circle that would reach past the canvas? -fn too_large(points: &[Point]) -> bool { +fn too_large(points: &[Point], centered: bool) -> bool { let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p)); - points.len() >= 2 && distinct && circle_of(points).is_none() + points.len() >= 2 && distinct && circle_for(points, centered).is_none() +} + +/// Checks the options `tool.setOption` sets on the Circle tool: `fromCenter` is true or false, and +/// no other key is known. +pub fn check_options(values: &Map) -> Result<(), String> { + for (key, v) in values { + match key.as_str() { + "fromCenter" if v.is_boolean() => {} + "fromCenter" => return Err(format!("`{key}` must be true or false")), + _ => return Err(format!("unknown Circle tool option `{key}`")), + } + } + Ok(()) } impl CircleTool { @@ -93,9 +142,15 @@ impl CircleTool { self.first = None; self.press = None; self.pointer = None; + self.centered = false; self.snap.clear(); } + /// [`round_diameter`] for the circle being drawn. + fn round(&self, cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point { + round_diameter(cx, first, p, mods, self.centered) + } + /// How the second point keeps to the first: Shift's 45° steps and the construction guides. fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { self.first.map(|a| Leave::segment(cx, a, mods.shift)) @@ -108,6 +163,8 @@ impl CircleTool { Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())), // A press on the first point adds no point: a drag from it drags out a diameter. Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)), + // From a center, the second point follows the pointer. + Some(Press::Second { .. }) if self.centered => out.extend(self.pointer), Some(Press::Second { at, dragged: false, .. }) => out.push(at), Some(Press::Second { snapped, dragged: true, .. }) => { out.push(snapped); @@ -117,8 +174,12 @@ impl CircleTool { out } - /// The second point as the tool shows it: none for a press on the first point. + /// The second point as the tool shows it: none for a press on the first point, nor for a + /// circle drawn from its center, whose second point follows the pointer. fn second(&self) -> Option { + if self.centered { + return None; + } match self.press { Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at), Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped), @@ -129,11 +190,12 @@ impl CircleTool { /// Runs the circle through `points` and starts afresh; where no circle is drawn through them /// (the tool showed none), it only starts afresh. fn draw(&mut self, points: &[Point]) -> Vec { + let centered = self.centered; self.clear(); - if circle_of(points).is_none() { + if circle_for(points, centered).is_none() { return vec![]; } - let (c, v) = command(points); + let (c, v) = command(points, centered); vec![Action::Exec(c, v)] } } @@ -151,7 +213,7 @@ impl Tool for CircleTool { PointerKind::Move => { let leave = self.leave(cx, ev.mods); let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref()); - self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + self.pointer = Some(self.first.map_or(p, |a| self.round(cx, a, p, ev.mods))); vec![] } PointerKind::Down => { @@ -159,13 +221,14 @@ impl Tool for CircleTool { None => { let at = self.snap.press(cx, ev.pos, &[], None); self.first = Some(at); + self.centered = self.from_center; self.press = Some(Press::First { at, from: ev.pos, dragged: false }); self.pointer = Some(at); } Some(a) => { let leave = self.leave(cx, ev.mods); let snapped = self.snap.press(cx, ev.pos, &[], leave.as_ref()); - let at = round_diameter(cx, a, snapped, ev.mods); + let at = self.round(cx, a, snapped, ev.mods); let on_first = snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX); self.press = Some(Press::Second { at, snapped, from: ev.pos, on_first, dragged: false }); self.pointer = Some(at); @@ -174,19 +237,21 @@ impl Tool for CircleTool { vec![] } PointerKind::Drag => { + let centered = self.centered; match &mut self.press { Some(Press::First { at, from, dragged }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); let leave = Leave::segment(cx, *at, ev.mods.shift); - self.pointer = Some(round_diameter(cx, *at, self.snap.drag(cx, ev.pos, Some(&leave)), ev.mods)); + self.pointer = Some(round_diameter(cx, *at, self.snap.drag(cx, ev.pos, Some(&leave)), ev.mods, centered)); } // Dragged from the first point, the pointer is the other end of a diameter, as - // for a drag from a first press. - Some(Press::Second { from, on_first: true, dragged, .. }) => { + // for a drag from a first press; from a center, the second point is always the + // pointer. + Some(Press::Second { from, dragged, on_first, .. }) if *on_first || centered => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); let leave = self.first.map(|a| Leave::segment(cx, a, ev.mods.shift)); let p = self.snap.drag(cx, ev.pos, leave.as_ref()); - self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods, centered))); } Some(Press::Second { from, dragged, .. }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); @@ -208,6 +273,8 @@ impl Tool for CircleTool { (Some(Press::Second { on_first: true, dragged: false, .. }), ..) => vec![], (Some(Press::Second { on_first: true, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, c]), (Some(Press::Second { at, dragged: false, .. }), Some(a), _) => self.draw(&[a, at]), + // From a center: the outline passes through the point the drag ends on. + (Some(Press::Second { dragged: true, .. }), Some(a), Some(c)) if self.centered => self.draw(&[a, c]), // Three points: Alt's rounding of the diameter does not apply. (Some(Press::Second { snapped, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, snapped, c]), _ => vec![], @@ -216,6 +283,19 @@ impl Tool for CircleTool { } } + /// `{fromCenter}`. + fn options(&self) -> Value { + json!({ "fromCenter": self.from_center }) + } + + /// `fromCenter` (true or false, [`check_options`]); a circle being drawn keeps the mode it + /// started with. + fn set_option(&mut self, key: &str, value: &Value) { + if let ("fromCenter", Some(on)) = (key, value.as_bool()) { + self.from_center = on; + } + } + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { if key == ToolKey::Escape { self.clear(); @@ -263,13 +343,14 @@ impl Tool for CircleTool { let mut o = self.snap.guides().to_vec(); let points = self.points(); let color = crate::draw2::FEEDBACK; - if let Some((c, r)) = circle_of(&points) { + if let Some((c, r)) = circle_for(&points, self.centered) { let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); // The canvas draws a dashed outline dash by dash along its whole length: a circle longer // than DASHED_PX on screen is drawn solid instead. let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); o.push(Overlay::Path { path, color, width: 1.0, dashed }); - for p in &points { + // A circle drawn from its center has one radius, to the point on its outline. + for p in points.iter().filter(|p| **p != c) { o.push(Overlay::Line { a: c, b: *p, color, dashed: false }); } let arm = cx.tol(CROSS_PX); @@ -278,7 +359,7 @@ impl Tool for CircleTool { if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) { o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); } - } else if let Some(p) = self.pointer.filter(|_| too_large(&points)) { + } else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.centered)) { o.push(Overlay::Label { p, text: "Circle too large".into(), color }); } for p in self.first.into_iter().chain(self.second()) { diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index a6caafbc1d..53ae46bbef 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -199,8 +199,8 @@ fn points_on_one_line_say_the_circle_is_too_large() { assert_eq!(label(&t), None, "a circle is shown"); t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default())); assert_eq!(label(&t), None, "the third point is on the second"); - assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)])); - assert!(!too_large(&[Point::new(0.0, 0.0)]) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)])); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], false)); + assert!(!too_large(&[Point::new(0.0, 0.0)], false) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], false)); } /// Escape drops the first point; so do a dropped press and an edit made outside the tool. A @@ -313,6 +313,126 @@ fn a_huge_circle_is_previewed_solid() { assert!(preview(&t.overlays(&cx)).is_some()); } +/// The command the tool runs for a circle at `c` whose outline passes through `p`. +fn centered(c: (f64, f64), p: (f64, f64)) -> Vec { + vec![Action::Exec("shape.circleThroughPoints".into(), json!({ "center": [c.0, c.1], "points": [[p.0, p.1]] }))] +} + +fn from_center() -> CircleTool { + let mut t = CircleTool::default(); + t.set_option("fromCenter", &json!(true)); + t +} + +/// With From Center, a drag from the corner anchor of the rectangle at (200, 200) to next to the +/// opposite corner at (100, 100) snaps both ends to the anchors: the circle is centered on one +/// corner, its outline passes through the other, and its radius is the diagonal. Until the release +/// the outline passes through the pointer, with one radius drawn to it. +#[test] +fn from_center_the_outline_passes_through_the_opposite_corner() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = from_center(); + assert_eq!(t.options(), json!({ "fromCenter": true })); + t.pointer(&cx, &ev(PointerKind::Move, (201.0, 199.5), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Down, (201.0, 199.5), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (150.0, 150.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (101.0, 101.5), Mods::default())); + let r = 100.0 * std::f64::consts::SQRT_2; + let o = t.overlays(&cx); + let shown = o + .iter() + .find_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + _ => None, + }) + .expect("the circle is shown"); + assert!(near(shown, Rect::new(200.0 - r, 200.0 - r, 200.0 + r, 200.0 + r)), "{o:?}"); + let center = Point::new(200.0, 200.0); + let radii: Vec = o + .iter() + .filter_map(|o| match o { + Overlay::Line { a, b, .. } if *a == center => Some(*b), + _ => None, + }) + .collect(); + assert_eq!(radii, vec![Point::new(100.0, 100.0)], "one radius, to the pointer: {o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("D: 282.84"))), "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.0, 101.5), Mods::default())), centered((200.0, 200.0), (100.0, 100.0))); + assert_eq!(circle_for(&[center, Point::new(100.0, 100.0)], true), Some((center, r))); +} + +/// With From Center, a click places the center and a second click the point the outline passes +/// through; a second click on the center places nothing, and the center stays. +#[test] +fn from_center_two_clicks_draw_the_circle_through_the_second() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]); + assert_eq!(click(&mut t, &cx, (300.5, 300.0)), vec![], "a double-click places the center alone"); + assert!(t.ends_on_escape(&cx)); + t.pointer(&cx, &ev(PointerKind::Move, (330.0, 340.0), Mods::default())); + // Center (300, 300), radius 50. + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(250.0, 250.0, 350.0, 350.0)), "{:?}", t.overlays(&cx)); + assert_eq!(click(&mut t, &cx, (330.0, 340.0)), centered((300.0, 300.0), (330.0, 340.0))); + // A second press dragged from elsewhere moves the point the outline passes through. + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(drag(&mut t, &cx, (330.0, 340.0), &[(360.0, 300.0)], Mods::default()), centered((300.0, 300.0), (360.0, 300.0))); +} + +/// With From Center, Shift keeps the point at 45° steps from the center, and Alt rounds the +/// diameter, twice the radius, to the rulers' ticks (every 5 pt at 100% in points). +#[test] +fn from_center_shift_and_alt_keep_to_the_center() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + let shift = Mods { shift: true, ..Mods::default() }; + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(400.0, 310.0)], shift); + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + assert!((v["points"][0][1].as_f64().unwrap() - 300.0).abs() < 1e-9, "level with the center: {v}"); + // Near the diagonal, the point keeps to the 45° line through the center. + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 372.0)], shift); + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + let (x, y) = (v["points"][0][0].as_f64().unwrap(), v["points"][0][1].as_f64().unwrap()); + assert!(((x - 300.0) - (y - 300.0)).abs() < 1e-9 && x > 300.0, "on the 45° line from the center: {v}"); + let alt = Mods { alt: true, ..Mods::default() }; + // A radius of 26 is a diameter of 52, which Alt makes 50. + assert_eq!(drag(&mut t, &cx, (0.0, 0.0), &[(0.0, 26.0)], alt), centered((0.0, 0.0), (0.0, 25.0))); +} + +/// The option in force when the first point is placed applies to that circle: turning From Center +/// off part way keeps the circle being drawn centered, and the next circle is drawn on a diameter. +/// A point on the center draws nothing. +#[test] +fn from_center_holds_for_the_circle_being_drawn() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("fromCenter", &json!(false)); + assert_eq!(click(&mut t, &cx, (100.0, 150.0)), centered((100.0, 100.0), (100.0, 150.0))); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert_eq!(circle_for(&[Point::new(1.0, 1.0), Point::new(1.0, 1.0)], true), None); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true)); + t.set_option("fromCenter", &json!("yes")); + assert_eq!(t.options(), json!({ "fromCenter": false }), "a value that is not true or false is ignored"); +} + +/// `tool.setOption` takes `fromCenter` as true or false, and no other key. +#[test] +fn the_options_are_checked() { + let map = |v: Value| v.as_object().cloned().unwrap(); + assert_eq!(check_options(&map(json!({ "fromCenter": true }))), Ok(())); + assert_eq!(check_options(&map(json!({ "fromCenter": 1 }))), Err("`fromCenter` must be true or false".into())); + assert_eq!(check_options(&map(json!({ "radius": 5 }))), Err("unknown Circle tool option `radius`".into())); +} + /// The tool is in the Ellipse tool's group, after the Ellipse tool. #[test] fn the_circle_tool_follows_the_ellipse_tool() { diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 97e980e3c0..65144f78b5 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -53,6 +53,8 @@ const ROWS: &[Row] = &[ (&["star"], None, &["points"]), // The Ellipse dialog's Anchors. (&["ellipse"], None, &["anchors"]), + // The Circle tool's From Center. + (&[crate::circle::ID], None, &["fromCenter"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 61c67e6a70..a2b240d086 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -3767,6 +3767,27 @@ fn control_bar_overflow(app: &mut crate::VectorcraftApp, ctx: &egui::Context, sc /// tool's, in English and in German. Every control it shows is drawn whole, left of the panel menu /// button, which shows in every width, with the bar docked to the top or the bottom or floating. In a /// wide window, each of those groups shows its controls. +/// A click on the Circle tool's From Center checkbox in the Control bar turns the option on, and a +/// second click turns it off. +#[test] +fn the_circle_tool_s_from_center_checkbox_sets_the_option() { + use crate::tests_removeanchors::{click_control, control_frame}; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.select_tool("circle"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let from_center = |app: &crate::VectorcraftApp| app.session.tool_options()["fromCenter"].clone(); + assert_eq!(from_center(&app), json!(false)); + for want in [true, false] { + let bar = control_frame(&mut app, &ctx, vec![]); + let at = bar.iter().find(|(t, _)| t == "From Center").map(|(_, r)| r.center()).expect("From Center shows"); + click_control(&mut app, &ctx, at); + assert_eq!(from_center(&app), json!(want)); + } +} + #[test] fn the_control_bar_s_controls_stay_inside_the_bar_in_a_narrow_window() { use crate::tests_removeanchors::{control_frame, has}; @@ -3820,10 +3841,12 @@ fn the_control_bar_s_controls_stay_inside_the_bar_in_a_narrow_window() { }; // The tools' options, with a rectangle selected and with nothing selected. app.run("select.set", json!({ "ids": [id] })).unwrap(); - for tool in ["rectangle", "ellipse", "polygon", "star", "spiral", "box3d", "dimension", "mirrorCut", "puppetWarp"] { + for tool in ["rectangle", "ellipse", "circle", "polygon", "star", "spiral", "box3d", "dimension", "mirrorCut", "puppetWarp"] { app.select_tool(tool); check(&mut app, tool); } + app.select_tool("circle"); + wide(&mut app, "Circle", &["From Center"]); app.select_tool("polygon"); wide(&mut app, "Polygon", &["Round", "Random", "Reset"]); app.select_tool("mirrorCut"); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d347439b69..0344f9e24c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -467,6 +467,7 @@ font-technology Variable Променливи Circle Кръг Circle Tool Инструмент Кръг Circle too large Кръгът е твърде голям + From Center От центъра Classic Defaults Класически по подразбиране Clean Up… Почистване… Clear Изчистване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 6fea288f77..86d6495de6 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4527,6 +4527,7 @@ font-technology Variable Varijabilni Circle Krug Circle Tool Alat za krug Circle too large Krug je prevelik + From Center Od središta Clip to Art Isijeci prema crtežu Colorize Oboji Gamma Gama diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e99406bffe..fd363e5cc6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -702,6 +702,7 @@ antiAlias Sharp Nítid Circle Cercle Circle Tool Eina de cercle Circle too large El cercle és massa gran + From Center Des del centre Circle (open) Cercle (obert) Classic Clàssic Classic Defaults Valors predeterminats clàssics @@ -5584,6 +5585,7 @@ digits Malayalam Malaiàlam @msg `{key}` must be a #rrggbb color or a layer color name `{key}` ha de ser un color #rrggbb o el nom d’un color de capa @msg unknown Live Paint option `{key}` opció de pintura interactiva desconeguda `{key}` @msg unknown Shape Builder option `{key}` opció del constructor de formes desconeguda `{key}` +@msg unknown Circle tool option `{key}` opció de l’eina Cercle desconeguda `{key}` @msg `{key}` must be a #rrggbb colour `{key}` ha de ser un color #rrggbb @msg `{key}` must be a number `{key}` ha de ser un nombre @msg `{key}` must be a number not below 0 `{key}` ha de ser un nombre no inferior a 0 @@ -6152,6 +6154,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg no active perspective plane no hi ha cap pla de perspectiva actiu @msg no anchor points selected no hi ha cap punt d’ancoratge seleccionat @msg `points` must be two or three [x, y] pairs of numbers `points` han de ser dos o tres parells de nombres [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` ha de ser un parell de nombres [x, y], amb un parell [x, y] a `points` +@msg the point in `points` is on `center` el punt de `points` és a `center` @msg direct-select two or three anchor points, or give `points` seleccioneu directament dos o tres punts d’ancoratge o indiqueu `points` @msg no circle passes through these points: two are the same or all three lie on one line cap cercle no passa per aquests punts: dos són iguals o tots tres són en una mateixa recta @msg no app to open files here aquí no hi ha cap aplicació per obrir fitxers diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b217199fe0..662911c598 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4631,6 +4631,7 @@ font-technology Variable Variabilní Circle Kruh Circle Tool Nástroj Kruh Circle too large Kruh je příliš velký + From Center Ze středu Clip to Art Oříznout podle kresby Colorize Obarvit Gamma Gama @@ -5121,6 +5122,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg `{key}` must be a #rrggbb color or a layer color name `{key}` musí být barva #rrggbb nebo název barvy vrstvy @msg unknown Live Paint option `{key}` neznámá možnost živé malby `{key}` @msg unknown Shape Builder option `{key}` neznámá možnost tvorby tvarů `{key}` +@msg unknown Circle tool option `{key}` neznámá možnost nástroje Kruh `{key}` @msg `{key}` must be a #rrggbb colour `{key}` musí být barva #rrggbb @msg `{key}` must be a number `{key}` musí být číslo @msg `{key}` must be a number, not {v} `{key}` musí být číslo, ne {v} @@ -5317,6 +5319,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg no active perspective plane žádná aktivní perspektivní rovina @msg no anchor points selected nejsou vybrány žádné kotevní body @msg `points` must be two or three [x, y] pairs of numbers `points` musí být dvě nebo tři dvojice čísel [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` musí být dvojice čísel [x, y] a `points` musí obsahovat jednu dvojici [x, y] +@msg the point in `points` is on `center` bod v `points` leží na `center` @msg direct-select two or three anchor points, or give `points` vyberte přímým výběrem dva nebo tři kotevní body, nebo zadejte `points` @msg no circle passes through these points: two are the same or all three lie on one line těmito body neprochází žádná kružnice: dva jsou stejné nebo všechny tři leží na jedné přímce @msg no app to open files here zde chybí aplikace pro otevírání souborů diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index de726e7860..e62fe02e03 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -229,6 +229,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg `{key}` must be a #rrggbb color or a layer color name `{key}` skal være en #rrggbb-farve eller navnet på en lagfarve @msg unknown Live Paint option `{key}` ukendt Live Paint-indstilling `{key}` @msg unknown Shape Builder option `{key}` ukendt Formbygger-indstilling `{key}` +@msg unknown Circle tool option `{key}` ukendt Cirkelværktøj-indstilling `{key}` @msg `{key}` must be a profile name or null `{key}` skal være et profilnavn eller null @msg `top` and `below` can't both be true `top` og `below` kan ikke begge være true @msg `select` must be true or false `select` skal være true eller false @@ -7030,6 +7031,7 @@ font-technology Variable Variable Circle Cirkel Circle Tool Cirkelværktøj Circle too large Cirklen er for stor + From Center Fra midten Clip to Art Beskær til grafik Colorize Farvelæg Gamma Gamma @@ -7506,6 +7508,8 @@ imageTrace Outline Kontur @msg no active perspective plane intet aktivt perspektivplan @msg no anchor points selected ingen ankerpunkter er markeret @msg `points` must be two or three [x, y] pairs of numbers `points` skal være to eller tre talpar [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` skal være et talpar [x, y], med ét talpar [x, y] i `points` +@msg the point in `points` is on `center` punktet i `points` ligger på `center` @msg direct-select two or three anchor points, or give `points` direkte markér to eller tre ankerpunkter, eller angiv `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går gennem disse punkter: to er ens, eller alle tre ligger på én linje @msg no app to open files here ingen app til at åbne filer her diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index f85240675f..51859ea3bc 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -458,6 +458,7 @@ font-technology Variable Variabel Circle Kreis Circle Tool Kreis-Werkzeug Circle too large Kreis zu groß + From Center Von der Mitte aus Classic Defaults Klassische Standardwerte Clean Up… Aufräumen… Clear Löschen @@ -4722,6 +4723,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg `{key}` must be a #rrggbb color or a layer color name `{key}` muss eine Farbe der Form #rrggbb oder der Name einer Ebenenfarbe sein @msg unknown Live Paint option `{key}` unbekannte Option für Interaktiv malen `{key}` @msg unknown Shape Builder option `{key}` unbekannte Option für Formerstellung `{key}` +@msg unknown Circle tool option `{key}` unbekannte Option für das Kreis-Werkzeug `{key}` @msg `{key}` must be a #rrggbb colour `{key}` muss eine Farbe der Form #rrggbb sein @msg `{key}` must be a number `{key}` muss eine Zahl sein @msg `{key}` must be a number, not {v} `{key}` muss eine Zahl sein, nicht {v} @@ -4918,6 +4920,8 @@ liquify-list-end {0}, {1} {0} und {1} @msg no active perspective plane keine aktive Perspektivebene @msg no anchor points selected keine Ankerpunkte ausgewählt @msg `points` must be two or three [x, y] pairs of numbers `points` muss aus zwei oder drei Zahlenpaaren [x, y] bestehen +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` muss ein Zahlenpaar [x, y] sein, mit einem Paar [x, y] in `points` +@msg the point in `points` is on `center` der Punkt in `points` liegt auf `center` @msg direct-select two or three anchor points, or give `points` wählen Sie zwei oder drei Ankerpunkte direkt aus oder geben Sie `points` an @msg no circle passes through these points: two are the same or all three lie on one line durch diese Punkte verläuft kein Kreis: zwei sind gleich oder alle drei liegen auf einer Linie @msg no app to open files here hier gibt es keine App zum Öffnen von Dateien diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a26550a5ac..31699d5491 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -451,6 +451,7 @@ font-technology Variable Μεταβλητές Circle Κύκλος Circle Tool Εργαλείο κύκλου Circle too large Ο κύκλος είναι πολύ μεγάλος + From Center Από το κέντρο Classic Defaults Κλασικές προεπιλογές Clean Up… Εκκαθάριση… Clear Εκκαθάριση @@ -2721,6 +2722,7 @@ liquify-list-end {0}, {1} {0} και {1} @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 unknown Circle tool option `{key}` άγνωστη επιλογή εργαλείου κύκλου `{key}` @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} @@ -4976,6 +4978,8 @@ digits Malayalam Μαλαγιάλαμ @msg no active perspective plane δεν υπάρχει ενεργό επίπεδο προοπτικής @msg no anchor points selected δεν έχουν επιλεγεί σημεία αγκύρωσης @msg `points` must be two or three [x, y] pairs of numbers το `points` πρέπει να είναι δύο ή τρία ζεύγη αριθμών [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` το `center` πρέπει να είναι ένα ζεύγος αριθμών [x, y], με ένα ζεύγος [x, y] στο `points` +@msg the point in `points` is on `center` το σημείο στο `points` βρίσκεται πάνω στο `center` @msg direct-select two or 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 no app to open files here δεν υπάρχει εφαρμογή για άνοιγμα αρχείων εδώ diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 74e4627a9c..5901422d6b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -481,6 +481,7 @@ font-technology Variable Variables Circle Círculo Circle Tool Herramienta Círculo Circle too large Círculo demasiado grande + From Center Desde el centro Classic Defaults Valores predeterminados clásicos Clean Up… Limpiar… Clear Borrar @@ -4826,6 +4827,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `{key}` must be a #rrggbb color or a layer color name `{key}` debe ser un color #rrggbb o el nombre de un color de capa @msg unknown Live Paint option `{key}` opción de pintura interactiva desconocida `{key}` @msg unknown Shape Builder option `{key}` opción del generador de formas desconocida `{key}` +@msg unknown Circle tool option `{key}` opción de la herramienta Círculo desconocida `{key}` @msg `{key}` must be a #rrggbb colour `{key}` debe ser un color #rrggbb @msg `{key}` must be a number `{key}` debe ser un número @msg `{key}` must be a number, not {v} `{key}` debe ser un número, no {v} @@ -5022,6 +5024,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg no active perspective plane no hay ningún plano de perspectiva activo @msg no anchor points selected no hay puntos de ancla seleccionados @msg `points` must be two or three [x, y] pairs of numbers `points` debe ser dos o tres pares de números [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` debe ser un par de números [x, y], con un par [x, y] en `points` +@msg the point in `points` is on `center` el punto de `points` está en `center` @msg direct-select two or three anchor points, or give `points` seleccione directamente dos o tres puntos de ancla o indique `points` @msg no circle passes through these points: two are the same or all three lie on one line ningún círculo pasa por estos puntos: dos son iguales o los tres están en una misma línea @msg no app to open files here aquí no hay ninguna aplicación para abrir archivos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 170db8da57..a3d6f76b86 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4550,6 +4550,7 @@ font-technology Variable Muuttuvat Circle Ympyrä Circle Tool Ympyrätyökalu Circle too large Ympyrä on liian suuri + From Center Keskeltä Clip to Art Rajaa kuvitukseen Colorize Väritä Gamma Gamma @@ -5058,6 +5059,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `{key}` must be a #rrggbb color or a layer color name `{key}` on oltava #rrggbb-väri tai tason värin nimi @msg unknown Live Paint option `{key}` tuntematon elävän maalauksen valinta `{key}` @msg unknown Shape Builder option `{key}` tuntematon muodonmuodostimen valinta `{key}` +@msg unknown Circle tool option `{key}` tuntematon ympyrätyökalun valinta `{key}` @msg `{key}` must be a #rrggbb colour `{key}` on oltava #rrggbb-väri @msg `{key}` must be a number `{key}` on oltava luku @msg `{key}` must be a number, not {v} `{key}` on oltava luku, ei {v} @@ -5246,6 +5248,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no active perspective plane ei aktiivista perspektiivitasoa @msg no anchor points selected ankkuripisteitä ei ole valittu @msg `points` must be two or three [x, y] pairs of numbers `points` on annettava kahtena tai kolmena lukuparina [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` on annettava lukuparina [x, y], ja `points` sisältää yhden lukuparin [x, y] +@msg the point in `points` is on `center` `points`-kohdan piste on `center`-kohdassa @msg direct-select two or three anchor points, or give `points` valitse suoraan kaksi tai kolme ankkuripistettä tai anna `points` @msg no circle passes through these points: two are the same or all three lie on one line näiden pisteiden kautta ei kulje ympyrää: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla @msg no app to open files here täällä ei ole sovellusta tiedostojen avaamiseen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 9ca4919a2e..1080917f44 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -482,6 +482,7 @@ font-technology Variable Variables Circle Cercle Circle Tool Outil Cercle Circle too large Cercle trop grand + From Center Depuis le centre Classic Defaults Valeurs par défaut classiques Clean Up… Nettoyer… Clear Effacer @@ -4788,6 +4789,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `{key}` must be a #rrggbb color or a layer color name `{key}` doit être une couleur #rrggbb ou le nom d’une couleur de calque @msg unknown Live Paint option `{key}` option de peinture dynamique inconnue `{key}` @msg unknown Shape Builder option `{key}` option du concepteur de forme inconnue `{key}` +@msg unknown Circle tool option `{key}` option de l’outil Cercle inconnue `{key}` @msg `{key}` must be a #rrggbb colour `{key}` doit être une couleur #rrggbb @msg `{key}` must be a number `{key}` doit être un nombre @msg `{key}` must be a number, not {v} `{key}` doit être un nombre, pas {v} @@ -4984,6 +4986,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg no active perspective plane aucun plan de perspective actif @msg no anchor points selected aucun point d’ancrage sélectionné @msg `points` must be two or three [x, y] pairs of numbers `points` doit contenir deux ou trois paires de nombres [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` doit être une paire de nombres [x, y], avec une paire [x, y] dans `points` +@msg the point in `points` is on `center` le point de `points` est sur `center` @msg direct-select two or three anchor points, or give `points` sélectionnez deux ou trois points d’ancrage avec l’outil Sélection directe, ou indiquez `points` @msg no circle passes through these points: two are the same or all three lie on one line aucun cercle ne passe par ces points : deux sont identiques ou les trois sont alignés @msg no app to open files here aucune application pour ouvrir des fichiers ici diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 532fcb06cb..2f0554abb7 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -564,6 +564,7 @@ Circle વર્તુળ Circle Tool વર્તુળ ટૂલ Circle too large વર્તુળ ખૂબ મોટું છે + From Center કેન્દ્રથી Circle: વર્તુળ: Classic ક્લાસિક Clean Up સાફ કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3bfe38fb3e..747f8f82cf 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -822,6 +822,7 @@ antiAlias Sharp शार्प Circle वृत्त Circle Tool वृत्त टूल Circle too large वृत्त बहुत बड़ा है + From Center केंद्र से Circle (open) सर्किल (ओपन) Circle: वृत्त: Classic क्लासिक @@ -6245,6 +6246,7 @@ antiAlias Sharp शार्प @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 unknown Circle tool option `{key}` अज्ञात वृत्त टूल ऑप्शन `{key}` @msg `{key}` must be a #rrggbb colour `{key}` एक #rrggbb रंग होना चाहिए @msg `{key}` must be a non-negative integer `{key}` को एक गैर-नकारात्मक पूर्णांक होना चाहिए @msg `{key}` must be a number `{key}` एक संख्या होना चाहिए @@ -7634,6 +7636,8 @@ liquify-list-end {0}, {1} {0} और {1} @msg no active perspective plane कोई सक्रिय पर्सपेक्टिव विमान नहीं @msg no anchor points selected कोई एंकर पॉइंट सिलेक्ट नहीं है @msg `points` must be two or three [x, y] pairs of numbers `points` में संख्याओं के दो या तीन [x, y] जोड़े होने चाहिए +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` संख्याओं का एक [x, y] जोड़ा होना चाहिए, और `points` में एक [x, y] जोड़ा होना चाहिए +@msg the point in `points` is on `center` `points` का बिंदु `center` पर है @msg direct-select two or 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 no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index cfc6c224a3..5c4977da98 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -643,6 +643,7 @@ font-technology Variable Változó Circle Kör Circle Tool Kör eszköz Circle too large A kör túl nagy + From Center Középről Circle (open) Kör (nyitott) Classic Defaults Klasszikus alapértékek Clean Up… Tisztítás… @@ -5182,6 +5183,7 @@ imageTrace Outline Körvonal @msg `{key}` must be a #rrggbb color or a layer color name `{key}`: #rrggbb szín vagy rétegszín neve kell @msg unknown Live Paint option `{key}` ismeretlen élő festés beállítás: `{key}` @msg unknown Shape Builder option `{key}` ismeretlen alakzatépítő beállítás: `{key}` +@msg unknown Circle tool option `{key}` ismeretlen Kör eszköz beállítás: `{key}` @msg `{key}` must be a #rrggbb colour `{key}`: #rrggbb szín kell @msg `{key}` must be a number `{key}`: szám kell @msg `{key}` must be a number, not {v} `{key}`: szám kell, ez nem az: {v} @@ -5685,6 +5687,8 @@ liquify-list-end {0}, {1} {0} és {1} @msg no active perspective plane nincs aktív perspektivikus sík @msg no anchor points selected nincs kijelölt horgonypont @msg `points` must be two or three [x, y] pairs of numbers a `points` két vagy három [x, y] számpár legyen +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` a `center` egy [x, y] számpár legyen, a `points` pedig egy [x, y] párt tartalmazzon +@msg the point in `points` is on `center` a `points` pontja a `center` helyén van @msg direct-select two or three anchor points, or give `points` jelölj ki közvetlen kijelöléssel két vagy három horgonypontot, vagy add meg a `points` értéket @msg no circle passes through these points: two are the same or all three lie on one line ezeken a pontokon nem halad át kör: kettő egybeesik, vagy mindhárom egy egyenesen van @msg no app to open files here itt nincs fájlmegnyitó alkalmazás diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0526f18380..b77f342253 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4282,6 +4282,7 @@ font-technology Variable Variabel Circle Lingkaran Circle Tool Alat lingkaran Circle too large Lingkaran terlalu besar + From Center Dari tengah Clip to Art Pangkas ke karya seni Colorize Warnai Gamma Gamma diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 066a4ef6fd..d4d13bb83b 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -483,6 +483,7 @@ font-technology Variable Variabili Circle Cerchio Circle Tool Strumento Cerchio Circle too large Cerchio troppo grande + From Center Dal centro Classic Defaults Valori predefiniti classici Clean Up… Pulisci… Clear Cancella @@ -4856,6 +4857,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `{key}` must be a #rrggbb color or a layer color name `{key}` deve essere un colore #rrggbb o il nome di un colore del livello @msg unknown Live Paint option `{key}` opzione di pittura dinamica sconosciuta `{key}` @msg unknown Shape Builder option `{key}` opzione del generatore forme sconosciuta `{key}` +@msg unknown Circle tool option `{key}` opzione dello strumento Cerchio sconosciuta `{key}` @msg `{key}` must be a #rrggbb colour `{key}` deve essere un colore #rrggbb @msg `{key}` must be a number `{key}` deve essere un numero @msg `{key}` must be a number, not {v} `{key}` deve essere un numero, non {v} @@ -5052,6 +5054,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg no active perspective plane nessun piano prospettico attivo @msg no anchor points selected nessun punto di ancoraggio selezionato @msg `points` must be two or three [x, y] pairs of numbers `points` deve essere composto da due o tre coppie di numeri [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` deve essere una coppia di numeri [x, y], con una coppia [x, y] in `points` +@msg the point in `points` is on `center` il punto in `points` si trova su `center` @msg direct-select two or three anchor points, or give `points` seleziona con Selezione diretta due o tre punti di ancoraggio oppure indica `points` @msg no circle passes through these points: two are the same or all three lie on one line nessun cerchio passa per questi punti: due coincidono oppure tutti e tre sono allineati @msg no app to open files here nessuna app per aprire file qui diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 597abda551..365eceb39f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1299,6 +1299,7 @@ antiAlias Sharp シャープ Circle 円 Circle Tool 円ツール Circle too large 円が大きすぎます + From Center 中心から Clear All Tabs すべてのタブを消去 Above Text テキストの上 Position Panel Above Text テキストの上にパネルを配置 @@ -4846,6 +4847,8 @@ swatch Bright Violet ビビッドバイオレット @msg clipboard is empty クリップボードが空です @msg no anchor points selected アンカーポイントが選択されていません @msg `points` must be two or three [x, y] pairs of numbers `points` は 2 組または 3 組の数値 [x, y] にしてください +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` は数値の組 [x, y] にし、`points` には [x, y] を 1 組指定してください +@msg the point in `points` is on `center` `points` の点が `center` と同じ位置にあります @msg direct-select two or three anchor points, or give `points` アンカーポイントを 2 つまたは 3 つダイレクト選択するか、`points` を指定してください @msg no circle passes through these points: two are the same or all three lie on one line これらの点を通る円はありません: 2 つの点が同じか、3 点すべてが一直線上にあります @msg select at least two objects オブジェクトを 2 つ以上選択してください @@ -4910,6 +4913,7 @@ swatch Bright Violet ビビッドバイオレット @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 unknown Circle tool option `{key}` 不明な円ツールオプション `{key}` @msg `{key}` must be a #rrggbb colour `{key}` は #rrggbb 形式のカラーにしてください @msg `{key}` must be a string `{key}` は文字列にしてください @msg `{key}` must be a profile name or null `{key}` はプロファイル名または null にしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0eb74ca1c0..67d8e1f880 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6348,6 +6348,7 @@ font-technology Variable ცვლადი Circle წრე Circle Tool წრის ხელსაწყო Circle too large წრე ზედმეტად დიდია + From Center ცენტრიდან Clip to Art ნახატზე მოჭრა Colorize გაფერადება Gamma გამა @@ -6831,6 +6832,8 @@ font-technology Variable ცვლადი @msg no active perspective plane აქტიური პერსპექტივის სიბრტყე არ არის @msg no anchor points selected საყრდენი წერტილები მონიშნული არ არის @msg `points` must be two or three [x, y] pairs of numbers `points` უნდა იყოს რიცხვების ორი ან სამი [x, y] წყვილი +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` უნდა იყოს რიცხვების [x, y] წყვილი, ხოლო `points` უნდა შეიცავდეს ერთ [x, y] წყვილს +@msg the point in `points` is on `center` `points`-ის წერტილი `center`-ზეა @msg direct-select two or 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 no app to open files here აქ ფაილების გასახსნელი აპი არ არის @@ -8706,6 +8709,7 @@ liquify-list-end {0}, {1} {0} და {1} @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 unknown Circle tool option `{key}` წრის ხელსაწყოს უცნობი პარამეტრი `{key}` @msg a key object sits on that point ამ წერტილზე საკვანძო ობიექტი მდებარეობს @msg a linked image can't become a gradient mesh: embed it first დაკავშირებული გამოსახულება გრადიენტულ ბადედ ვერ გადაიქცევა: ჯერ ჩააშენეთ ის @msg a mask has more than one art block ნიღაბს ერთზე მეტი ნახატის ბლოკი აქვს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 83219f8de8..e2d4dc5f97 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1289,6 +1289,7 @@ antiAlias Sharp 날카롭게 Circle 원 Circle Tool 점 기준 원 도구 Circle too large 원이 너무 큽니다 + From Center 중심에서 Clear All Tabs 모든 탭 지우기 Above Text 문자 위 Position Panel Above Text 패널을 문자 위에 배치 @@ -4773,6 +4774,8 @@ theme Appearance 외관 @msg clipboard is empty 클립보드가 비어 있습니다 @msg no anchor points selected 선택한 앵커 포인트가 없습니다 @msg `points` must be two or three [x, y] pairs of numbers `points`는 숫자 쌍 [x, y] 두 개 또는 세 개여야 합니다 +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center`는 숫자 쌍 [x, y]이고 `points`에는 [x, y] 쌍이 하나 있어야 합니다 +@msg the point in `points` is on `center` `points`의 점이 `center`에 있습니다 @msg direct-select two or 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 select at least two objects 개체를 두 개 이상 선택하세요 @@ -4837,6 +4840,7 @@ theme Appearance 외관 @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 unknown Circle tool option `{key}` 알 수 없는 점 기준 원 도구 옵션 `{key}` @msg `{key}` must be a #rrggbb colour `{key}`은(는) #rrggbb 색상이어야 합니다 @msg `{key}` must be a string `{key}`은(는) 문자열이어야 합니다 @msg `{key}` must be a profile name or null `{key}`은(는) 프로파일 이름 또는 null이어야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f40a61047c..41bef3d562 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4904,6 +4904,7 @@ font-technology Variable Variabel Circle Cirkel Circle Tool Cirkelgereedschap Circle too large Cirkel te groot + From Center Vanuit het midden Clip to Art Clippen op artwork Colorize Inkleuren Gamma Gamma @@ -5379,6 +5380,8 @@ imageTrace Outline Contour @msg no active perspective plane geen actief perspectiefvlak @msg no anchor points selected geen ankerpunten geselecteerd @msg `points` must be two or three [x, y] pairs of numbers `points` moet uit twee of drie getallenparen [x, y] bestaan +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` moet een getallenpaar [x, y] zijn, met één paar [x, y] in `points` +@msg the point in `points` is on `center` het punt in `points` ligt op `center` @msg direct-select two or three anchor points, or give `points` selecteer met directe selectie twee of drie ankerpunten of geef `points` op @msg no circle passes through these points: two are the same or all three lie on one line er gaat geen cirkel door deze punten: twee zijn gelijk of alle drie liggen op één lijn @msg no app to open files here hier is geen app om bestanden mee te openen @@ -8724,6 +8727,7 @@ swatch Bright Violet Felviolet @msg `{key}` must be a #rrggbb color or a layer color name `{key}` moet een #rrggbb-kleur of de naam van een laagkleur zijn @msg unknown Live Paint option `{key}` onbekende Live Paint-optie `{key}` @msg unknown Shape Builder option `{key}` onbekende Vormopbouw-optie `{key}` +@msg unknown Circle tool option `{key}` onbekende Cirkelgereedschap-optie `{key}` @msg a key object sits on that point op dat punt ligt een sleutelobject @msg a linked image can't become a gradient mesh: embed it first een gekoppelde afbeelding kan geen verloopraster worden: sluit deze eerst in @msg a mask has more than one art block een masker heeft meer dan één illustratieblok diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 52e33d639a..a16737d422 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4472,6 +4472,7 @@ font-technology Variable Zmienne Circle Okrąg Circle Tool Narzędzie Okrąg Circle too large Okrąg jest za duży + From Center Od środka Clip to Art Przytnij do kompozycji Colorize Koloruj Gamma Gamma @@ -4944,6 +4945,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `{key}` must be a #rrggbb color or a layer color name `{key}` musi być kolorem #rrggbb lub nazwą koloru warstwy @msg unknown Live Paint option `{key}` nieznana opcja aktywnego malowania `{key}` @msg unknown Shape Builder option `{key}` nieznana opcja kreatora kształtów `{key}` +@msg unknown Circle tool option `{key}` nieznana opcja narzędzia Okrąg `{key}` @msg `{key}` must be a #rrggbb colour `{key}` musi być kolorem #rrggbb @msg `{key}` must be a number `{key}` musi być liczbą @msg `{key}` must be a number, not {v} `{key}` musi być liczbą, nie {v} @@ -5140,6 +5142,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg no active perspective plane brak aktywnej płaszczyzny perspektywy @msg no anchor points selected nie zaznaczono punktów kontrolnych @msg `points` must be two or three [x, y] pairs of numbers `points` musi zawierać dwie lub trzy pary liczb [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` musi być parą liczb [x, y], a `points` musi zawierać jedną parę [x, y] +@msg the point in `points` is on `center` punkt w `points` leży w `center` @msg direct-select two or three anchor points, or give `points` zaznacz bezpośrednio dwa lub trzy punkty kontrolne lub podaj `points` @msg no circle passes through these points: two are the same or all three lie on one line przez te punkty nie przechodzi żaden okrąg: dwa są takie same albo wszystkie trzy leżą na jednej prostej @msg no app to open files here brak aplikacji do otwierania plików diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 5ae5b28f19..80d4379592 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -448,6 +448,7 @@ antiAlias Sharp Nítido Circle Círculo Circle Tool Ferramenta Círculo Circle too large Círculo grande demais + From Center Do centro Clean Up… Limpar… Clear Limpar Clear All Tabs Limpar Todas as Paradas de Tabulação @@ -4140,6 +4141,7 @@ axis Both Ambos @msg `{key}` must be a #rrggbb color or a layer color name `{key}` deve ser uma cor #rrggbb ou o nome de uma cor de camada @msg unknown Live Paint option `{key}` opção de Pintura ao Vivo desconhecida `{key}` @msg unknown Shape Builder option `{key}` opção do Construtor de Formas desconhecida `{key}` +@msg unknown Circle tool option `{key}` opção da Ferramenta Círculo desconhecida `{key}` @msg `{key}` must be a #rrggbb colour `{key}` deve ser uma cor #rrggbb @msg `{key}` must be a number `{key}` deve ser um número @msg `{key}` must be a number, not {v} `{key}` deve ser um número, não {v} @@ -4326,6 +4328,8 @@ axis Both Ambos @msg no active perspective plane nenhum plano de perspectiva ativo @msg no anchor points selected nenhum ponto de ancoragem selecionado @msg `points` must be two or three [x, y] pairs of numbers `points` deve ter dois ou três pares de números [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` deve ser um par de números [x, y], com um par [x, y] em `points` +@msg the point in `points` is on `center` o ponto em `points` está em `center` @msg direct-select two or three anchor points, or give `points` selecione diretamente dois ou três pontos de ancoragem ou informe `points` @msg no circle passes through these points: two are the same or all three lie on one line nenhum círculo passa por esses pontos: dois são iguais ou os três estão na mesma reta @msg no app to open files here nenhum aplicativo para abrir arquivos aqui diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3dc089a76d..d989b704ad 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -479,6 +479,7 @@ font-technology Variable Вариативные Circle Круг Circle Tool Инструмент «Круг» Circle too large Круг слишком большой + From Center От центра Classic Defaults Классические значения по умолчанию Clean Up… Очистить… Clear Очистить @@ -4850,6 +4851,7 @@ liquify-list-end {0}, {1} {0} и {1} @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 unknown Circle tool option `{key}` неизвестный параметр инструмента «Круг» `{key}` @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} @@ -5046,6 +5048,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg no active perspective plane нет активной плоскости перспективы @msg no anchor points selected опорные точки не выделены @msg `points` must be two or three [x, y] pairs of numbers `points` должен содержать две или три пары чисел [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` должен быть парой чисел [x, y], а `points` должен содержать одну пару [x, y] +@msg the point in `points` is on `center` точка в `points` совпадает с `center` @msg direct-select two or 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 no app to open files here здесь нет приложения для открытия файлов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5e852da822..b73bee10cf 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -469,6 +469,7 @@ font-technology Variable Variabla Circle Cirkel Circle Tool Cirkelverktyg Circle too large Cirkeln är för stor + From Center Från mitten Classic Defaults Klassiska standardvärden Clean Up… Rensa upp… Clear Rensa @@ -4732,6 +4733,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg `{key}` must be a #rrggbb color or a layer color name `{key}` måste vara en färg i formatet #rrggbb eller namnet på en lagerfärg @msg unknown Live Paint option `{key}` okänt alternativ för direktmålning `{key}` @msg unknown Shape Builder option `{key}` okänt alternativ för formbyggaren `{key}` +@msg unknown Circle tool option `{key}` okänt alternativ för cirkelverktyget `{key}` @msg `{key}` must be a #rrggbb colour `{key}` måste vara en färg i formatet #rrggbb @msg `{key}` must be a number `{key}` måste vara ett tal @msg `{key}` must be a number, not {v} `{key}` måste vara ett tal, inte {v} @@ -4919,6 +4921,8 @@ liquify-list-end {0}, {1} {0} och {1} @msg no active perspective plane inget aktivt perspektivplan @msg no anchor points selected inga ankarpunkter är markerade @msg `points` must be two or three [x, y] pairs of numbers `points` måste vara två eller tre talpar [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` måste vara ett talpar [x, y], med ett talpar [x, y] i `points` +@msg the point in `points` is on `center` punkten i `points` ligger på `center` @msg direct-select two or three anchor points, or give `points` direktmarkera två eller tre ankarpunkter eller ange `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går genom de här punkterna: två är samma punkt eller så ligger alla tre på en linje @msg no app to open files here det finns ingen app för att öppna filer här diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 97fccd9167..c31053c943 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -475,6 +475,23 @@ fn objects_on_path_detach_strings_are_in_complete_catalogs() { } } +/// The errors `tool.setOption` gives for the Circle tool's options (the tools crate is not one of +/// [`MESSAGE_CRATES`]) are translated in every complete-message language, with the key kept. +#[test] +fn circle_tool_option_errors_translate() { + let errors = [serde_json::json!({ "fromCenter": 1 }), serde_json::json!({ "radius": 5 })].map(|v| { + let map = v.as_object().cloned().unwrap_or_default(); + vectorcraft_tools::circle::check_options(&map).expect_err("refused") + }); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for (error, key) in errors.iter().zip(["fromCenter", "radius"]) { + let shown = message(lang, error); + assert!(shown != *error && shown.contains(key), "{code}: {shown}"); + } + } +} + /// 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 de1d7280f1..fa6f1c4cab 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -463,6 +463,7 @@ font-technology Variable Değişken Circle daire Circle Tool Daire Aracı Circle too large Daire çok büyük + From Center Merkezden Classic Defaults Klasik Varsayılanlar Clean Up… Temizleme… Clear Temizle @@ -4739,6 +4740,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg no active perspective plane aktif perspektif düzlemi yok @msg no anchor points selected bağlantı noktası seçilmedi @msg `points` must be two or three [x, y] pairs of numbers `points` iki veya üç [x, y] sayı çifti olmalıdır +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` bir [x, y] sayı çifti olmalı ve `points` bir [x, y] çifti içermelidir +@msg the point in `points` is on `center` `points` içindeki nokta `center` üzerinde @msg direct-select two or three anchor points, or give `points` iki veya üç bağlantı noktasını doğrudan seçin veya `points` verin @msg no circle passes through these points: two are the same or all three lie on one line bu noktalardan geçen bir çember yok: ikisi aynı ya da üçü de aynı doğru üzerinde @msg no app to open files here burada dosyaları açacak uygulama yok @@ -6475,6 +6478,7 @@ theme Appearance Görünüm @msg `{key}` must be a #rrggbb color or a layer color name `{key}` bir #rrggbb rengi ya da katman rengi adı olmalıdır @msg unknown Live Paint option `{key}` bilinmeyen Canlı Boyama seçeneği `{key}` @msg unknown Shape Builder option `{key}` bilinmeyen Şekil Oluşturucu seçeneği `{key}` +@msg unknown Circle tool option `{key}` bilinmeyen Daire Aracı seçeneği `{key}` @msg a key object sits on that point bu noktanın üzerinde bir anahtar nesne bulunuyor @msg a linked image can't become a gradient mesh: embed it first bağlantılı bir görüntü degrade ağına dönüştürülemez: önce görüntüyü gömün @msg a mask has more than one art block bir maskede birden fazla çizim bloğu var diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e82439dca3..c4cd777c36 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -477,6 +477,7 @@ font-technology Variable Варіативні Circle Коло Circle Tool Інструмент «Коло» Circle too large Коло завелике + From Center Від центру Classic Defaults Класичні значення за промовчанням Clean Up… Очистити… Clear Очистити @@ -4840,6 +4841,7 @@ liquify-list-end {0}, {1} {0} і {1} @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 unknown Circle tool option `{key}` невідомий параметр інструмента «Коло» `{key}` @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} @@ -5036,6 +5038,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg no active perspective plane немає активної площини перспективи @msg no anchor points selected опорні точки не виділені @msg `points` must be two or three [x, y] pairs of numbers `points` має містити дві або три пари чисел [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` має бути парою чисел [x, y], а `points` має містити одну пару [x, y] +@msg the point in `points` is on `center` точка в `points` збігається з `center` @msg direct-select two or 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 no app to open files here тут немає програми для відкриття файлів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 0f088fec2b..f9dbf1c514 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -559,6 +559,7 @@ font-technology Variable Biến thiên Circle Hình tròn Circle Tool Công cụ Hình tròn Circle too large Hình tròn quá lớn + From Center Từ tâm Classic Cổ điển Classic Defaults Mặc định cổ điển Clean Up… Dọn dẹp… @@ -4844,6 +4845,7 @@ theme Appearance Giao diện @msg `{key}` must be a #rrggbb color or a layer color name `{key}` phải là màu #rrggbb hoặc tên màu lớp @msg unknown Live Paint option `{key}` tùy chọn Tô trực tiếp không xác định `{key}` @msg unknown Shape Builder option `{key}` tùy chọn Tạo hình dạng không xác định `{key}` +@msg unknown Circle tool option `{key}` tùy chọn Công cụ Hình tròn không xác định `{key}` @msg `{key}` must be a #rrggbb colour `{key}` phải là màu #rrggbb @msg `{key}` must be a number `{key}` phải là một số @msg `{key}` must be a number, not {v} `{key}` phải là một số, không phải {v} @@ -5368,6 +5370,8 @@ liquify-list-end {0}, {1} {0} và {1} @msg no active perspective plane không có mặt phẳng phối cảnh đang hoạt động @msg no anchor points selected chưa chọn điểm neo @msg `points` must be two or three [x, y] pairs of numbers `points` phải là hai hoặc ba cặp số [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` phải là một cặp số [x, y], với một cặp [x, y] trong `points` +@msg the point in `points` is on `center` điểm trong `points` nằm tại `center` @msg direct-select two or three anchor points, or give `points` hãy chọn trực tiếp hai hoặc ba điểm neo hoặc cung cấp `points` @msg no circle passes through these points: two are the same or all three lie on one line không có đường tròn nào đi qua các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng @msg no app to open files here không có ứng dụng để mở tệp ở đây diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ed027b9f23..ebab6472b3 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -430,6 +430,7 @@ antiAlias Sharp 锐利 Circle 圆形 Circle Tool 圆形工具 Circle too large 圆形过大 + From Center 从中心 Classic Defaults 经典默认 Clean Up… 清理… Clear 清除 @@ -4544,6 +4545,8 @@ imageTrace Outline 轮廓 @msg clipboard is empty 剪贴板为空 @msg no anchor points selected 未选择锚点 @msg `points` must be two or three [x, y] pairs of numbers `points` 必须是两对或三对数字 [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` 必须是一对数字 [x, y],且 `points` 中须有一对 [x, y] +@msg the point in `points` is on `center` `points` 中的点与 `center` 重合 @msg direct-select two or 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 select at least two objects 请至少选择两个对象 @@ -6455,6 +6458,7 @@ lighting Light 光源 @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 unknown Circle tool option `{key}` 未知的圆形工具选项 `{key}` @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 无法读取图像的像素 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d5d613a7d8..35df9f4e58 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -445,6 +445,7 @@ font-technology Variable 可變 Circle 圓形 Circle Tool 圓形工具 Circle too large 圓形過大 + From Center 從中心 Classic Defaults 經典預設值 Clean Up… 清除… Clear 清除 @@ -2077,6 +2078,8 @@ file-filter Templates 範本 @msg clipboard is empty 剪貼簿是空的 @msg no anchor points selected 未選取錨點 @msg `points` must be two or three [x, y] pairs of numbers `points` 必須是兩組或三組數字 [x, y] +@msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` 必須是一組數字 [x, y],且 `points` 中須有一組 [x, y] +@msg the point in `points` is on `center` `points` 中的點與 `center` 重合 @msg direct-select two or 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 select at least two objects 請選取至少兩個物件 @@ -2986,6 +2989,7 @@ liquify-list-end {0}, {1} {0}和{1} @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 unknown Circle tool option `{key}` 未知的圓形工具選項 `{key}` @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 無法讀取影像的像素 diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 3c78f12df0..32bc9a02fa 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -495,10 +495,10 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result Date: Tue, 17 Nov 2026 17:26:49 -0800 Subject: [PATCH 002/101] Shapes: a centered Circle tool release draws the circle it shows With From Center, a second press moved less than 2 screen points now draws the outline through the pointer the preview follows, not through the point of the press. A second click on the center still places nothing. --- crates/tools/src/circle.rs | 5 +++-- crates/tools/src/circle/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 8f16210542..99ec88f6e7 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -285,9 +285,10 @@ impl Tool for CircleTool { // a drag from there draws the circle on the diameter it drags out. (Some(Press::Second { on_first: true, dragged: false, .. }), ..) => vec![], (Some(Press::Second { on_first: true, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, c]), + // From a center: the outline passes through the point the tool shows it on, where + // the drag ends or, within DRAG_PX of the press, where the pointer last was. + (Some(Press::Second { .. }), Some(a), Some(c)) if self.centered => self.draw(&[a, c]), (Some(Press::Second { at, dragged: false, .. }), Some(a), _) => self.draw(&[a, at]), - // From a center: the outline passes through the point the drag ends on. - (Some(Press::Second { dragged: true, .. }), Some(a), Some(c)) if self.centered => self.draw(&[a, c]), // Three points: Alt's rounding of the diameter does not apply. (Some(Press::Second { snapped, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, snapped, c]), _ => vec![], diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index 0b2336f278..32875b186d 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -409,6 +409,27 @@ fn from_center_two_clicks_draw_the_circle_through_the_second() { assert_eq!(drag(&mut t, &cx, (330.0, 340.0), &[(360.0, 300.0)], Mods::default()), centered((300.0, 300.0), (360.0, 300.0))); } +/// With From Center, the release draws the circle the tool shows: a drag from the center ends +/// where it is let go, and a second press moved less than 2 screen points draws the outline +/// through the pointer, not through the point of the press. +#[test] +fn from_center_the_release_draws_the_circle_shown() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (400.0, 300.0), Mods::default())), centered((300.0, 300.0), (400.0, 300.0))); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (330.0, 340.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (331.0, 340.0), Mods::default())); + let shown = preview(&t.overlays(&cx)).expect("the circle is shown"); + let r = Point::new(300.0, 300.0).distance(Point::new(331.0, 340.0)); + assert!(near(shown, Rect::new(300.0 - r, 300.0 - r, 300.0 + r, 300.0 + r)), "{:?}", t.overlays(&cx)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (331.0, 340.0), Mods::default())), centered((300.0, 300.0), (331.0, 340.0))); +} + /// With From Center, Shift keeps the point at 45° steps from the center, and Alt rounds the /// diameter, twice the radius, to the rulers' ticks (every 5 pt at 100% in points). #[test] From 199860918da1564683b902db67761f9b79d6a6d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 17:51:19 -0800 Subject: [PATCH 003/101] Shapes: shape.circleThroughPoints refuses a null center --- crates/engine/src/cmd/create.rs | 5 +++-- crates/engine/src/tests/circle_through.rs | 6 ++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 7a5a3633af..88e40c229c 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -419,8 +419,9 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { fn circle_through_points(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.circleThroughPoints"; const SAME: &str = "no circle passes through these points: two are the same or all three lie on one line"; - let (center, radius) = match p.get("center").filter(|v| !v.is_null()) { - // From a center: the circle at `center` whose edge passes through the one point. + let (center, radius) = match p.get("center") { + // From a center: the circle at `center` whose edge passes through the one point. A null + // `center` is refused, as a null `points` with a center is. Some(c) => { let one = p.get("points").and_then(Value::as_array).and_then(|v| match v.as_slice() { [q] => pair(q), diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index 462838a979..ef504538db 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -126,8 +126,8 @@ fn two_points_are_the_ends_of_a_diameter() { /// With `center`, the circle is centered there and its edge passes through the one point in /// `points`: from the bottom-right corner (200, 200) of a 100 pt square through its top-left /// corner (100, 100), the radius is the square's diagonal, in one undo step. A point on the center -/// and a circle past the canvas are refused, and so is a `center` or `points` that is not one -/// `[x, y]` pair of finite numbers; nothing is drawn and no undo step is recorded. +/// and a circle past the canvas are refused, and so is a `center` (null included) or `points` that +/// is not one `[x, y]` pair of finite numbers; nothing is drawn and no undo step is recorded. #[test] fn a_center_and_a_point_on_the_edge_give_the_circle() { let mut s = session(); @@ -157,6 +157,8 @@ fn a_center_and_a_point_on_the_edge_give_the_circle() { (json!([0]), json!([[10, 0]])), (json!("0,0"), json!([[10, 0]])), (json!([0, 0, 1]), json!([[10, 0]])), + (Value::Null, json!([[10, 0]])), + (Value::Null, json!([[10, 0], [20, 0]])), ] { let e = s.execute(C, &json!({ "center": center, "points": points })).unwrap_err().to_string(); assert!(e.contains("`center` must be an [x, y] pair of numbers, with one [x, y] pair in `points`"), "{center} {points}: {e}"); From 35d64a18a6c4866792b13012128c649f7dd5af4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 17:12:04 -0800 Subject: [PATCH 004/101] Shapes: Circle tool review fixes for From Center - tool.setOption accepts fromCenter again: the Circle tool implements check_option, which the shared option check now calls for every tool. - A drag from the first point that comes back within 2 screen points of the press draws the circle the tool shows. A drag to no circle draws nothing and leaves no point pending. - shape.circleThroughPoints refuses a circle whose opposite edges round to the same number at its coordinates, and the tool no longer shows such a circle. The error is translated in every complete-message catalog. - An option set during a press (tool.setOption, the Control bar) is kept when the press is dropped, with the options that write reset. --- crates/engine/src/cmd/create.rs | 6 ++++- crates/engine/src/tests/circle_through.rs | 14 +++++++++++ crates/engine/src/tests/toolsettings.rs | 26 ++++++++++++++++++++ crates/engine/src/tooling.rs | 29 +++++++++++++++++++++- crates/tools/src/circle.rs | 22 ++++++++++++++--- crates/tools/src/circle/tests.rs | 30 +++++++++++++++++++++++ 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/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 4 ++- 31 files changed, 148 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index b7d84d28b2..7d0a8db3ba 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -71,7 +71,7 @@ pub fn specs() -> Vec { "Circle Through Points", [], None, - "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), center?: [x, y] (the circle's center; `points` then holds the one point its edge passes through, [[x, y]])} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, a point on `center`, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", + "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), center?: [x, y] (the circle's center; `points` then holds the one point its edge passes through, [[x, y]])} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, a point on `center`, three on one line, a circle reaching past the canvas, or one too small for its edges to differ at its coordinates are an error, and nothing is drawn", has_doc, circle_through_points ), @@ -455,6 +455,10 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result { } }; let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); + // A radius below the step between doubles at the center leaves opposite edges on one number. + if !(r.width() > 0.0 && r.height() > 0.0) { + return Err(bad(C, "the circle is too small to draw at these coordinates")); + } let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; // Not pixel-aligned: the circle stays through the points. let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?; diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index ef504538db..f841b56a61 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -166,6 +166,20 @@ fn a_center_and_a_point_on_the_edge_give_the_circle() { assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); } +/// A circle so small beside its coordinates that its left and right edges round to the same +/// number (radius 10⁻¹¹ pt at x = 1,048,576, where doubles step by about 2.3 × 10⁻¹⁰) is refused, +/// from a center and on a diameter alike; nothing is drawn and no undo step is recorded. +#[test] +fn a_circle_with_no_width_at_document_precision_is_refused() { + let mut s = session(); + let (undo, count) = (undo_len(&s), object_count(&s)); + for p in [json!({"center": [1_048_576, 0], "points": [[1_048_576, 1e-11]]}), json!({"points": [[1_048_576, 0], [1_048_576, 2e-11]]})] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains("the circle is too small to draw at these coordinates"), "{p}: {e}"); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + /// Points that are not two or three pairs of finite numbers are an error, not a fallback. #[test] fn malformed_points_are_refused() { diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 7afdb80aef..42209b6ab1 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -48,6 +48,32 @@ fn circle_from_center_persists() { assert_eq!(next.tool_options(), json!({"fromCenter": true})); } +/// An option set during a press (`tool.setOption`, or a Control bar change) is kept when the press +/// is dropped: the drop gives back only what the press itself changed. +#[test] +fn an_option_set_during_a_dropped_press_is_kept() { + let v = ViewInfo::default(); + let mut s = session(); + select(&mut s, "circle"); + s.set_tool_option("fromCenter", &json!(true)); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": false})).unwrap(); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options(), json!({"fromCenter": false})); + assert_eq!(s.prefs.tool_settings["circle"]["fromCenter"], json!(false)); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.set_tool_option("fromCenter", &json!(true)); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options(), json!({"fromCenter": true})); + assert_eq!(s.prefs.tool_settings["circle"]["fromCenter"], json!(true)); + // Setting a Parametric Shape's kind also puts its numbers back to that kind's: those are kept too. + select(&mut s, "parametricShape"); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + let set = s.set_tool_option_cmd(&json!({"key": "kind", "value": "star"})).unwrap(); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options(), set); +} + #[test] fn options_survive_a_tool_switch() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index b144087b6f..19d262117f 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -605,7 +605,8 @@ impl Session { /// Escape, as during a drag, for most tools), and a release returns the tool to rest. Of what /// the tool asks for along the way, only a cancel and a notify run, so a marquee selects /// nothing and a click opens no size dialog. The tool gets back the persistent options it had - /// when the press began, and none of the press's changes to them are stored. A dropped Type + /// when the press began, and none of the press's changes to them are stored; an option set on + /// it during the press (`tool.setOption`, the Control bar) is kept. A dropped Type /// press restores the prior selection. The freeform gradient point selected once the tool /// took the press is selected again. A press held while the tool computes an edit on another /// thread has not reached the tool: it is removed from the held input with the pointer events @@ -1303,9 +1304,31 @@ impl Session { if key == "queue" && self.tool.id() == "place" { self.note_place_queue_roots(); } + let was = self.tool.options(); self.tool.set_option(key, v); self.tool_set_since_reset = true; self.keep_tool_settings(); + self.keep_option_writes_past_a_dropped_press(&was, [key]); + } + + /// Options set on the active tool during a press are written into the options the press began + /// with, so a dropped press ([`Self::drop_tool_press`]) gives back only what the press changed: + /// the options `keys` names, and every other option the write changed from `was` (setting a + /// Parametric Shape's `kind` resets its numbers). + fn keep_option_writes_past_a_dropped_press<'a>(&mut self, was: &Value, keys: impl IntoIterator) { + let now = self.tool.options(); + if let Some((id, before)) = self.press_options.as_mut() + && id == self.tool.id() + { + let keys: Vec<&str> = keys.into_iter().collect(); + for (key, slot) in before.iter_mut() { + if let Some(v) = now.get(key) + && (keys.contains(&key.as_str()) || was.get(key) != Some(v)) + { + *slot = v.clone(); + } + } + } } /// Keep the automation roots in force now as those the place cursor's queue, being loaded, @@ -1359,6 +1382,7 @@ impl Session { // kind puts the shape's other numbers back to that kind's, and those given with it are its. let first = |k: &str| k == "queue" || k == "kind"; let ordered = || values.iter().filter(|(k, _)| first(k)).chain(values.iter().filter(|(k, _)| !first(k))); + let was = self.tool.options(); let mut other = (!active).then(|| self.make_tool(id.unwrap_or_default())); let t = other.as_deref_mut().unwrap_or(self.tool.as_mut()); for (k, v) in ordered() { @@ -1387,6 +1411,9 @@ impl Session { let set = other.id(); Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store)); } + if active { + self.keep_option_writes_past_a_dropped_press(&was, values.keys().map(String::as_str)); + } out } diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 99ec88f6e7..388cdab4fb 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -82,9 +82,10 @@ fn command(points: &[Point], centered: bool) -> (String, Value) { } } -/// Is the circle at `c` with radius `r` inside the canvas? +/// Is the circle at `c` with radius `r` inside the canvas, with its opposite edges on different +/// numbers (as `shape.circleThroughPoints` requires)? fn on_canvas(c: Point, r: f64) -> bool { - [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD) + [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD) && c.x - r < c.x + r && c.y - r < c.y + r } /// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints` @@ -275,8 +276,16 @@ impl Tool for CircleTool { vec![] } PointerKind::Up => match (self.press.take(), self.first, self.pointer) { - (Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]), - // A click places the first point; the guides of the press go. + // Once the press has moved DRAG_PX, the release draws the circle the tool shows, also + // where the pointer came back nearer the press; where it shows none, the release + // draws nothing and starts afresh. + (Some(Press::First { at, dragged: true, .. }), _, Some(b)) + if b.distance(at) >= cx.tol(DRAG_PX) || circle_for(&[at, b], self.centered).is_some() => + { + self.draw(&[at, b]) + } + // A click, or a drag back onto the press, places the first point; the guides of the + // press go. (Some(Press::First { .. }), ..) => { self.snap.clear(); vec![] @@ -310,6 +319,11 @@ impl Tool for CircleTool { } } + /// [`check_options`] for one option. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + check_options(&Map::from_iter([(key.to_string(), value.clone())])) + } + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { if key == ToolKey::Escape { self.clear(); diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index 32875b186d..e8377dc478 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -430,6 +430,28 @@ fn from_center_the_release_draws_the_circle_shown() { assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (331.0, 340.0), Mods::default())), centered((300.0, 300.0), (331.0, 340.0))); } +/// Once a press has moved 2 screen points, its release draws the circle the tool shows, also when +/// the pointer comes back nearer than that: from a center and on a diameter. A drag back onto the +/// press itself shows no circle and places the first point, as a click does. +#[test] +fn a_drag_brought_back_near_its_press_draws_the_circle_shown() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (301.0, 300.0)], Mods::default()), centered((300.0, 300.0), (301.0, 300.0))); + assert!(!t.ends_on_escape(&cx), "no center is left pending"); + let mut t = CircleTool::default(); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (301.0, 300.0)], Mods::default()), circle(&[(300.0, 300.0), (301.0, 300.0)])); + assert!(!t.ends_on_escape(&cx)); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (300.0, 300.0)], Mods::default()), vec![]); + assert!(t.ends_on_escape(&cx), "the first point is placed"); + t.key(&cx, ToolKey::Escape, Mods::default()); + // A drag to a circle past the canvas draws nothing and leaves no point behind. + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(4.1e6, 300.0)], Mods::default()), vec![]); + assert!(!t.ends_on_escape(&cx), "nothing is left pending"); +} + /// With From Center, Shift keeps the point at 45° steps from the center, and Alt rounds the /// diameter, twice the radius, to the rulers' ticks (every 5 pt at 100% in points). #[test] @@ -467,6 +489,10 @@ fn from_center_holds_for_the_circle_being_drawn() { assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)])); assert_eq!(circle_for(&[Point::new(1.0, 1.0), Point::new(1.0, 1.0)], true), None); assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true)); + // Edges that round to one number at document precision, as `shape.circleThroughPoints` refuses. + let x = 1_048_576.0; + assert_eq!(circle_for(&[Point::new(x, 0.0), Point::new(x, 1e-11)], true), None); + assert_eq!(circle_of(&[Point::new(x, 0.0), Point::new(x, 2e-11)]), None); t.set_option("fromCenter", &json!("yes")); assert_eq!(t.options(), json!({ "fromCenter": false }), "a value that is not true or false is ignored"); } @@ -478,6 +504,10 @@ fn the_options_are_checked() { assert_eq!(check_options(&map(json!({ "fromCenter": true }))), Ok(())); assert_eq!(check_options(&map(json!({ "fromCenter": 1 }))), Err("`fromCenter` must be true or false".into())); assert_eq!(check_options(&map(json!({ "radius": 5 }))), Err("unknown Circle tool option `radius`".into())); + let t = CircleTool::default(); + assert_eq!(t.check_option("fromCenter", &json!(false)), Ok(())); + assert_eq!(t.check_option("fromCenter", &json!(1)), Err("`fromCenter` must be true or false".into())); + assert_eq!(t.check_option("radius", &json!(5)), Err("unknown Circle tool option `radius`".into())); } /// The tool is in the Ellipse tool's group, after the Ellipse tool. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index fdf1c5c881..bb588caef8 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6609,6 +6609,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `points` must be two or three [x, y] pairs of numbers `points` han de ser dos o tres parells de nombres [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` ha de ser un parell de nombres [x, y], amb un parell [x, y] a `points` @msg the point in `points` is on `center` el punt de `points` és a `center` +@msg the circle is too small to draw at these coordinates el cercle és massa petit per dibuixar-lo en aquestes coordenades @msg direct-select two or three anchor points, or give `points` seleccioneu directament dos o tres punts d’ancoratge o indiqueu `points` @msg no circle passes through these points: two are the same or all three lie on one line cap cercle no passa per aquests punts: dos són iguals o tots tres són en una mateixa recta @msg no app to open files here aquí no hi ha cap aplicació per obrir fitxers diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6b79156ede..4664964b19 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5511,6 +5511,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg `points` must be two or three [x, y] pairs of numbers `points` musí být dvě nebo tři dvojice čísel [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` musí být dvojice čísel [x, y] a `points` musí obsahovat jednu dvojici [x, y] @msg the point in `points` is on `center` bod v `points` leží na `center` +@msg the circle is too small to draw at these coordinates kruh je na těchto souřadnicích příliš malý na vykreslení @msg direct-select two or three anchor points, or give `points` vyberte přímým výběrem dva nebo tři kotevní body, nebo zadejte `points` @msg no circle passes through these points: two are the same or all three lie on one line těmito body neprochází žádná kružnice: dva jsou stejné nebo všechny tři leží na jedné přímce @msg no app to open files here zde chybí aplikace pro otevírání souborů diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 3b1edf35e0..9811af3cc9 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7685,6 +7685,7 @@ imageTrace Outline Kontur @msg `points` must be two or three [x, y] pairs of numbers `points` skal være to eller tre talpar [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` skal være et talpar [x, y], med ét talpar [x, y] i `points` @msg the point in `points` is on `center` punktet i `points` ligger på `center` +@msg the circle is too small to draw at these coordinates cirklen er for lille til at tegne ved disse koordinater @msg direct-select two or three anchor points, or give `points` direkte markér to eller tre ankerpunkter, eller angiv `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går gennem disse punkter: to er ens, eller alle tre ligger på én linje @msg no app to open files here ingen app til at åbne filer her diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 97b9689e89..f924c7cae0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5106,6 +5106,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg `points` must be two or three [x, y] pairs of numbers `points` muss aus zwei oder drei Zahlenpaaren [x, y] bestehen @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` muss ein Zahlenpaar [x, y] sein, mit einem Paar [x, y] in `points` @msg the point in `points` is on `center` der Punkt in `points` liegt auf `center` +@msg the circle is too small to draw at these coordinates der Kreis ist zu klein, um ihn an diesen Koordinaten zu zeichnen @msg direct-select two or three anchor points, or give `points` wählen Sie zwei oder drei Ankerpunkte direkt aus oder geben Sie `points` an @msg no circle passes through these points: two are the same or all three lie on one line durch diese Punkte verläuft kein Kreis: zwei sind gleich oder alle drei liegen auf einer Linie @msg no app to open files here hier gibt es keine App zum Öffnen von Dateien diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 708fdbdea6..5023e79736 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5163,6 +5163,7 @@ digits Malayalam Μαλαγιάλαμ @msg `points` must be two or three [x, y] pairs of numbers το `points` πρέπει να είναι δύο ή τρία ζεύγη αριθμών [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` το `center` πρέπει να είναι ένα ζεύγος αριθμών [x, y], με ένα ζεύγος [x, y] στο `points` @msg the point in `points` is on `center` το σημείο στο `points` βρίσκεται πάνω στο `center` +@msg the circle is too small to draw at these coordinates ο κύκλος είναι πολύ μικρός για να σχεδιαστεί σε αυτές τις συντεταγμένες @msg direct-select two or 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 no app to open files here δεν υπάρχει εφαρμογή για άνοιγμα αρχείων εδώ diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5a9f2c6745..b24ca7345e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5218,6 +5218,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `points` must be two or three [x, y] pairs of numbers `points` debe ser dos o tres pares de números [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` debe ser un par de números [x, y], con un par [x, y] en `points` @msg the point in `points` is on `center` el punto de `points` está en `center` +@msg the circle is too small to draw at these coordinates el círculo es demasiado pequeño para dibujarlo en estas coordenadas @msg direct-select two or three anchor points, or give `points` seleccione directamente dos o tres puntos de ancla o indique `points` @msg no circle passes through these points: two are the same or all three lie on one line ningún círculo pasa por estos puntos: dos son iguales o los tres están en una misma línea @msg no app to open files here aquí no hay ninguna aplicación para abrir archivos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 939fba5136..369fd5c84d 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5429,6 +5429,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `points` must be two or three [x, y] pairs of numbers `points` on annettava kahtena tai kolmena lukuparina [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` on annettava lukuparina [x, y], ja `points` sisältää yhden lukuparin [x, y] @msg the point in `points` is on `center` `points`-kohdan piste on `center`-kohdassa +@msg the circle is too small to draw at these coordinates ympyrä on liian pieni piirrettäväksi näissä koordinaateissa @msg direct-select two or three anchor points, or give `points` valitse suoraan kaksi tai kolme ankkuripistettä tai anna `points` @msg no circle passes through these points: two are the same or all three lie on one line näiden pisteiden kautta ei kulje ympyrää: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla @msg no app to open files here täällä ei ole sovellusta tiedostojen avaamiseen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e176a346f5..54451dc567 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5177,6 +5177,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `points` must be two or three [x, y] pairs of numbers `points` doit contenir deux ou trois paires de nombres [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` doit être une paire de nombres [x, y], avec une paire [x, y] dans `points` @msg the point in `points` is on `center` le point de `points` est sur `center` +@msg the circle is too small to draw at these coordinates le cercle est trop petit pour être dessiné à ces coordonnées @msg direct-select two or three anchor points, or give `points` sélectionnez deux ou trois points d’ancrage avec l’outil Sélection directe, ou indiquez `points` @msg no circle passes through these points: two are the same or all three lie on one line aucun cercle ne passe par ces points : deux sont identiques ou les trois sont alignés @msg no app to open files here aucune application pour ouvrir des fichiers ici diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 55a8d59b38..c153796e96 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8113,6 +8113,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg `points` must be two or three [x, y] pairs of numbers `points` में संख्याओं के दो या तीन [x, y] जोड़े होने चाहिए @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` संख्याओं का एक [x, y] जोड़ा होना चाहिए, और `points` में एक [x, y] जोड़ा होना चाहिए @msg the point in `points` is on `center` `points` का बिंदु `center` पर है +@msg the circle is too small to draw at these coordinates इन निर्देशांकों पर बनाने के लिए वृत्त बहुत छोटा है @msg direct-select two or 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 no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f4c96c7a18..cce0dd257b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5882,6 +5882,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg `points` must be two or three [x, y] pairs of numbers a `points` két vagy három [x, y] számpár legyen @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` a `center` egy [x, y] számpár legyen, a `points` pedig egy [x, y] párt tartalmazzon @msg the point in `points` is on `center` a `points` pontja a `center` helyén van +@msg the circle is too small to draw at these coordinates a kör túl kicsi ahhoz, hogy ezeken a koordinátákon megrajzolható legyen @msg direct-select two or three anchor points, or give `points` jelölj ki közvetlen kijelöléssel két vagy három horgonypontot, vagy add meg a `points` értéket @msg no circle passes through these points: two are the same or all three lie on one line ezeken a pontokon nem halad át kör: kettő egybeesik, vagy mindhárom egy egyenesen van @msg no app to open files here itt nincs fájlmegnyitó alkalmazás diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index e19aacb767..e9367355da 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5244,6 +5244,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `points` must be two or three [x, y] pairs of numbers `points` deve essere composto da due o tre coppie di numeri [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` deve essere una coppia di numeri [x, y], con una coppia [x, y] in `points` @msg the point in `points` is on `center` il punto in `points` si trova su `center` +@msg the circle is too small to draw at these coordinates il cerchio è troppo piccolo per essere disegnato a queste coordinate @msg direct-select two or three anchor points, or give `points` seleziona con Selezione diretta due o tre punti di ancoraggio oppure indica `points` @msg no circle passes through these points: two are the same or all three lie on one line nessun cerchio passa per questi punti: due coincidono oppure tutti e tre sono allineati @msg no app to open files here nessuna app per aprire file qui diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59566c624e..0068177ecf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5006,6 +5006,7 @@ variable-list-end {0}, {1} {0}、{1} @msg `points` must be two or three [x, y] pairs of numbers `points` は 2 組または 3 組の数値 [x, y] にしてください @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` は数値の組 [x, y] にし、`points` には [x, y] を 1 組指定してください @msg the point in `points` is on `center` `points` の点が `center` と同じ位置にあります +@msg the circle is too small to draw at these coordinates 円が小さすぎるため、この座標には描画できません @msg direct-select two or three anchor points, or give `points` アンカーポイントを 2 つまたは 3 つダイレクト選択するか、`points` を指定してください @msg no circle passes through these points: two are the same or all three lie on one line これらの点を通る円はありません: 2 つの点が同じか、3 点すべてが一直線上にあります @msg select at least two objects オブジェクトを 2 つ以上選択してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2efcf36d22..c087fe47a4 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6970,6 +6970,7 @@ font-technology Variable ცვლადი @msg `points` must be two or three [x, y] pairs of numbers `points` უნდა იყოს რიცხვების ორი ან სამი [x, y] წყვილი @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` უნდა იყოს რიცხვების [x, y] წყვილი, ხოლო `points` უნდა შეიცავდეს ერთ [x, y] წყვილს @msg the point in `points` is on `center` `points`-ის წერტილი `center`-ზეა +@msg the circle is too small to draw at these coordinates წრე ძალიან პატარაა ამ კოორდინატებზე დასახატად @msg direct-select two or 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 no app to open files here აქ ფაილების გასახსნელი აპი არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 8a842f9b71..f60b5a4eb7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4935,6 +4935,7 @@ variable-list-end {0}, {1} {0} 및 {1} @msg `points` must be two or three [x, y] pairs of numbers `points`는 숫자 쌍 [x, y] 두 개 또는 세 개여야 합니다 @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center`는 숫자 쌍 [x, y]이고 `points`에는 [x, y] 쌍이 하나 있어야 합니다 @msg the point in `points` is on `center` `points`의 점이 `center`에 있습니다 +@msg the circle is too small to draw at these coordinates 원이 너무 작아 이 좌표에서 그릴 수 없습니다 @msg direct-select two or 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 select at least two objects 개체를 두 개 이상 선택하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 27092ebd7d..001884c62b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5560,6 +5560,7 @@ imageTrace Outline Contour @msg `points` must be two or three [x, y] pairs of numbers `points` moet uit twee of drie getallenparen [x, y] bestaan @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` moet een getallenpaar [x, y] zijn, met één paar [x, y] in `points` @msg the point in `points` is on `center` het punt in `points` ligt op `center` +@msg the circle is too small to draw at these coordinates de cirkel is te klein om op deze coördinaten te tekenen @msg direct-select two or three anchor points, or give `points` selecteer met directe selectie twee of drie ankerpunten of geef `points` op @msg no circle passes through these points: two are the same or all three lie on one line er gaat geen cirkel door deze punten: twee zijn gelijk of alle drie liggen op één lijn @msg no app to open files here hier is geen app om bestanden mee te openen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index c26579b579..a2e7599dc5 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5328,6 +5328,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `points` must be two or three [x, y] pairs of numbers `points` musi zawierać dwie lub trzy pary liczb [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` musi być parą liczb [x, y], a `points` musi zawierać jedną parę [x, y] @msg the point in `points` is on `center` punkt w `points` leży w `center` +@msg the circle is too small to draw at these coordinates okrąg jest zbyt mały, aby go narysować w tych współrzędnych @msg direct-select two or three anchor points, or give `points` zaznacz bezpośrednio dwa lub trzy punkty kontrolne lub podaj `points` @msg no circle passes through these points: two are the same or all three lie on one line przez te punkty nie przechodzi żaden okrąg: dwa są takie same albo wszystkie trzy leżą na jednej prostej @msg no app to open files here brak aplikacji do otwierania plików diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 461b2b188e..9a946817dc 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4474,6 +4474,7 @@ axis Both Ambos @msg `points` must be two or three [x, y] pairs of numbers `points` deve ter dois ou três pares de números [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` deve ser um par de números [x, y], com um par [x, y] em `points` @msg the point in `points` is on `center` o ponto em `points` está em `center` +@msg the circle is too small to draw at these coordinates o círculo é pequeno demais para ser desenhado nessas coordenadas @msg direct-select two or three anchor points, or give `points` selecione diretamente dois ou três pontos de ancoragem ou informe `points` @msg no circle passes through these points: two are the same or all three lie on one line nenhum círculo passa por esses pontos: dois são iguais ou os três estão na mesma reta @msg no app to open files here nenhum aplicativo para abrir arquivos aqui diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3833801529..cd4b6a34ce 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5239,6 +5239,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg `points` must be two or three [x, y] pairs of numbers `points` должен содержать две или три пары чисел [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` должен быть парой чисел [x, y], а `points` должен содержать одну пару [x, y] @msg the point in `points` is on `center` точка в `points` совпадает с `center` +@msg the circle is too small to draw at these coordinates круг слишком мал, чтобы нарисовать его в этих координатах @msg direct-select two or 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 no app to open files here здесь нет приложения для открытия файлов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 486ad17e33..479b960195 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5103,6 +5103,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg `points` must be two or three [x, y] pairs of numbers `points` måste vara två eller tre talpar [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` måste vara ett talpar [x, y], med ett talpar [x, y] i `points` @msg the point in `points` is on `center` punkten i `points` ligger på `center` +@msg the circle is too small to draw at these coordinates cirkeln är för liten för att ritas vid dessa koordinater @msg direct-select two or three anchor points, or give `points` direktmarkera två eller tre ankarpunkter eller ange `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går genom de här punkterna: två är samma punkt eller så ligger alla tre på en linje @msg no app to open files here det finns ingen app för att öppna filer här diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 17f712e5e9..847aa2c502 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4931,6 +4931,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `points` must be two or three [x, y] pairs of numbers `points` iki veya üç [x, y] sayı çifti olmalıdır @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` bir [x, y] sayı çifti olmalı ve `points` bir [x, y] çifti içermelidir @msg the point in `points` is on `center` `points` içindeki nokta `center` üzerinde +@msg the circle is too small to draw at these coordinates daire bu koordinatlarda çizilemeyecek kadar küçük @msg direct-select two or three anchor points, or give `points` iki veya üç bağlantı noktasını doğrudan seçin veya `points` verin @msg no circle passes through these points: two are the same or all three lie on one line bu noktalardan geçen bir çember yok: ikisi aynı ya da üçü de aynı doğru üzerinde @msg no app to open files here burada dosyaları açacak uygulama yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0da8c07841..a9419f974e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5228,6 +5228,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg `points` must be two or three [x, y] pairs of numbers `points` має містити дві або три пари чисел [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` має бути парою чисел [x, y], а `points` має містити одну пару [x, y] @msg the point in `points` is on `center` точка в `points` збігається з `center` +@msg the circle is too small to draw at these coordinates коло занадто мале, щоб намалювати його в цих координатах @msg direct-select two or 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 no app to open files here тут немає програми для відкриття файлів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4c77ae1c5b..d11f1f4ff0 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5575,6 +5575,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg `points` must be two or three [x, y] pairs of numbers `points` phải là hai hoặc ba cặp số [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` phải là một cặp số [x, y], với một cặp [x, y] trong `points` @msg the point in `points` is on `center` điểm trong `points` nằm tại `center` +@msg the circle is too small to draw at these coordinates hình tròn quá nhỏ để vẽ tại các tọa độ này @msg direct-select two or three anchor points, or give `points` hãy chọn trực tiếp hai hoặc ba điểm neo hoặc cung cấp `points` @msg no circle passes through these points: two are the same or all three lie on one line không có đường tròn nào đi qua các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng @msg no app to open files here không có ứng dụng để mở tệp ở đây diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 4602582363..7f3734ae01 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4701,6 +4701,7 @@ imageTrace Outline 轮廓 @msg `points` must be two or three [x, y] pairs of numbers `points` 必须是两对或三对数字 [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` 必须是一对数字 [x, y],且 `points` 中须有一对 [x, y] @msg the point in `points` is on `center` `points` 中的点与 `center` 重合 +@msg the circle is too small to draw at these coordinates 圆太小,无法在这些坐标处绘制 @msg direct-select two or 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 select at least two objects 请至少选择两个对象 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 8adc28406f..fc73a5308d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2152,6 +2152,7 @@ file-filter Templates 範本 @msg `points` must be two or three [x, y] pairs of numbers `points` 必須是兩組或三組數字 [x, y] @msg `center` must be an [x, y] pair of numbers, with one [x, y] pair in `points` `center` 必須是一組數字 [x, y],且 `points` 中須有一組 [x, y] @msg the point in `points` is on `center` `points` 中的點與 `center` 重合 +@msg the circle is too small to draw at these coordinates 圓太小,無法在這些座標處繪製 @msg direct-select two or 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 select at least two objects 請選取至少兩個物件 diff --git a/docs/mcp.md b/docs/mcp.md index eb1c620a22..8b86caa800 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6699,7 +6699,9 @@ out and the selection does not hold two or three anchor points of paths. `shape.circleThroughPoints {center: [x, y], points: [[x, y]]}` draws the circle centered at `center` whose edge passes through the one point in `points`: its radius is the distance between them. It returns an error and draws nothing when the point is on `center`, when the circle would reach past the canvas, and when `center` is not a pair of numbers or -`points` does not hold exactly one pair. With `center`, the selected anchor points are not used. +`points` does not hold exactly one pair. With `center`, the selected anchor points are not used. With or without +`center`, a circle whose radius is so small beside its coordinates that its opposite edges round to the same number is +an error, and nothing is drawn. The Circle tool, after the Ellipse tool in its toolbar group, draws with this command. A drag from one point to another, or a click on each, draws the circle with the two points as the ends of a diameter. A click on a first point, From 0a74c7d0c2ab635655ed476c5d1ee3c6c885099a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 14:11:17 -0800 Subject: [PATCH 005/101] Shapes: a Circle tool release near the press keeps the press's point from a center too A second press from a center let go within 2 screen points of the press showed the circle through the pointer but drew it through the press, and the tests for a drag brought back near its press asked for the opposite of the click rule on main. The preview of such a press now shows the pressed point until it has been dragged, and the tests follow the rule that a first press let go near its press places the first point. --- crates/tools/src/circle.rs | 12 ++++++------ crates/tools/src/circle/tests.rs | 24 +++++++++++------------- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index e68a4d85c7..456d27f947 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -165,8 +165,9 @@ impl CircleTool { Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())), // A press on the first point adds no point: a drag from it drags out a diameter. Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)), - // From a center, the second point follows the pointer. - Some(Press::Second { .. }) if self.centered => out.extend(self.pointer), + // From a center, the second point follows the pointer once the press has been dragged; + // until then it is the pressed point, which a release within DRAG_PX draws through. + Some(Press::Second { dragged: true, .. }) if self.centered => out.extend(self.pointer), Some(Press::Second { at, dragged: false, .. }) => out.push(at), Some(Press::Second { snapped, dragged: true, .. }) => { out.push(snapped); @@ -296,9 +297,8 @@ impl Tool for CircleTool { vec![] } PointerKind::Up => match (self.press.take(), self.first, self.pointer) { - // Once the press has moved DRAG_PX, the release draws the circle the tool shows, also - // where the pointer came back nearer the press; where it shows none, the release - // draws nothing and starts afresh. + // A release DRAG_PX or more from the press draws the circle the tool shows; where it + // shows none, the release draws nothing and starts afresh. (Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) || circle_for(&[at, b], self.centered).is_some() => { @@ -315,7 +315,7 @@ impl Tool for CircleTool { (Some(Press::Second { on_first: true, dragged: false, .. }), ..) => vec![], (Some(Press::Second { on_first: true, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, c]), // From a center: the outline passes through the point the tool shows it on, where - // the drag ends or, within DRAG_PX of the press, where the pointer last was. + // the drag ends or, within DRAG_PX of the press, the pressed point. (Some(Press::Second { .. }), Some(a), Some(c)) if self.centered => self.draw(&[a, c]), (Some(Press::Second { at, dragged: false, .. }), Some(a), _) => self.draw(&[a, at]), // Three points: Alt's rounding of the diameter does not apply. diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index c075d715a5..d9354a96fd 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -473,8 +473,8 @@ fn from_center_two_clicks_draw_the_circle_through_the_second() { } /// With From Center, the release draws the circle the tool shows: a drag from the center ends -/// where it is let go, and a second press moved less than 2 screen points draws the outline -/// through the pointer, not through the point of the press. +/// where it is let go, and a second press moved less than 2 screen points shows and draws the +/// outline through the point of the press. #[test] fn from_center_the_release_draws_the_circle_shown() { let (d, _) = doc_with_rect(); @@ -488,26 +488,24 @@ fn from_center_the_release_draws_the_circle_shown() { t.pointer(&cx, &ev(PointerKind::Down, (330.0, 340.0), Mods::default())); t.pointer(&cx, &ev(PointerKind::Drag, (331.0, 340.0), Mods::default())); let shown = preview(&t.overlays(&cx)).expect("the circle is shown"); - let r = Point::new(300.0, 300.0).distance(Point::new(331.0, 340.0)); + let r = Point::new(300.0, 300.0).distance(Point::new(330.0, 340.0)); assert!(near(shown, Rect::new(300.0 - r, 300.0 - r, 300.0 + r, 300.0 + r)), "{:?}", t.overlays(&cx)); - assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (331.0, 340.0), Mods::default())), centered((300.0, 300.0), (331.0, 340.0))); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (331.0, 340.0), Mods::default())), centered((300.0, 300.0), (330.0, 340.0))); } -/// Once a press has moved 2 screen points, its release draws the circle the tool shows, also when -/// the pointer comes back nearer than that: from a center and on a diameter. A drag back onto the -/// press itself shows no circle and places the first point, as a click does. +/// A first press let go within 2 screen points of where it was pressed is a click also after a +/// drag that came back to it, from a center and on a diameter: it places the first point. #[test] -fn a_drag_brought_back_near_its_press_draws_the_circle_shown() { +fn a_first_press_dragged_back_near_its_press_places_the_first_point() { let (d, _) = doc_with_rect(); let (s, p) = (Selection::default(), paint()); let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; let mut t = from_center(); - assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (301.0, 300.0)], Mods::default()), centered((300.0, 300.0), (301.0, 300.0))); - assert!(!t.ends_on_escape(&cx), "no center is left pending"); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (301.0, 300.0)], Mods::default()), vec![]); + assert!(t.ends_on_escape(&cx), "the center is placed"); + assert_eq!(click(&mut t, &cx, (380.0, 300.0)), centered((300.0, 300.0), (380.0, 300.0))); let mut t = CircleTool::default(); - assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (301.0, 300.0)], Mods::default()), circle(&[(300.0, 300.0), (301.0, 300.0)])); - assert!(!t.ends_on_escape(&cx)); - assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (300.0, 300.0)], Mods::default()), vec![]); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (301.0, 300.0)], Mods::default()), vec![]); assert!(t.ends_on_escape(&cx), "the first point is placed"); t.key(&cx, ToolKey::Escape, Mods::default()); // A drag to a circle past the canvas draws nothing and leaves no point behind. From 6c1eb02a57a544e6105721f86d5df49dba1f6fcf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 07:06:06 -0800 Subject: [PATCH 006/101] Circle: From Center tests compare against the Circle Tool Options defaults The two Circle From Center tests in the engine's tool settings compared the tool's options with {"fromCenter": ...} alone. Since the Circle tool also reports the Circle Tool Options (center, radii, diameter, color, standardAnchors and dragThird), the tests take the options the tool starts with and check that only fromCenter changes. --- crates/engine/src/tests/toolsettings.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 96d75a78a7..998d88dbff 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -35,17 +35,19 @@ fn blob_tip_options_report_and_persist() { fn circle_from_center_persists() { let mut s = session(); select(&mut s, "circle"); - assert_eq!(s.tool_options(), json!({"fromCenter": false})); + let mut want = s.tool_options(); + assert_eq!(want["fromCenter"], json!(false)); + want["fromCenter"] = json!(true); s.set_tool_option("fromCenter", &json!(true)); select(&mut s, "selection"); select(&mut s, "circle"); - assert_eq!(s.tool_options(), json!({"fromCenter": true})); + assert_eq!(s.tool_options(), want); select(&mut s, "selection"); let saved = serde_json::to_string(&s.prefs).unwrap(); let mut next = session(); next.apply_prefs(serde_json::from_str(&saved).unwrap()); select(&mut next, "circle"); - assert_eq!(next.tool_options(), json!({"fromCenter": true})); + assert_eq!(next.tool_options(), want); } /// An option set during a press (`tool.setOption`, or a Control bar change) is kept when the press @@ -55,16 +57,19 @@ fn the_circle_from_center_set_during_a_dropped_press_is_kept() { let v = ViewInfo::default(); let mut s = session(); select(&mut s, "circle"); + let mut want = s.tool_options(); s.set_tool_option("fromCenter", &json!(true)); s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": false})).unwrap(); s.drop_tool_press(v).unwrap(); - assert_eq!(s.tool_options(), json!({"fromCenter": false})); + want["fromCenter"] = json!(false); + assert_eq!(s.tool_options(), want); assert_eq!(s.prefs.tool_settings["circle"]["fromCenter"], json!(false)); s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); s.set_tool_option("fromCenter", &json!(true)); s.drop_tool_press(v).unwrap(); - assert_eq!(s.tool_options(), json!({"fromCenter": true})); + want["fromCenter"] = json!(true); + assert_eq!(s.tool_options(), want); assert_eq!(s.prefs.tool_settings["circle"]["fromCenter"], json!(true)); // Setting a Parametric Shape's kind also puts its numbers back to that kind's: those are kept too. select(&mut s, "parametricShape"); From 9c643e302e320a632a3fa578d152624c60e6dcfe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:41:56 -0800 Subject: [PATCH 007/101] Tests: canvas tests that compare renders keep the proof view while they run The proof view is process-wide, and the Proof Setup dialog tests turn Proof Colors on while other tests run. A change between two renders of a canvas test made the frames differ, and a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution failed in full runs of the crate's tests. The Proof Setup tests' lock is now a read-write lock, and keeping_color_settings holds it for reading. --- crates/ui-egui/src/canvas/tests.rs | 2 ++ crates/ui-egui/src/dialogs/proof_setup.rs | 14 ++++++++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..1922842acd 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3059,7 +3059,9 @@ fn the_art_renders_within_the_largest_texture_side() { /// Run a test that compares two renders with the color settings that are active when it starts. /// A test on another thread can change the process's active settings; this thread keeps its own. +/// The proof view is process-wide, so the tests that change it wait until this one ends. fn keeping_color_settings(test: fn()) { + let _view = crate::dialogs::proof_setup::tests::keeping_the_proof_view(); vectorcraft_color::cms::with_active(vectorcraft_color::cms::active(), test); } diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs index 44350ac659..735fafaaef 100644 --- a/crates/ui-egui/src/dialogs/proof_setup.rs +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -492,18 +492,19 @@ pub fn saved_items() -> Vec { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use vectorcraft_engine::Session; /// Proof views are process-wide: these tests take turns, and each leaves the default view. - static VIEW: std::sync::Mutex<()> = std::sync::Mutex::new(()); + /// Tests that compare renders hold it for reading ([`keeping_the_proof_view`]). + static VIEW: std::sync::RwLock<()> = std::sync::RwLock::new(()); - struct DefaultView<'a>(#[allow(dead_code)] std::sync::MutexGuard<'a, ()>); + struct DefaultView<'a>(#[allow(dead_code)] std::sync::RwLockWriteGuard<'a, ()>); impl DefaultView<'_> { fn new() -> Self { - let g = VIEW.lock().unwrap_or_else(|e| e.into_inner()); + let g = VIEW.write().unwrap_or_else(|e| e.into_inner()); proof::set_view(Default::default()); DefaultView(g) } @@ -515,6 +516,11 @@ mod tests { } } + /// Keeps the proof view as it is while the guard lives: the tests here wait to change it. + pub(crate) fn keeping_the_proof_view() -> std::sync::RwLockReadGuard<'static, ()> { + VIEW.read().unwrap_or_else(|e| e.into_inner()) + } + fn frame(app: &mut VectorcraftApp, ctx: &egui::Context) { let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); out.textures_delta.clear(); From b2e390f18f0ec48f0125920e70fd73a8149f7445 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:40:50 -0800 Subject: [PATCH 008/101] Save for Web: Transparency Dither makes a share of partly transparent pixels clear With Transparency on, GIF and PNG-8 now offer Transparency Dither: No Transparency Dither (the default, the half-opacity cut as before), Diffusion with an Amount, Pattern and Noise. The help page describes the four methods and the Diffusion amount: https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400 - render: `clear_mask` decides which pixels take the transparent entry. Diffusion spreads the opacity error Floyd-Steinberg style over two rows, scaled by the amount; Pattern uses the 8x8 ordered matrix and Noise a fixed coordinate hash, so the same art always gives the same file. Fully clear and fully opaque pixels do not change. `quantize_locked`, `quantize_to`, `nearest_entries` and the fixed-palette path use it. - engine: `document.exportForWeb`, its preview, `webExport.settings` and presets take `transparencyDither` (none, diffusion, pattern, noise) and `transparencyDitherAmount` (0 to 100, default 100). An unknown method or an amount over 100 is refused; settings saved without the keys take the defaults. - ui: the Transparency Dither row sits under Transparency, with an Amount slider for Diffusion; both are disabled while Transparency is off and keep their values. Rows for the five labels are in every complete catalog. The matrix, the noise, the amount mapping and the defaults' combination with the matte are VectorCraft's own rules. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/colorcmds.rs | 11 +- crates/engine/src/cmd/fileio/encode.rs | 1 + crates/engine/src/cmd/webexport.rs | 20 ++- crates/engine/src/tests/webexport.rs | 86 +++++++++++++ crates/render/src/encode/quantize.rs | 119 ++++++++++++++---- crates/render/src/encode/tests_palette.rs | 78 +++++++++++- crates/ui-egui/src/dialogs/save_for_web.rs | 22 +++- .../ui-egui/src/dialogs/tests_save_for_web.rs | 55 ++++++++ crates/ui-egui/src/i18n/bg.tsv | 5 + crates/ui-egui/src/i18n/bs.tsv | 5 + crates/ui-egui/src/i18n/ca.tsv | 5 + crates/ui-egui/src/i18n/cs.tsv | 5 + crates/ui-egui/src/i18n/da.tsv | 5 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 5 + crates/ui-egui/src/i18n/es.tsv | 5 + crates/ui-egui/src/i18n/fi.tsv | 5 + crates/ui-egui/src/i18n/fr.tsv | 5 + crates/ui-egui/src/i18n/gu.tsv | 5 + crates/ui-egui/src/i18n/hi.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 5 + crates/ui-egui/src/i18n/id.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 5 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ka.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/nl.tsv | 5 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 5 + crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/sv.tsv | 5 + crates/ui-egui/src/i18n/tests.rs | 12 ++ crates/ui-egui/src/i18n/tr.tsv | 5 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/vi.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 5 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + docs/mcp.md | 13 +- docs/target-app-parity.md | 1 + 39 files changed, 522 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index a9dee00af3..4be925b0cd 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -701,8 +701,15 @@ impl Indexing { v.as_f64().filter(|x| (0.0..=100.0).contains(x)).ok_or_else(|| bad(C, "`ditherAmount` must be a number from 0 to 100"))?.round() as u8 } }; - let options = - |r: Reduction| PaletteOptions { colors: colors.unwrap_or(256), reduction: r, dither, dither_amount, transparency: true, matte: None }; + let options = |r: Reduction| PaletteOptions { + colors: colors.unwrap_or(256), + reduction: r, + dither, + dither_amount, + transparency: true, + matte: None, + ..PaletteOptions::default() + }; let refuse_colors = |name: &str| match colors { Some(_) => Err(bad(C, format!("`colors` does not apply to the {name} reduction"))), None => Ok(()), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 1ecb41290e..23b7a1c13f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -348,6 +348,7 @@ impl RasterOptions { Some(v) => background(v).map_err(|e| bad(C, format!("matte: {e}")))?, None => Some([255; 3]), }, + ..PaletteOptions::default() }, tiff: TiffOptions { color_model, diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 498982a7f9..e9d480c5eb 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Save for Web", [], None, - "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", + "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (gif/png8 with transparency: partly transparent pixels become transparent or keep their color in a dither, about as many keeping it as their opacity says with pattern, noise or diffusion at amount 100; fully transparent and opaque pixels do not change), transparencyDitherAmount?: 100 (0–100: the diffusion dither's strength, a lower amount closer to none, 0 as none), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", has_doc, export ), @@ -398,6 +398,12 @@ pub struct WebSettings { pub dither_amount: u8, /// Keep transparent pixels transparent (GIF, PNG-8, PNG-24). pub transparency: bool, + /// GIF and PNG-8 with `transparency`: how partly transparent pixels are split between the + /// transparent entry and their color (`none`: under half opacity is transparent). + #[serde(serialize_with = "ser_key", deserialize_with = "de_key")] + pub transparency_dither: Dither, + /// 0–100: the strength of the `diffusion` transparency dither. + pub transparency_dither_amount: u8, /// What partly transparent edges blend into (JPEG and opaque PNG-24: the background): `white`, /// `black`, `none` or `#rrggbb`. pub matte: String, @@ -444,6 +450,8 @@ impl Default for WebSettings { dither: Dither::Diffusion, dither_amount: 100, transparency: true, + transparency_dither: Dither::None, + transparency_dither_amount: 100, matte: "white".into(), interlaced: false, web_snap: 0, @@ -492,6 +500,10 @@ impl WebSettings { fn checked(mut self) -> std::result::Result { self.colors = self.colors.clamp(2, 256); self.dither_amount = self.dither_amount.min(100); + if self.transparency_dither_amount > 100 { + let key = "transparencyDitherAmount"; + return Err(format!("`{key}` must be from 0 to 100")); + } self.web_snap = self.web_snap.min(100); self.lossy = self.lossy.min(100); self.quality = self.quality.min(100); @@ -799,6 +811,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 dither_amount: s.dither_amount, transparency: s.transparency, matte, + transparency_dither: s.transparency_dither, + transparency_dither_amount: s.transparency_dither_amount, }; let mut ix = reduced(rgba, w, h, s, &o, &kept)?; // Map to transparent works on the colours the reduction made. @@ -889,7 +903,7 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc return Ok(quantize::quantize_to(rgba, w, h, o, &left)); } // A fixed palette holds at most `colors` entries, the transparent one included. - let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128); + let has_clear = quantize::clear_mask(rgba, w, o).contains(&true); let removed = custom.iter().any(|c| deleted.contains(c)); let mut left: Vec<[u8; 3]> = vec![]; for c in custom { @@ -941,7 +955,7 @@ fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; return; } let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect(); - let near = quantize::nearest_entries(rgba, o, &all); + let near = quantize::nearest_entries(rgba, ix.width, o, &all); if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) { return; } diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index fe3deecbef..34d8cd41dd 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -163,6 +163,92 @@ fn gif_transparency_index_and_map_to_transparent() { assert_eq!(pixels(&gif).get_pixel(25, 15)[3], 0, "index {i}"); } +/// 40×30: red at 25% opacity on the left half, blue at 75% on the right, nothing behind them. +fn see_through() -> Session { + let mut s = session(40.0, 30.0); + rect(&mut s, [0.0, 0.0, 20.0, 30.0], "#ff0000"); + run(&mut s, "transparency.set", json!({"opacity": 25})); + rect(&mut s, [20.0, 0.0, 20.0, 30.0], "#0000ff"); + run(&mut s, "transparency.set", json!({"opacity": 75})); + s +} + +/// The shares of the left and right halves' pixels that are opaque. +fn opaque_halves(img: &image::RgbaImage) -> [f64; 2] { + [0, 20].map(|x0| (x0..x0 + 20).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| img.get_pixel(x, y)[3] == 255).count() as f64 / 600.0) +} + +#[test] +fn transparency_dither_keeps_a_share_of_partly_transparent_pixels() { + let mut s = see_through(); + for format in ["gif", "png8"] { + let file = |s: &mut Session, extra: Value| { + let mut p = json!({"format": format, "antiAlias": "none"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + one(s, p) + }; + // By default the pixels under half opacity are transparent and the others opaque. + let none = file(&mut s, json!({})); + assert_eq!(opaque_halves(&pixels(&none)), [0.0, 1.0], "{format}"); + assert_eq!(file(&mut s, json!({"transparencyDither": "none"})), none, "{format}"); + assert_eq!(file(&mut s, json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}"); + for method in ["diffusion", "pattern", "noise"] { + let p = json!({"transparencyDither": method}); + let dithered = file(&mut s, p.clone()); + let [left, right] = opaque_halves(&pixels(&dithered)); + assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}"); + if format == "gif" { + assert_eq!(gif_transparent_index(&dithered), Some(0), "{method}"); + } + assert_eq!(file(&mut s, p.clone()), dithered, "{format} {method}: the same art gives the same file"); + // The preview shows what Save writes. + let mut pv = json!({"format": format, "antiAlias": "none", "image": true}); + pv["transparencyDither"] = json!(method); + let shown = run(&mut s, "document.exportForWeb.preview", pv); + assert_eq!(vectorcraft_format::base64_decode(shown["dataBase64"].as_str().unwrap()).unwrap(), dithered, "{format} {method}"); + // Without transparency the dither does nothing. + let opaque = file(&mut s, json!({"transparencyDither": method, "transparency": false})); + assert_eq!(opaque, file(&mut s, json!({"transparency": false})), "{format} {method}"); + } + // A fixed palette keeps the transparent entry for the dithered pixels. + let fixed = file(&mut s, json!({"transparencyDither": "pattern", "colorTable": {"customPalette": ["#ffbfbf", "#4040ff"]}})); + let [left, right] = opaque_halves(&pixels(&fixed)); + assert!(left > 0.0 && left < 1.0 && right > 0.0 && right < 1.0, "{format}: {left} {right}"); + } +} + +#[test] +fn transparency_dither_settings_are_checked_and_remembered() { + let mut s = see_through(); + for bad in [ + json!({"transparencyDither": "spray"}), + json!({"transparencyDither": 3}), + json!({"transparencyDitherAmount": 101}), + json!({"transparencyDitherAmount": -1}), + ] { + assert!(s.execute("document.exportForWeb", &bad).is_err(), "{bad}"); + assert!(s.execute("webExport.settings", &bad).is_err(), "{bad}"); + } + let e = s.execute("document.exportForWeb", &json!({"transparencyDitherAmount": 101})).unwrap_err().to_string(); + assert!(e.contains("`transparencyDitherAmount` must be from 0 to 100"), "{e}"); + assert_eq!(defaults()["transparencyDither"], "none"); + assert_eq!(defaults()["transparencyDitherAmount"], 100); + // The remembered settings and a saved preset keep both. + let set = run(&mut s, "webExport.settings", json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40})); + assert_eq!((&set["settings"]["transparencyDither"], &set["settings"]["transparencyDitherAmount"]), (&json!("diffusion"), &json!(40))); + let read = run(&mut s, "webExport.settings", json!({})); + assert_eq!(read["settings"], set["settings"]); + run(&mut s, "webExport.presets.save", json!({"name": "Soft edges", "transparencyDither": "noise", "transparencyDitherAmount": 60})); + let list = run(&mut s, "webExport.presets.list", json!({})); + let saved = list["presets"].as_array().unwrap().iter().find(|p| p["name"] == "Soft edges").unwrap(); + assert_eq!((&saved["settings"]["transparencyDither"], &saved["settings"]["transparencyDitherAmount"]), (&json!("noise"), &json!(60))); + let by_preset = one(&mut s, json!({"preset": "Soft edges", "format": "gif", "antiAlias": "none"})); + assert_eq!(by_preset, one(&mut s, json!({"format": "gif", "antiAlias": "none", "transparencyDither": "noise", "transparencyDitherAmount": 60}))); + // Settings saved before the keys existed take the defaults. + let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"format": "png8", "dither": "pattern"})).unwrap(); + assert_eq!((old.transparency_dither.id(), old.transparency_dither_amount), ("none", 100)); +} + #[test] fn jpeg_size_grows_with_quality() { let mut s = many_colours(); diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index fff66aa142..96b9ffe338 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -1,8 +1,9 @@ //! Colour reduction for palette formats (PNG-8, GIF): a palette of at most 256 colours chosen by //! median cut over a 15-bit histogram (refined by a few k-means passes) or a fixed palette, then //! each pixel mapped to its nearest entry with optional dithering (Floyd–Steinberg diffusion, an -//! 8×8 ordered pattern, or noise). Pixels under half opacity can become one transparent entry; -//! the others are blended over the matte colour. +//! 8×8 ordered pattern, or noise). Pixels under half opacity can become one transparent entry, or +//! with a transparency dither a share of the partly transparent pixels that follows their +//! opacity; the others are blended over the matte color. use std::collections::HashMap; @@ -111,11 +112,18 @@ pub struct PaletteOptions { pub dither: Dither, /// Dither strength 0–100. pub dither_amount: u8, - /// Pixels under half opacity become a transparent entry; otherwise every pixel is opaque. + /// Pixels under half opacity become a transparent entry (see `transparency_dither`); + /// otherwise every pixel is opaque. pub transparency: bool, /// The colour partly transparent pixels are blended over. `None`: with transparency, they /// keep their own colour (hard edges); without, white. pub matte: Option<[u8; 3]>, + /// With `transparency`, how partly transparent pixels are split between the transparent entry + /// and their color ([`clear_mask`]); `Dither::None` cuts them at half opacity. + pub transparency_dither: Dither, + /// The strength of the diffusion transparency dither, 0–100 (0 cuts at half opacity); the + /// pattern and noise methods do not use it. + pub transparency_dither_amount: u8, } impl Default for PaletteOptions { @@ -127,6 +135,8 @@ impl Default for PaletteOptions { dither_amount: 100, transparency: true, matte: Some([255; 3]), + transparency_dither: Dither::None, + transparency_dither_amount: 100, } } } @@ -153,12 +163,12 @@ pub fn quantize(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions) -> Ind /// them all anyway; locked colours no pixel ends up using are left out. pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, locked: &[[u8; 3]]) -> Indexed { let px = rgba.as_chunks::<4>().0; - let clear = |p: &[u8; 4]| o.transparency && p[3] < 128; + let clear = clear_mask(rgba, width, o); let matte = o.matte.unwrap_or([255; 3]); let colors = opaque_colors(px, o, matches!(o.reduction, Reduction::Gray | Reduction::BlackWhite)); - let has_clear = px.iter().any(clear); + let has_clear = clear.contains(&true); let k = (o.colors.clamp(2, 256) as usize - usize::from(has_clear)).max(1); - let opaque = || colors.iter().zip(px).filter(|(_, p)| !clear(p)).map(|(c, _)| *c); + let opaque = || colors.iter().zip(&clear).filter(|(_, c)| !**c).map(|(c, _)| *c); // Locked colours take their slots first (at least one is left for the reduction). let mut lock: Vec<[u8; 3]> = Vec::with_capacity(locked.len().min(k)); for c in locked { @@ -185,7 +195,7 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, if palette.is_empty() { palette.push(matte); } - finish(px, &colors, width, height, &palette, o, if exact { Dither::None } else { o.dither }) + finish(&clear, &colors, width, height, &palette, o, if exact { Dither::None } else { o.dither }) } /// [`quantize`] to the fixed `palette`: each pixel takes its nearest entry, with `o`'s dither, @@ -195,27 +205,82 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Indexed { let px = rgba.as_chunks::<4>().0; let colors = opaque_colors(px, o, false); - let has_clear = o.transparency && px.iter().any(|p| p[3] < 128); + let clear = clear_mask(rgba, width, o); + let has_clear = clear.contains(&true); let mut palette: Vec<[u8; 3]> = palette.iter().take(256 - usize::from(has_clear)).copied().collect(); if palette.is_empty() { palette.push(o.matte.unwrap_or([255; 3])); } - finish(px, &colors, width, height, &palette, o, o.dither) + finish(&clear, &colors, width, height, &palette, o, o.dither) } -/// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures -/// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a -/// pixel that becomes transparent, and for every pixel when `palette` is empty. -pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec> { +/// For each pixel of `rgba` (`width` pixels a row), the entry of `palette` nearest its color, as +/// [`quantize_to`] measures it (the matte, transparency and `o.reduction`'s distance weights) +/// without dither; `None` for a pixel that becomes transparent ([`clear_mask`]), and for every +/// pixel when `palette` is empty. +pub fn nearest_entries(rgba: &[u8], width: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec> { let px = rgba.as_chunks::<4>().0; let colors = opaque_colors(px, o, false); + let clear = clear_mask(rgba, width, o); let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect(); let index = PaletteIndex::new(&pal, o.reduction.weights()); - colors - .iter() - .zip(px) - .map(|(c, p)| if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(c.map(f32::from))) }) - .collect() + colors.iter().zip(&clear).map(|(c, &clear)| if pal.is_empty() || clear { None } else { Some(index.nearest(c.map(f32::from))) }).collect() +} + +/// Which pixels of `rgba` (`width` pixels a row) become the transparent entry. Without +/// `o.transparency`, none. Otherwise fully transparent pixels always do and opaque ones never; a +/// partly transparent pixel does under half opacity with no transparency dither, and else by +/// `o.transparency_dither`. With pattern, noise, or diffusion at amount 100, about as many of an +/// area's pixels stay opaque as its opacity says; a lower diffusion amount moves the result toward +/// the cut at half opacity. Diffusion spreads each pixel's opacity error to the pixels right of it +/// and below it (Floyd–Steinberg, scaled by `o.transparency_dither_amount`), pattern compares the +/// opacity with the 8×8 ordered pattern and noise with a noise threshold. The result depends only +/// on the pixels and the options, so exports are reproducible. +pub fn clear_mask(rgba: &[u8], width: u32, o: &PaletteOptions) -> Vec { + let px = rgba.as_chunks::<4>().0; + if !o.transparency { + return vec![false; px.len()]; + } + let width = (width as usize).min(px.len()).max(1); + let amount = f32::from(o.transparency_dither_amount.min(100)) / 100.0; + let dither = match o.transparency_dither { + Dither::Diffusion if amount == 0.0 => Dither::None, + d => d, + }; + // Two rows of opacity error for diffusion (the current one and the next), one pixel of margin + // on each side. + let mut err = vec![0f32; if dither == Dither::Diffusion { 2 * (width + 2) } else { 0 }]; + let half = err.len() / 2; + let mut out = Vec::with_capacity(px.len()); + for (y, row) in px.chunks(width).enumerate() { + let (cur, next) = err.split_at_mut(half); + next.fill(0.0); + for (x, p) in row.iter().enumerate() { + let a = f32::from(p[3]); + let clear = match (p[3], dither) { + (0, _) => true, + (255, _) => false, + (_, Dither::None) => p[3] < 128, + (_, Dither::Pattern) => a < 255.0 * bayer(x % 8, y % 8), + // Another noise than the color dither's, so the two do not line up. + (_, Dither::Noise) => a < 255.0 * noise(x ^ 0x5a5a, y ^ 0xa5a5), + (_, Dither::Diffusion) => { + let v = a + cur[x + 1]; + let clear = v < 127.5; + let e = (v - if clear { 0.0 } else { 255.0 }) * amount; + // 7/16 right, 3/16 below left, 5/16 below, 1/16 below right. + cur[x + 2] += e * 7.0 / 16.0; + next[x] += e * 3.0 / 16.0; + next[x + 1] += e * 5.0 / 16.0; + next[x + 2] += e / 16.0; + clear + } + }; + out.push(clear); + } + cur.copy_from_slice(next); + } + out } /// The color of each pixel when opaque: blended over the matte, and gray when `gray`. @@ -231,20 +296,20 @@ fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> .collect() } -/// Map the pixels `px` (their opaque `colors`) to `palette` with `dither`, then drop the entries -/// no pixel uses and put the transparent entry first when a pixel is transparent. -fn finish(px: &[[u8; 4]], colors: &[[u8; 3]], width: u32, height: u32, palette: &[[u8; 3]], o: &PaletteOptions, dither: Dither) -> Indexed { - let clear = |p: &[u8; 4]| o.transparency && p[3] < 128; +/// Map the pixels (their opaque `colors`, transparent where `clear` says) to `palette` with +/// `dither`, then drop the entries no pixel uses and put the transparent entry first when a pixel +/// is transparent. +fn finish(clear: &[bool], colors: &[[u8; 3]], width: u32, height: u32, palette: &[[u8; 3]], o: &PaletteOptions, dither: Dither) -> Indexed { + let clear = |i: usize| clear.get(i).copied().unwrap_or(false); let matte = o.matte.unwrap_or([255; 3]); - let has_clear = px.iter().any(clear); + let has_clear = (0..colors.len()).any(clear); let weights = o.reduction.weights(); // (A width past the pixels there are would size the error rows from a number nothing checked.) - let mut indices = - map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, |i| clear(&px[i])); + let mut indices = map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, clear); // Drop the entries no pixel uses (fixed palettes), keeping the order. let mut used = [false; 256]; for (i, &ix) in indices.iter().enumerate() { - if !clear(&px[i]) { + if !clear(i) { used[ix as usize] = true; } } @@ -260,7 +325,7 @@ fn finish(px: &[[u8; 4]], colors: &[[u8; 3]], width: u32, height: u32, palette: } } for (i, ix) in indices.iter_mut().enumerate() { - *ix = if clear(&px[i]) { 0 } else { remap[*ix as usize] }; + *ix = if clear(i) { 0 } else { remap[*ix as usize] }; } Indexed { width, height, palette: kept, transparent: has_clear.then_some(0), indices } } diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index d9a8a2fc0f..8a377190f8 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -3,7 +3,7 @@ use vectorcraft_doc::{Appearance, Node}; use vectorcraft_geom::shapes; use super::png::{PngOptions, encode_indexed}; -use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, quantize, quantize_to}; +use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, clear_mask, nearest_entries, quantize, quantize_to}; use super::*; /// A `w`×`h` opaque image of `f(x, y)` colours. @@ -252,3 +252,79 @@ fn ids_round_trip() { assert_eq!(Dither::from_id(d.id()), Some(d)); } } + +/// A `w`×`h` red image whose pixels have the opacity `alpha(x, y)`. +fn see_through(w: u32, h: u32, alpha: impl Fn(u32, u32) -> u8) -> Vec { + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| [255, 0, 0, alpha(x, y)]).collect() +} + +/// The share of the pixels of `ix` that are not transparent. +fn opaque_share(ix: &Indexed) -> f64 { + ix.indices.iter().filter(|&&i| ix.transparent != Some(i)).count() as f64 / ix.indices.len() as f64 +} + +fn alpha_dither(d: Dither, amount: u8) -> PaletteOptions { + PaletteOptions { transparency_dither: d, transparency_dither_amount: amount, ..Default::default() } +} + +#[test] +fn transparency_dither_keeps_about_as_many_pixels_as_their_opacity() { + let (w, h) = (32, 32); + for alpha in [64u8, 128, 191] { + let px = see_through(w, h, |_, _| alpha); + // No transparency dither cuts at half opacity, and so does Diffusion at 0. + let none = quantize(&px, w, h, &alpha_dither(Dither::None, 100)); + assert_eq!(opaque_share(&none), if alpha < 128 { 0.0 } else { 1.0 }, "none at {alpha}"); + assert_eq!(quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 0)), none, "diffusion at 0, {alpha}"); + for d in [Dither::Diffusion, Dither::Pattern, Dither::Noise] { + let ix = quantize(&px, w, h, &alpha_dither(d, 100)); + let share = opaque_share(&ix); + assert!((share - f64::from(alpha) / 255.0).abs() < 0.08, "{d:?} at {alpha}: {share}"); + assert_eq!(ix.transparent, Some(0), "{d:?} at {alpha}"); + // The same pixels and options give the same image. + assert_eq!(quantize(&px, w, h, &alpha_dither(d, 100)), ix, "{d:?} at {alpha}"); + // A fixed palette and the nearest entries make the same pixels transparent. + let fixed = quantize_to(&px, w, h, &alpha_dither(d, 100), &[[255, 0, 0], [0, 0, 255]]); + assert_eq!(opaque_share(&fixed), share, "{d:?} at {alpha}, fixed palette"); + let near = nearest_entries(&px, w, &alpha_dither(d, 100), &[[255, 0, 0]]); + let mask = clear_mask(&px, w, &alpha_dither(d, 100)); + assert_eq!(near.iter().map(Option::is_none).collect::>(), mask, "{d:?} at {alpha}"); + } + // Diffusion at half strength keeps fewer pixels of a light area opaque than at full. + if alpha < 128 { + let half = opaque_share(&quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 50))); + let full = opaque_share(&quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 100))); + assert!(0.0 < half && half < full, "{alpha}: {half} {full}"); + } + } + // The methods arrange the pixels differently. + let px = see_through(w, h, |_, _| 96); + let masks: Vec> = [Dither::Diffusion, Dither::Pattern, Dither::Noise].map(|d| clear_mask(&px, w, &alpha_dither(d, 100))).into(); + assert!(masks[0] != masks[1] && masks[1] != masks[2] && masks[0] != masks[2]); +} + +#[test] +fn transparency_dither_leaves_clear_and_opaque_pixels_and_needs_transparency() { + let (w, h) = (16, 8); + // Fully transparent on the left, opaque on the right: every method keeps them as they are. + let hard = see_through(w, h, |x, _| if x < 8 { 0 } else { 255 }); + let none = clear_mask(&hard, w, &alpha_dither(Dither::None, 100)); + assert_eq!(none.iter().filter(|c| **c).count(), 64); + for d in Dither::ALL { + assert_eq!(clear_mask(&hard, w, &alpha_dither(d, 100)), none, "{d:?}"); + } + // Without transparency nothing is transparent, whatever the transparency dither. + let soft = see_through(w, h, |x, _| (x * 16) as u8); + for d in Dither::ALL { + let o = PaletteOptions { transparency: false, ..alpha_dither(d, 100) }; + assert!(!clear_mask(&soft, w, &o).contains(&true), "{d:?}"); + assert_eq!(quantize(&soft, w, h, &o).transparent, None, "{d:?}"); + } + // A palette of two entries keeps one for the transparent pixels and one for the others. + let o = PaletteOptions { colors: 2, ..alpha_dither(Dither::Pattern, 100) }; + let ix = quantize(&see_through(w, h, |_, _| 128), w, h, &o); + assert_eq!((ix.palette.len(), ix.transparent), (2, Some(0))); + // No pixels, and a width past the pixels there are. + assert!(clear_mask(&[], 0, &alpha_dither(Dither::Diffusion, 100)).is_empty()); + assert_eq!(clear_mask(&see_through(3, 1, |_, _| 200), 1000, &alpha_dither(Dither::Diffusion, 100)).len(), 3); +} diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 7376973d6f..f141e4bef8 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -1,7 +1,7 @@ //! File → Export → Save for Web (Legacy) (`saveForWeb`, Ctrl/Cmd+Alt+Shift+S): the art previewed //! as the web image Save writes, beside the original (Original, Optimized, 2-Up and 4-Up views, //! each with its file size and download time), and the settings: format (GIF, JPEG, PNG-8, -//! PNG-24), colour reduction, colours, dither, transparency and matte, interlacing, web snap, +//! PNG-24), color reduction, colors, dither, transparency and its dither, matte, interlacing, web snap, //! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort, Delete Color, //! Restore Generated Table, a double-click that shifts a color to one picked in the Color Picker, //! and Unshift All Colors), image size and anti-aliasing, Clip to Artboard, sRGB, metadata, @@ -823,6 +823,7 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& slider_row(ui, d, "ditherAmount", tl!("Amount:"), "%"); } check_pair(ui, d, ("transparency", tl!("Transparency")), ("interlaced", tl!("Interlaced"))); + transparency_dither_rows(ui, d); matte_row(ui, d); slider_row(ui, d, "webSnap", tl!("Web Snap:"), "%"); if format == WebFormat::Gif { @@ -1083,6 +1084,25 @@ fn slider_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, suffix: }); } +/// The Transparency Dither choices of GIF and PNG-8, as (`transparencyDither` value, label). +pub(crate) const TRANSPARENCY_DITHERS: [(&str, &str); 4] = [ + ("none", "No Transparency Dither"), + ("diffusion", "Diffusion Transparency Dither"), + ("pattern", "Pattern Transparency Dither"), + ("noise", "Noise Transparency Dither"), +]; + +/// Transparency Dither and, for Diffusion, its Amount; both are disabled while Transparency is off +/// and keep their values. +fn transparency_dither_rows(ui: &mut egui::Ui, d: &mut Dialog) { + ui.add_enabled_ui(d.bool("transparency"), |ui| { + form::choice(ui, d, "transparencyDither", &crate::i18n::colon(tl!("Transparency Dither")), (LABEL_W, FIELD_W), &TRANSPARENCY_DITHERS); + if Dither::from_id(&d.str("transparencyDither")) == Some(Dither::Diffusion) { + slider_row(ui, d, "transparencyDitherAmount", tl!("Amount:"), "%"); + } + }); +} + /// The palette size: the usual counts, or any 2–256. fn colors_row(ui: &mut egui::Ui, d: &mut Dialog) { widgets::label_row(ui, tl!("Colors:"), LABEL_W, |ui| { diff --git a/crates/ui-egui/src/dialogs/tests_save_for_web.rs b/crates/ui-egui/src/dialogs/tests_save_for_web.rs index 63ed3e2ded..69de7dd031 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -255,6 +255,61 @@ fn every_view_and_format_draws() { assert_eq!(kind(&app), Some(save_for_web::KIND)); } +/// GIF and PNG-8 show Transparency Dither under Transparency, with an Amount slider for Diffusion; +/// both are disabled while Transparency is off and keep their values, PNG-24 does not show them, and +/// Done remembers them. +#[test] +fn transparency_dither_rows_follow_transparency_and_the_method() { + use egui::accesskit::Role; + use egui_kittest::kittest::{By, NodeT, Queryable}; + type H<'a> = egui_kittest::Harness<'a, VectorcraftApp>; + let dir = vectorcraft_testkit::temp_dir("sfw-transparency-dither"); + let (mut app, _) = app(&dir, false); + app.run("file.saveForWeb", json!({})).unwrap(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 1200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + let disabled = |h: &H, value: &'static str| h.query(By::new().role(Role::ComboBox).value(value)).map(|n| n.accesskit_node().is_disabled()); + let sliders = |h: &H| h.query_all(By::new().role(Role::Slider)).count(); + let field = |h: &H, key: &str| h.state().ui.dialog.as_ref().unwrap().fields[key].clone(); + assert_eq!(disabled(&h, "No Transparency Dither"), Some(false)); + let before = sliders(&h); + h.get(By::new().role(Role::ComboBox).value("No Transparency Dither")).click(); + h.run(); + h.get_by_label("Diffusion Transparency Dither").click(); + h.run(); + assert_eq!(field(&h, "transparencyDither"), json!("diffusion")); + assert_eq!(sliders(&h), before + 1, "Diffusion has an Amount"); + // Transparency off: the rows are disabled and keep their values. + set(h.state_mut(), "transparency", json!(false)); + h.run(); + assert_eq!(disabled(&h, "Diffusion Transparency Dither"), Some(true)); + assert_eq!(field(&h, "transparencyDither"), json!("diffusion")); + // PNG-24 has no transparency dither; PNG-8 has it again. + set(h.state_mut(), "format", json!("png24")); + h.run(); + assert_eq!(disabled(&h, "Diffusion Transparency Dither"), None); + set(h.state_mut(), "format", json!("png8")); + set(h.state_mut(), "transparency", json!(true)); + set(h.state_mut(), "transparencyDitherAmount", json!(35)); + h.run(); + assert_eq!(disabled(&h, "Diffusion Transparency Dither"), Some(false)); + // Done remembers them. + set(h.state_mut(), "discard", json!(true)); + confirm(h.state_mut()).unwrap(); + let s = h.state().session.last_web_settings(); + assert_eq!((s.transparency_dither, s.transparency_dither_amount), (vectorcraft_render::encode::quantize::Dither::Diffusion, 35)); +} + #[test] fn save_remembers_and_writes_and_done_only_remembers() { let dir = vectorcraft_testkit::temp_dir("sfw-save"); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..25745dd946 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -919,6 +919,11 @@ font-technology Variable Променливи Distribute Spacing Разпределение на разстоянията Distribute Spacing: Разпределение на разстоянията: Dither: Дитъринг: + Transparency Dither Дитъринг на прозрачността + No Transparency Dither Без дитъринг на прозрачността + Diffusion Transparency Dither Дифузен дитъринг на прозрачността + Pattern Transparency Dither Дитъринг на прозрачността с мостра + Noise Transparency Dither Шумов дитъринг на прозрачността Divide Разделяне Divide Horizontally Into Разделяне хоризонтално на Divide Objects Below Разделяне на обектите отдолу diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..7fe312238e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3174,6 +3174,11 @@ antiAlias Sharp Oštro Convert to sRGB Pretvori u sRGB Delete this saved preset Izbriši ovaj sačuvani predložak Dither: Dithering: + Transparency Dither Dithering prozirnosti + No Transparency Dither Bez ditheringa prozirnosti + Diffusion Transparency Dither Difuzijski dithering prozirnosti + Pattern Transparency Dither Dithering prozirnosti uzorkom + Noise Transparency Dither Dithering prozirnosti šumom Fit in View Uklopi u prikaz Format: Format: WebP WebP diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..8d41f90f4a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1360,6 +1360,11 @@ arrowhead Target Diana Distribute Spacing: Distribueix l’espaiat: Dither Tramatge Dither: Tramatge: + Transparency Dither Tramatge de transparència + No Transparency Dither Sense tramatge de transparència + Diffusion Transparency Dither Tramatge de transparència per difusió + Pattern Transparency Dither Tramatge de transparència per motiu + Noise Transparency Dither Tramatge de transparència per soroll Divide Divideix Divide and Outline Will Remove Unpainted Artwork Divideix i contorneja eliminarà l’art no pintat Divide Horizontally Into Divideix horitzontalment en diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..616c0c91dc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3257,6 +3257,11 @@ antiAlias Sharp Ostré Convert to sRGB Převést na sRGB Delete this saved preset Odstranit toto uložené přednastavení Dither: Rozptýlení: + Transparency Dither Rozptýlení průhlednosti + No Transparency Dither Bez rozptylu průhlednosti + Diffusion Transparency Dither Difuzní rozptýlení průhlednosti + Pattern Transparency Dither Rozptýlení průhlednosti vzorkem + Noise Transparency Dither Rozptýlení průhlednosti šumem Fit in View Přizpůsobit zobrazení Format: Formát: WebP WebP diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..330aa68fa8 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5786,6 +5786,11 @@ antiAlias Sharp Skarp Convert to sRGB Konvertér til sRGB Delete this saved preset Slet denne gemte forudindstilling Dither: Dither: + Transparency Dither Gennemsigtighedsdithering + No Transparency Dither Ingen gennemsigtighedsdithering + Diffusion Transparency Dither Diffusionsdithering af gennemsigtighed + Pattern Transparency Dither Mønsterdithering af gennemsigtighed + Noise Transparency Dither Støjdithering af gennemsigtighed Fit in View Tilpas i visning Format: Format: WebP WebP diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..31c86fbf0d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -940,6 +940,11 @@ font-technology Variable Variabel Distribute Spacing Abstand verteilen Distribute Spacing: Abstand verteilen: Dither: Dithering: + Transparency Dither Transparenz-Dithering + No Transparency Dither Kein Transparenz-Dithering + Diffusion Transparency Dither Diffusion-Transparenz-Dithering + Pattern Transparency Dither Muster-Transparenz-Dithering + Noise Transparency Dither Rauschen-Transparenz-Dithering Divide Fläche aufteilen Divide Horizontally Into Horizontal teilen in Divide Objects Below Darunterliegende Objekte aufteilen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..8edcff954f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -903,6 +903,11 @@ font-technology Variable Μεταβλητές Distribute Spacing Κατανομή αποστάσεων Distribute Spacing: Κατανομή αποστάσεων: Dither: Πρόσθεση θορύβου: + Transparency Dither Πρόσμειξη θορύβου διαφάνειας + No Transparency Dither Χωρίς πρόσμειξη θορύβου διαφάνειας + Diffusion Transparency Dither Πρόσμειξη θορύβου διαφάνειας με διάχυση + Pattern Transparency Dither Πρόσμειξη θορύβου διαφάνειας με μοτίβο + Noise Transparency Dither Πρόσμειξη θορύβου διαφάνειας με θόρυβο Divide Διαίρεση Divide Horizontally Into Οριζόντια διαίρεση σε Divide Objects Below Διαίρεση αντικειμένων από κάτω diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..75d9333bbb 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -950,6 +950,11 @@ font-technology Variable Variables Distribute Spacing Distribuir espaciado Distribute Spacing: Distribuir espaciado: Dither: Tramado: + Transparency Dither Tramado de transparencia + No Transparency Dither Sin tramado de transparencia + Diffusion Transparency Dither Tramado de transparencia por difusión + Pattern Transparency Dither Tramado de transparencia por motivo + Noise Transparency Dither Tramado de transparencia por ruido Divide Dividir Divide Horizontally Into Dividir horizontalmente en Divide Objects Below Dividir objetos inferiores diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..10bb86e8f9 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3199,6 +3199,11 @@ antiAlias Sharp Terävä Convert to sRGB Muunna sRGB:ksi Delete this saved preset Poista tämä tallennettu esiasetus Dither: Rasterointi: + Transparency Dither Läpinäkyvyyden rasterointi + No Transparency Dither Ei läpinäkyvyyden rasterointia + Diffusion Transparency Dither Läpinäkyvyyden diffuusiorasterointi + Pattern Transparency Dither Läpinäkyvyyden kuviorasterointi + Noise Transparency Dither Läpinäkyvyyden kohinarasterointi Fit in View Sovita näkymään Format: Muoto: WebP WebP diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..0261b73594 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -953,6 +953,11 @@ font-technology Variable Variables Distribute Spacing Répartir l’espacement Distribute Spacing: Répartition de l’espacement : Dither: Simulation : + Transparency Dither Simulation de transparence + No Transparency Dither Sans simulation de transparence + Diffusion Transparency Dither Simulation de transparence par diffusion + Pattern Transparency Dither Simulation de transparence par motif + Noise Transparency Dither Simulation de transparence par bruit Divide Division Divide Horizontally Into Diviser horizontalement en Divide Objects Below Diviser les objets inférieurs diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..151f169a95 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1101,6 +1101,11 @@ Distribute Spacing: અંતર વિતરિત કરો: Dither ડિથર Dither: ડિથર: + Transparency Dither પારદર્શિતા ડિથર + No Transparency Dither પારદર્શિતા ડિથર નહીં + Diffusion Transparency Dither ડિફ્યુઝન પારદર્શિતા ડિથર + Pattern Transparency Dither પેટર્ન પારદર્શિતા ડિથર + Noise Transparency Dither નોઇઝ પારદર્શિતા ડિથર Divide વિભાજિત કરો Divide Horizontally Into આડી રીતે આમાં વિભાજિત કરો Divide Objects Below નીચેના ઑબ્જેક્ટ્સ વિભાજિત કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..907abfef3f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1776,6 +1776,11 @@ arrowhead Feather पंख Distribute Spacing: स्पेसिंग वितरित करें: Dither डिथर Dither: डिथर: + Transparency Dither पारदर्शिता डिथर + No Transparency Dither कोई पारदर्शिता डिथर नहीं + Diffusion Transparency Dither डिफ़्यूज़न पारदर्शिता डिथर + Pattern Transparency Dither पैटर्न पारदर्शिता डिथर + Noise Transparency Dither नॉइज़ पारदर्शिता डिथर Divide विभाजित करें Divide and Outline Will Remove Unpainted Artwork डिवाइड और आउटलाइन अनपेंटेड आर्टवर्क को हटा देगा Divide Horizontally Into क्षैतिज रूप से विभाजित करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..79f4344a92 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1222,6 +1222,11 @@ arrowhead Target Céltábla Distribute Spacing Térköz elosztása Distribute Spacing: Térköz elosztása: Dither: Árnyalatkeverés: + Transparency Dither Átlátszóság-árnyalatkeverés + No Transparency Dither Nincs átlátszóság-árnyalatkeverés + Diffusion Transparency Dither Diffúziós átlátszóság-árnyalatkeverés + Pattern Transparency Dither Mintázatos átlátszóság-árnyalatkeverés + Noise Transparency Dither Zajos átlátszóság-árnyalatkeverés Divide Felosztás Divide Horizontally Into Vízszintes felosztás Divide Objects Below Alatta lévő objektumok felosztása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..b092c3d6b0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3658,6 +3658,11 @@ antiAlias Sharp Tajam Convert to sRGB Konversi ke sRGB Delete this saved preset Hapus preset tersimpan ini Dither: Dither: + Transparency Dither Dither transparansi + No Transparency Dither Tanpa dither transparansi + Diffusion Transparency Dither Dither transparansi difusi + Pattern Transparency Dither Dither transparansi pola + Noise Transparency Dither Dither transparansi derau Fit in View Sesuaikan ke tampilan Format: Format: WebP WebP diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..dadbe02d68 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -961,6 +961,11 @@ font-technology Variable Variabili Distribute Spacing Distribuisci spaziatura Distribute Spacing: Distribuisci spaziatura: Dither: Dithering: + Transparency Dither Dithering trasparenza + No Transparency Dither Nessun dithering trasparenza + Diffusion Transparency Dither Dithering trasparenza a diffusione + Pattern Transparency Dither Dithering trasparenza a motivo + Noise Transparency Dither Dithering trasparenza a disturbo Divide Dividi Divide Horizontally Into Dividi orizzontalmente in Divide Objects Below Dividi oggetti sottostanti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..9c5097f0bd 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1722,6 +1722,11 @@ antiAlias Sharp シャープ Distribute Spacing 等間隔に分布 Distribute Spacing: 間隔の分布: Dither: ディザ: + Transparency Dither 透明部分のディザ + No Transparency Dither 透明部分のディザなし + Diffusion Transparency Dither 拡散の透明部分のディザ + Pattern Transparency Dither パターンの透明部分のディザ + Noise Transparency Dither ノイズの透明部分のディザ Divide Horizontally Into 水平方向に分割 Divide Slices スライスを分割 Divide Vertically Into 垂直方向に分割 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..39d76a3bf8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5137,6 +5137,11 @@ antiAlias Sharp მკვეთრი Convert to sRGB sRGB-ად გარდაქმნა Delete this saved preset ამ შენახული პრესეტის წაშლა Dither: დიზერინგი: + Transparency Dither გამჭვირვალობის დიზერინგი + No Transparency Dither გამჭვირვალობის დიზერინგის გარეშე + Diffusion Transparency Dither გამჭვირვალობის დიფუზიური დიზერინგი + Pattern Transparency Dither გამჭვირვალობის პატერნული დიზერინგი + Noise Transparency Dither გამჭვირვალობის ხმაურის დიზერინგი Fit in View ხედში ჩატევა Format: ფორმატი: High მაღალი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..22b851fa09 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1712,6 +1712,11 @@ antiAlias Sharp 날카롭게 Distribute Spacing 간격 분포 Distribute Spacing: 간격 분포: Dither: 디더: + Transparency Dither 투명도 디더 + No Transparency Dither 투명도 디더 없음 + Diffusion Transparency Dither 확산 투명도 디더 + Pattern Transparency Dither 패턴 투명도 디더 + Noise Transparency Dither 노이즈 투명도 디더 Divide Horizontally Into 가로로 나누기 Divide Slices 슬라이스 나누기 Divide Vertically Into 세로로 나누기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..eedf44f8dc 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3652,6 +3652,11 @@ antiAlias Sharp Scherp Convert to sRGB Converteren naar sRGB Delete this saved preset Deze opgeslagen voorinstelling verwijderen Dither: Dither: + Transparency Dither Transparantiedithering + No Transparency Dither Geen transparantiedithering + Diffusion Transparency Dither Transparantiedithering met diffusie + Pattern Transparency Dither Transparantiedithering met patroon + Noise Transparency Dither Transparantiedithering met ruis Fit in View In beeld passen Format: Indeling: WebP WebP diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..2590d6d969 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3165,6 +3165,11 @@ antiAlias Sharp Ostre Convert to sRGB Konwertuj na sRGB Delete this saved preset Usuń to zapisane ustawienie Dither: Rozpraszanie: + Transparency Dither Rozpraszanie przezroczystości + No Transparency Dither Bez rozpraszania przezroczystości + Diffusion Transparency Dither Dyfuzyjne rozpraszanie przezroczystości + Pattern Transparency Dither Rozpraszanie przezroczystości wzorkiem + Noise Transparency Dither Rozpraszanie przezroczystości szumem Fit in View Dopasuj do widoku Format: Format: High Wysoka diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..ca4f7be8d8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -876,6 +876,11 @@ antiAlias Sharp Nítido Distribute Spacing Distribuir Espaçamento Distribute Spacing: Distribuir Espaçamento: Dither: Dither: + Transparency Dither Dither de transparência + No Transparency Dither Sem dither de transparência + Diffusion Transparency Dither Dither de transparência por difusão + Pattern Transparency Dither Dither de transparência por padrão + Noise Transparency Dither Dither de transparência por ruído Divide Dividir Divide Horizontally Into Dividir Horizontalmente Em Divide Objects Below Dividir Objetos Abaixo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..56e0c410e2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -948,6 +948,11 @@ font-technology Variable Вариативные Distribute Spacing Распределить интервалы Distribute Spacing: Распределение интервалов: Dither: Дизеринг: + Transparency Dither Дизеринг прозрачности + No Transparency Dither Без дизеринга прозрачности + Diffusion Transparency Dither Диффузный дизеринг прозрачности + Pattern Transparency Dither Дизеринг прозрачности узором + Noise Transparency Dither Шумовой дизеринг прозрачности Divide Разделить Divide Horizontally Into Разделить по горизонтали на Divide Objects Below Разделить объекты ниже diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..bf3bd8b9d4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -933,6 +933,11 @@ font-technology Variable Variabla Distribute Spacing Fördela avstånd Distribute Spacing: Fördela avstånd: Dither: Dithering: + Transparency Dither Transparensdithering + No Transparency Dither Ingen transparensdithering + Diffusion Transparency Dither Transparensdithering med diffusion + Pattern Transparency Dither Transparensdithering med mönster + Noise Transparency Dither Transparensdithering med brus Divide Dela upp Divide Horizontally Into Dela horisontellt i Divide Objects Below Dela objekt nedanför diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..096fe7403d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1128,6 +1128,18 @@ fn anti_aliasing_method_labels_are_in_complete_catalogs() { } } +/// Save for Web's Transparency Dither label and its choices (drawn translated by the dropdown, not +/// through `tl!`). +#[test] +fn transparency_dither_labels_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + let cat = lang.catalog(); + for label in std::iter::once("Transparency Dither").chain(crate::dialogs::save_for_web::TRANSPARENCY_DITHERS.map(|(_, l)| l)) { + assert!(cat.plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + /// Each row in the `search` context, which adds a language's words to a group of words with the same /// meaning for the command palette, names a group and adds single words of no other group, and no /// two rows of a catalog add one word to different groups. No catalog has to have these rows. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..940ad83291 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -929,6 +929,11 @@ font-technology Variable Değişken Distribute Spacing Aralığı Dağıt Distribute Spacing: Aralığı Dağıt: Dither: Titreme: + Transparency Dither Saydamlık titremesi + No Transparency Dither Saydamlık titremesi yok + Diffusion Transparency Dither Difüzyon saydamlık titremesi + Pattern Transparency Dither Desen saydamlık titremesi + Noise Transparency Dither Gürültü saydamlık titremesi Divide Böl Divide Horizontally Into Yatay Olarak Böl Divide Objects Below Aşağıdaki Nesneleri Böl diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..721abf78de 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -955,6 +955,11 @@ font-technology Variable Варіативні Distribute Spacing Розподілити інтервали Distribute Spacing: Розподіл інтервалів: Dither: Дизеринг: + Transparency Dither Дизеринг прозорості + No Transparency Dither Без дизерингу прозорості + Diffusion Transparency Dither Дифузійний дизеринг прозорості + Pattern Transparency Dither Дизеринг прозорості візерунком + Noise Transparency Dither Шумовий дизеринг прозорості Divide Розділити Divide Horizontally Into Розділити по горизонталі на Divide Objects Below Розділити об’єкти нижче diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..5d0f31a3fe 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1122,6 +1122,11 @@ font-technology Variable Biến thiên Distribute Spacing Phân bố khoảng cách Distribute Spacing: Phân bố khoảng cách: Dither: Dither: + Transparency Dither Dither độ trong suốt + No Transparency Dither Không dither độ trong suốt + Diffusion Transparency Dither Dither độ trong suốt khuếch tán + Pattern Transparency Dither Dither độ trong suốt họa tiết + Noise Transparency Dither Dither độ trong suốt nhiễu Divide Chia Divide Horizontally Into Chia ngang thành Divide Objects Below Chia đối tượng bên dưới diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..3b80618a3d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -893,6 +893,11 @@ antiAlias Sharp 锐利 Distribute Spacing 按间距分布 Distribute Spacing: 分布间距: Dither: 仿色: + Transparency Dither 透明度仿色 + No Transparency Dither 无透明度仿色 + Diffusion Transparency Dither 扩散透明度仿色 + Pattern Transparency Dither 图案透明度仿色 + Noise Transparency Dither 杂色透明度仿色 Divide 分割 Divide Horizontally Into 水平分割为 Divide Objects Below 分割下方对象 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..fb9ab8441d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -923,6 +923,11 @@ font-technology Variable 可變 Distribute Spacing 均分間距 Distribute Spacing: 均分間距: Dither: 仿色: + Transparency Dither 透明度仿色 + No Transparency Dither 無透明度仿色 + Diffusion Transparency Dither 擴散透明度仿色 + Pattern Transparency Dither 圖樣透明度仿色 + Noise Transparency Dither 雜訊透明度仿色 Divide 分割 Divide Horizontally Into 水平分割為 Divide Objects Below 分割下方物件 diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..9e83056ee9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10531,8 +10531,8 @@ every option. File → Export → Save for Web (Legacy) writes optimised web images: `document.exportForWeb {format: gif|jpg|png8|png24, …}` renders the artboard (`clipToArtboard`, the default; `artboard` picks one) or the visible art and the slices, at `width`, `height` or `percent`, and encodes it with the format's settings: for GIF and PNG-8 `reduction`, `colors`, -`dither`, `ditherAmount`, `transparency`, `matte`, `interlaced`, `webSnap`, `lossy` (GIF) and `colorTable {locked, -transparent, webShift, sort, deleted, customPalette, shifted}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24 +`dither`, `ditherAmount`, `transparency`, `transparencyDither`, `transparencyDitherAmount`, `matte`, `interlaced`, +`webSnap`, `lossy` (GIF) and `colorTable {locked, transparent, webShift, sort, deleted, customPalette, shifted}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24 `transparency`, `matte` and `interlaced`. `metadata` (none, copyright, contact, all) writes File Info as PNG text or a GIF/JPEG comment; `convertToSrgb` marks PNGs as sRGB. `` is the name of `path` without its extension, or without `path` the document's title with the characters Windows does not allow in a file name as `-` and a `-` after @@ -10543,6 +10543,15 @@ after a Windows device name such as `aux` (`slices: selected` writes the selecte Without `path` the files come back as `{name, dataBase64}`. As in the raster exports, `warnings` says when an image couldn't be decoded and is missing from the image; the files are written all the same. +With `transparency` on, `transparencyDither` sets how GIF and PNG-8 treat partly transparent pixels: `none` (the +default) makes the pixels under half opacity transparent and keeps the others; `diffusion`, `pattern` and `noise` make +some of them transparent and keep the rest in a diffusion pattern, an 8×8 ordered pattern or noise. With `pattern`, +`noise`, or `diffusion` at amount 100, about as many are kept as their opacity says. `transparencyDitherAmount` (0 to +100, default 100) sets the strength of `diffusion`: a lower amount comes closer to `none`, and 0 gives the same file as +`none`. Fully transparent and fully opaque pixels do not change, the same art and settings +always give the same file, and a kept pixel is blended over `matte` as before. Without `transparency` both keys are +kept and do not change the file. An unknown method or an amount outside 0 to 100 is refused. + `document.exportForWeb.preview` returns what Save writes for the same settings without writing it: `bytes` (the exact file size), `seconds` to download at `kbps` (default 56.6), the size, and for palette formats the colour table (`colors: [{color, source, transparent, locked, webShifted, shifted, webSafe}]`). The colour table's lists name colours by diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..3b3a0b1fcc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1003,6 +1003,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - SVG Options: Show in Browser opens the SVG in the default web browser, beside Show Code, which shows the code instead; the SVG export options on the help page (https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) list both. VectorCraft writes the SVG of the dialog's current choices for one page to a new folder inside `VectorCraft SVG Preview` in the system's temporary folder, which is kept and cleaned up as Save for Web's previews are, and the dialog stays open without remembering the choices or writing the chosen file. The page is VectorCraft's own choice: under Export Selection the selection's crop, otherwise the first artboard the options choose, and a range the document does not have is an error. The web build disables the button, and control and MCP requests for `file.export.svg.browser` are refused. `crates/ui-egui/src/dialogs/svg_options.rs` (`show_in_browser_opens_what_ok_writes_without_confirming`, `show_in_browser_is_refused_on_the_web_and_for_automation`, `svg_preview_folders_leave_save_for_web_previews_alone`). - Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged. - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). + - Save for Web: with Transparency on, GIF and PNG-8 offer Transparency Dither (No Transparency Dither, Diffusion, Pattern and Noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an Amount for Diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is No Transparency Dither with Amount 100; with Pattern, Noise, or Diffusion at Amount 100, about as many pixels stay opaque as their opacity says, and a lower Diffusion Amount comes closer to No Transparency Dither; Pattern uses an 8×8 ordered pattern and Noise a fixed noise, so the same art always gives the same file; Amount 0 gives the same file as No Transparency Dither; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; both rows are disabled while Transparency is off and keep their values; presets and the remembered settings keep them (`transparencyDither`, `transparencyDitherAmount`). - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. - Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). From c8fb7729e5ff0d8291e9f4ab37076eb550ab58a3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:08:27 -0800 Subject: [PATCH 009/101] Save for Web: diffusion transparency dither keeps its error past fully clear pixels Fully transparent and fully opaque pixels keep their state but now pass on the opacity error they receive. Before, that error was dropped, so a row alternating half-opaque and fully transparent pixels kept every half-opaque pixel opaque at amount 100. About half of them stay opaque now, in a single row and in a checkerboard. --- crates/render/src/encode/quantize.rs | 33 ++++++++++++++--------- crates/render/src/encode/tests_palette.rs | 18 +++++++++++++ 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index 96b9ffe338..6167526655 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -232,8 +232,9 @@ pub fn nearest_entries(rgba: &[u8], width: u32, o: &PaletteOptions, palette: &[[ /// partly transparent pixel does under half opacity with no transparency dither, and else by /// `o.transparency_dither`. With pattern, noise, or diffusion at amount 100, about as many of an /// area's pixels stay opaque as its opacity says; a lower diffusion amount moves the result toward -/// the cut at half opacity. Diffusion spreads each pixel's opacity error to the pixels right of it -/// and below it (Floyd–Steinberg, scaled by `o.transparency_dither_amount`), pattern compares the +/// the cut at half opacity. Diffusion spreads each partly transparent pixel's opacity error to the +/// pixels right of it and below it (Floyd–Steinberg, scaled by `o.transparency_dither_amount`), and +/// fully transparent and opaque pixels pass on the error they receive; pattern compares the /// opacity with the 8×8 ordered pattern and noise with a noise threshold. The result depends only /// on the pixels and the options, so exports are reproducible. pub fn clear_mask(rgba: &[u8], width: u32, o: &PaletteOptions) -> Vec { @@ -264,18 +265,24 @@ pub fn clear_mask(rgba: &[u8], width: u32, o: &PaletteOptions) -> Vec { (_, Dither::Pattern) => a < 255.0 * bayer(x % 8, y % 8), // Another noise than the color dither's, so the two do not line up. (_, Dither::Noise) => a < 255.0 * noise(x ^ 0x5a5a, y ^ 0xa5a5), - (_, Dither::Diffusion) => { - let v = a + cur[x + 1]; - let clear = v < 127.5; - let e = (v - if clear { 0.0 } else { 255.0 }) * amount; - // 7/16 right, 3/16 below left, 5/16 below, 1/16 below right. - cur[x + 2] += e * 7.0 / 16.0; - next[x] += e * 3.0 / 16.0; - next[x + 1] += e * 5.0 / 16.0; - next[x + 2] += e / 16.0; - clear - } + (_, Dither::Diffusion) => a + cur[x + 1] < 127.5, }; + if dither == Dither::Diffusion { + // A partly transparent pixel spreads its own opacity error. A fully transparent or + // opaque pixel keeps its state and passes on the error it received unchanged, so + // the partly transparent pixels around it keep their share of opacity + // (VectorCraft's own rule). + let got = cur[x + 1]; + let e = match p[3] { + 0 | 255 => got, + _ => (a + got - if clear { 0.0 } else { 255.0 }) * amount, + }; + // 7/16 right, 3/16 below left, 5/16 below, 1/16 below right. + cur[x + 2] += e * 7.0 / 16.0; + next[x] += e * 3.0 / 16.0; + next[x + 1] += e * 5.0 / 16.0; + next[x + 2] += e / 16.0; + } out.push(clear); } cur.copy_from_slice(next); diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index 8a377190f8..0a280e9d32 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -328,3 +328,21 @@ fn transparency_dither_leaves_clear_and_opaque_pixels_and_needs_transparency() { assert!(clear_mask(&[], 0, &alpha_dither(Dither::Diffusion, 100)).is_empty()); assert_eq!(clear_mask(&see_through(3, 1, |_, _| 200), 1000, &alpha_dither(Dither::Diffusion, 100)).len(), 3); } + +#[test] +fn transparency_diffusion_passes_error_through_clear_and_opaque_pixels() { + // Half-opaque pixels between fully transparent or fully opaque ones, in one row and in a + // checkerboard: about half of them stay opaque, and the others keep their state. + for other in [0u8, 255] { + for (w, h, half) in [(64, 1, (|x, _| x % 2 == 0) as fn(u32, u32) -> bool), (32, 32, |x, y| (x + y) % 2 == 0)] { + let px = see_through(w, h, |x, y| if half(x, y) { 128 } else { other }); + let mask = clear_mask(&px, w, &alpha_dither(Dither::Diffusion, 100)); + let at = |x: u32, y: u32| mask[(y * w + x) as usize]; + let cells: Vec<(u32, u32)> = (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).collect(); + assert!(cells.iter().filter(|&&(x, y)| !half(x, y)).all(|&(x, y)| at(x, y) == (other == 0)), "{other} {w}x{h}"); + let halves: Vec<_> = cells.iter().filter(|&&(x, y)| half(x, y)).collect(); + let share = halves.iter().filter(|&&&(x, y)| !at(x, y)).count() as f64 / halves.len() as f64; + assert!((share - 128.0 / 255.0).abs() < 0.1, "{other} {w}x{h}: {share}"); + } + } +} From 4cb3b0d5b6bf56f2ccf143deba226ea09cc2798f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:58:32 -0800 Subject: [PATCH 010/101] Parametric Shape: W and H keep the shared reference point in place The Parametric Shape panel's W and H fields resized a shape about its center whatever point the reference point locator showed, while the Transform panel and the Control bar keep that point in place. - addon.pathtools.shape.set takes `reference` (0 to 8; any other value is an error). With it and no `center`, the point of the bounding box that object.setBounds measures (rotated with rotated objects, and as drawn with Use Preview Bounds) keeps its place. Without it the center stays, as before. - The panel's W and H pass the locator's point. - A shape set by id and not selected that the edit would take past the coordinate limit is refused, as object.setLiveShape refuses one. - The result's `shape` is read back after the edit, and is null when snapping to the pixel grid left a plain path. Docs: docs/mcp.md, docs/target-app-parity.md. --- .../engine/src/cmd/addons/pathtools/shape.rs | 45 +++++++++- .../engine/src/cmd/addons/pathtools/tests.rs | 86 +++++++++++++++++++ crates/ui-egui/src/addons/pathtools/shape.rs | 7 +- crates/ui-egui/src/addons/pathtools/tests.rs | 56 ++++++++++++ docs/mcp.md | 7 +- docs/target-app-parity.md | 7 +- 6 files changed, 199 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs index fc88442997..551d5c7dba 100644 --- a/crates/engine/src/cmd/addons/pathtools/shape.rs +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -4,13 +4,15 @@ //! (`vectorcraft_tools::addons::parametric_shape`), which SVG export leaves out. use serde_json::{Value, json}; -use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeKind}; use vectorcraft_geom::{FillRule, PathData, Point}; use vectorcraft_pathops::addons::pathtools::shapes::{ParametricShape, ShapeKind, recognise}; +use vectorcraft_render::effects; use vectorcraft_tools::addons::parametric_shape::{CREATE, EDIT, KEY, apply, read, stored, to_json}; +use super::super::super::menucmds::whole_or; use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection}; -use crate::{EngineError, Result, Session}; +use crate::{EngineError, MAX_COORD, Result, Session}; /// The undo step's name and the command's label. const CONVERT: &str = "Convert to Parametric Shape"; @@ -31,7 +33,7 @@ pub fn specs() -> Vec { "Edit Parametric Shape", [], None, - "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with none, or the same ones, nothing changes → {id, shape (its numbers now)}", + "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do), otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}", has_doc, set ), @@ -95,15 +97,52 @@ fn set(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "the path is locked or hidden")); } let old = d.node(id).and_then(read).ok_or_else(|| bad(C, "the object is not an editable parametric shape"))?; + let reference = match p.get("reference").filter(|v| !v.is_null()) { + Some(_) => match whole_or(p, "reference", 4, C)? { + i @ 0..=8 => Some(i as usize), + _ => return Err(bad(C, "`reference` must be from 0 to 8")), + }, + None => None, + }; let shape = apply(old, p).map_err(|e| bad(C, e))?; if shape != old { + // Without a center, the reference point of the bounding box (as the Transform panel and + // `object.setBounds` measure it; the geometric box where the preview leaves none) keeps + // its place: the new outline moves onto it. + let how = s.bounds_measure(); + let boxed = move |d: &Document| { + effects::preview::oriented_bounds_with(d, &[id], how) + .or_else(|| effects::preview::oriented_bounds_with(d, &[id], effects::preview::Measure { preview: false, ..how })) + }; + let keep = match reference.filter(|_| p.get("center").is_none_or(Value::is_null)) { + Some(i) => Some((i, boxed(&s.doc()?.doc).ok_or_else(|| EngineError::Other("no bounds".into()))?.reference_point(i))), + None => None, + }; let path = outline(&shape, C)?; s.edit(EDIT, |d, sel| { shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path); + if let Some((i, was)) = keep + && let Some(now) = boxed(d).map(|b| b.reference_point(i)) + && now != was + { + let mut moved = shape; + moved.center += was - now; + let path = outline(&moved, C)?; + shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &moved, path); + } + // A shape named by `id` and not selected is not checked after the edit: one the edit + // takes past the coordinate limit is an error here, and nothing changes. + if !crate::sanity::objects_in_range(d, &[id]) { + return Err(bad(C, format!("coordinate out of range (limit ±{MAX_COORD} pt)"))); + } sel.anchors.remove(&id); sel.segments.remove(&id); Ok(()) })?; + // The numbers the edit committed (an object attached to a path is put back on it); none + // when snapping to the pixel grid left a plain path. + let committed = s.doc()?.doc.node(id).and_then(read); + return Ok(json!({ "id": id.0, "shape": committed.map_or(Value::Null, |c| to_json(&c)) })); } Ok(json!({ "id": id.0, "shape": to_json(&shape) })) } diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 8cd83bacfd..c474cfae85 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -476,6 +476,92 @@ fn set_changes_the_numbers_in_one_step_and_nothing_without_a_change() { assert_eq!(path(&s, id).anchor_count(), 16); } +#[test] +fn set_keeps_the_reference_point_of_the_bounding_box_in_place() { + let mut s = session(); + let corner = |s: &Session, id: NodeId, i: usize| s.transform_box(&[id]).unwrap().reference_point(i); + // (kind, its own rotation, a turn with object.rotate, which turns its bounding box too) + for (kind, rotation, turn) in [ + ("rectangle", 0.0, 0.0), + ("rectangle", 30.0, 0.0), + ("rectangle", 180.0, 0.0), + ("rectangle", 0.0, 30.0), + ("star", 0.0, 0.0), + ("heart", 0.0, 0.0), + ] { + let r = s.execute("addon.pathtools.shape.create", &json!({"kind": kind, "center": [200, 150], "rotation": rotation})).unwrap(); + let id = id_of(&r); + if turn != 0.0 { + s.execute("object.rotate", &json!({"angle": turn, "origin": [200, 150]})).unwrap(); + assert!(s.transform_box(&[id]).unwrap().angle != 0.0, "the box turns with the object"); + } + // Each of the 9 points of the box the Transform panel shows stays where it was while the + // width and then the height change, as `object.setBounds` keeps it. + for refi in 0..9 { + for key in ["width", "height"] { + let (before, was) = (shape_of(&s, id).unwrap(), corner(&s, id, refi)); + let grown = if key == "width" { before.width } else { before.height } + 10.0; + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, key: grown, "reference": refi})).unwrap(); + let moved = corner(&s, id, refi).distance(was); + assert!(moved < 1e-6, "{kind} at {rotation}°, reference {refi}, {key}: the point moved {moved} pt"); + let after = shape_of(&s, id).unwrap(); + assert!((if key == "width" { after.width } else { after.height } - grown).abs() < 1e-9, "{kind}, {key}: the new size"); + } + } + // Without a reference point, and with an explicit center, the old rules hold. + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 80})).unwrap(); + let c = shape_of(&s, id).unwrap().center; + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 120})).unwrap(); + assert!(shape_of(&s, id).unwrap().center.distance(c) < 1e-9, "the center stays by default"); + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 60, "center": [10, 20], "reference": 0})).unwrap(); + assert!(shape_of(&s, id).unwrap().center.distance(Point::new(10.0, 20.0)) < 1e-9, "a center given wins"); + } + let id = star(&mut s); + refuses( + &mut s, + "addon.pathtools.shape.set", + &[ + json!({"id": id.0, "width": 50, "reference": -1}), + json!({"id": id.0, "width": 50, "reference": 1.5}), + json!({"id": id.0, "width": 50, "reference": 9}), + json!({"id": id.0, "width": 50, "reference": 9.0}), + ], + ); + // A whole number written with a decimal point picks the same point. + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 50, "reference": 8.0})).unwrap(); + let written_whole = shape_of(&s, id).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 50, "reference": 8})).unwrap(); + assert!(shape_of(&s, id).unwrap().center.distance(written_whole.center) < 1e-9, "`8.0` and `8` pick the same point"); + s.execute("edit.undo", &json!({})).unwrap(); + // With Use Preview Bounds the point is on the box as drawn: a star's stroked tips reach past + // its anchors by more as the star is stretched, so the drawn box and the anchors' box move apart. + s.prefs.use_preview_bounds = true; + let stroked = id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "star", "center": [300, 300], "count": 5})).unwrap()); + s.execute("paint.setStroke", &json!({"ids": [stroked.0], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [stroked.0], "weight": 12})).unwrap(); + let geometric = |s: &Session, i: usize| s.doc().unwrap().doc.oriented_bounds(&[stroked], false).unwrap().reference_point(i); + for refi in [0, 2, 6, 8] { + let (was, anchors_were) = (corner(&s, stroked, refi), geometric(&s, refi)); + let wide = shape_of(&s, stroked).unwrap().width * 2.5; + s.execute("addon.pathtools.shape.set", &json!({"id": stroked.0, "width": wide, "reference": refi})).unwrap(); + let moved = corner(&s, stroked, refi).distance(was); + assert!(moved < 1e-6, "stroked star, reference {refi}: the drawn box's point moved {moved} pt"); + assert!(geometric(&s, refi).distance(anchors_were) > 1e-3, "reference {refi}: the anchors' box is not the one kept"); + s.execute("edit.undo", &json!({})).unwrap(); + } + s.prefs.use_preview_bounds = false; + // A shape set by id, not selected, that the edit would take past the coordinate limit. + let edge = id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "rectangle", "center": [3_999_900, 100]})).unwrap()); + select(&mut s, &[]); + refuses( + &mut s, + "addon.pathtools.shape.set", + &[json!({"id": edge.0, "width": 180, "reference": 0}), json!({"id": edge.0, "center": [3_999_990, 100]})], + ); + s.execute("addon.pathtools.shape.set", &json!({"id": edge.0, "width": 180, "reference": 2})).unwrap(); +} + #[test] fn bad_shape_params_are_refused() { let mut s = session(); diff --git a/crates/ui-egui/src/addons/pathtools/shape.rs b/crates/ui-egui/src/addons/pathtools/shape.rs index f29a372934..a5135bf042 100644 --- a/crates/ui-egui/src/addons/pathtools/shape.rs +++ b/crates/ui-egui/src/addons/pathtools/shape.rs @@ -9,7 +9,7 @@ use vectorcraft_geom::Point; use vectorcraft_tools::addons::parametric_shape::{self as tool, MAX_COUNT, MAX_SIZE, MIN_COUNT, ParametricShape, ShapeKind, apply, read}; use crate::VectorcraftApp; -use crate::panels::empty_state; +use crate::panels::{empty_state, transform}; use crate::widgets::{self, dim_label}; /// The panel's id (`window.panel {panel: "parametricShape"}`). @@ -121,6 +121,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { match (change, selected) { (Some(mut p), Some((id, _))) => { p["id"] = json!(id.0); + // The Transform panel and the Control bar share one reference point locator. W and H + // keep the point of the shape's bounding box chosen there in place. + if p.get("width").or_else(|| p.get("height")).is_some() { + p["reference"] = json!(transform::reference_index(ui)); + } run(app, "addon.pathtools.shape.set", p); } (Some(values), None) => run(app, "tool.setOption", json!({ "tool": tool::ID, "values": values })), diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 2c49c661fe..a87262294e 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -136,6 +136,62 @@ fn the_parametric_shape_panel_opens_from_the_submenu_and_shows_the_shape() { assert!(!text.contains("Count:"), "a speech bubble has no count: {text}"); } +/// One headless frame of the Parametric Shape panel with input `events`: every text drawn, with its rect. +fn shape_panel_frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> Vec<(String, egui::Rect)> { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::shape::show(app, ui)); + out.textures_delta.clear(); + fn collect(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)), + _ => {} + } + } + let mut texts = vec![]; + for c in &out.shapes { + collect(&c.shape, &mut texts); + } + texts +} + +/// Type `value` into the panel's field that shows `shown`, and press Enter. +fn type_into_shape_panel(ctx: &egui::Context, app: &mut VectorcraftApp, shown: &str, value: &str) { + let texts = shape_panel_frame(ctx, app, vec![]); + let pos = texts.iter().find(|(t, _)| t == shown).unwrap_or_else(|| panic!("`{shown}` not drawn: {texts:?}")).1.center(); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + for e in + [egui::Event::PointerMoved(pos), button(true), button(false), key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(value.into())] + { + shape_panel_frame(ctx, app, vec![e]); + } + shape_panel_frame(ctx, app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]); + shape_panel_frame(ctx, app, vec![]); +} + +/// The panel's W and H keep the point of the selection's box that the Transform panel and the +/// Control bar share in place, as their own W and H do, on upright and turned shapes. +#[test] +fn the_parametric_shape_panels_size_fields_keep_the_shared_reference_point() { + for (refi, rotation) in [(0usize, 0.0), (8, 0.0), (2, 30.0), (0, 180.0)] { + let mut app = app(); + let params = json!({"kind": "rectangle", "center": [150, 150], "width": 100, "height": 60, "rotation": rotation}); + let id = vectorcraft_doc::NodeId(app.run("addon.pathtools.shape.create", params).unwrap()["id"].as_u64().unwrap()); + let node = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(id).cloned().unwrap(); + let shape = |app: &VectorcraftApp| vectorcraft_tools::addons::parametric_shape::read(&node(app)).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("refpt"), refi)); + let (before, was) = (shape(&app), app.selection_box().unwrap().reference_point(refi)); + type_into_shape_panel(&ctx, &mut app, "100 pt", "160"); + type_into_shape_panel(&ctx, &mut app, "60 pt", "20"); + let after = shape(&app); + assert!(after.width > before.width && after.height < before.height, "reference {refi}: W and H took {after:?}"); + let moved = app.selection_box().unwrap().reference_point(refi).distance(was); + assert!(moved < 1e-6, "reference {refi}, rotation {rotation}: the reference point moved {moved} pt"); + } +} + #[test] fn the_corner_tool_item_selects_the_tool_and_opens_its_panel_section() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..bafdc73f8f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14749,8 +14749,11 @@ Commands: roundness (0 to 1; 0.4 and 0); gear, tooth height (0.01 to 0.9, 0.2); bubble, the tail's height (0.05 to 0.9, 0.25) and where its tip is across (−1 to 1, −0.4). → `{id, shape}`. - `addon.pathtools.shape.set {id, …}` changes a parametric shape's numbers (the same keys; a new `kind` takes its own - defaults for the values not given) and redraws it in place. With no change it makes no step. → `{id, shape}` (its - numbers now, so `{id}` alone reads them). + defaults for the values not given) and redraws it in place. With `reference` (0 to 8 on the 9-point grid of the + bounding box as `object.setBounds` measures it, rotated with rotated objects) and no `center`, that point of the box + keeps its place, as with the Transform panel's W and H; otherwise the shape's center stays. A `reference` outside 0 + to 8 is an error. With no change it makes no step. → `{id, shape}` (its numbers now, so `{id}` alone reads them; + `null` when snapping to the pixel grid left a plain path). - `addon.pathtools.shape.convert {ids?}` makes the selected plain closed paths that are rectangles, ellipses or polygons with equal sides and corners (stretched along their own axes at most) parametric shapes with the same outline. → `{ids}` (those converted). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..6e2efc2feb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2820,9 +2820,10 @@ The add-on's Parametric Shape Tool (2026-10-30) draws ten kinds of shape that st ellipse, polygon and star with 3 to 1,000 sides or points, ring, arrow, cross, heart, gear, speech bubble; corner radius limited to the middle of a side): a drag from the centre sizes and turns one, the arrow keys change its count and values while dragging, handles edit a selected one, a double-click places one with the last settings, and its panel edits the -numbers. A shape is a plain path whose numbers and outline fingerprint sit in one object-data entry that SVG export -leaves out; moving, rotating or scaling it keeps it editable, editing its anchors makes it a plain path. Convert to -Parametric Shape recognises plain rectangles, ellipses and regular polygons. Geometry in +numbers (its W and H keep the point chosen in the shared reference point locator in place). A shape is a plain path +whose numbers and outline fingerprint sit in one object-data entry that SVG export leaves out; moving, rotating or +scaling it keeps it editable, editing its anchors makes it a plain path. Convert to Parametric Shape recognises plain +rectangles, ellipses and regular polygons. Geometry in `vectorcraft_pathops::addons::pathtools::shapes`. Tests: `shapes` in `vectorcraft-pathops` (each kind, ranges, recovery after transforms, recognition), `addons::parametric_shape` in `vectorcraft-tools` (drag, keys, handles, stored data), `cmd::addons::pathtools::tests` in `vectorcraft-engine` (each command one undo step, bad params refused, From d5e15200f1b586413a08f9eb68e4187ba9adcc7c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:08:47 -0800 Subject: [PATCH 011/101] Blob Brush: Size offers Stylus Wheel Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. With it the brush is Size - Variation wide at one end of an airbrush pen's finger wheel travel and Size + Variation at the other, in a drag, a click and with a tip that is not round. A point without a wheel counts as half way, and a mouse stroke keeps the Size. - path.blob takes sizeMode "stylusWheel" with the wheel seventh in each point, and its error for an unknown sizeMode lists the three modes. - The tool keeps the mode, records the wheel, and sends it on release. While the Blob Brush paints, its tip outline takes the size the pen gives (on Pressure too), and keeps the set angle and roundness. A wheel turned with the pen held in place updates the last sample. - The Eraser's Size already offered Stylus Wheel and is unchanged. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/draw2/commands.rs | 2 +- crates/engine/src/cmd/draw2/common.rs | 31 ++++++---- crates/engine/src/cmd/draw2/cut.rs | 4 +- crates/engine/src/cmd/draw2/freehand.rs | 10 +-- crates/engine/src/tests/draw2.rs | 65 +++++++++++++++++++- crates/engine/src/tests/toolsettings.rs | 5 +- crates/tools/src/draw2.rs | 5 ++ crates/tools/src/draw2/gesture.rs | 48 +++++++++------ crates/tools/src/draw2/gesture/tests.rs | 63 ++++++++++++++++++- crates/ui-egui/src/dialogs/freehand.rs | 4 +- crates/ui-egui/src/dialogs/freehand/tests.rs | 20 ++++++ docs/mcp.md | 10 +++ docs/target-app-parity.md | 1 + 13 files changed, 221 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index e4846367b5..95bd4b72d3 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -138,7 +138,7 @@ pub fn specs() -> Vec { "Blob Brush", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An angle, roundness or fidelity outside its range is rejected with an error, and nothing changes", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1, finger wheel 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" | \"stylusWheel\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest; set to Stylus Wheel: size − sizeVariation wide at one end of an airbrush pen's finger wheel travel, size at the middle and size + sizeVariation at the other end; at least 0.1 pt; a stroke without that reading, and a point without a wheel on Stylus Wheel, keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An unknown sizeMode, or an angle, roundness or fidelity outside its range, is rejected with an error, and nothing changes", has_doc, blob ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index 36280196b7..f69ac40822 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -236,22 +236,27 @@ impl PenRecord { } } -/// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`, with -/// `sizeVariation` in points, 0..1000): the stroke's pen pressure along it and the variation, `None` -/// for Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the -/// size. A `sizeVariation` outside its range is an error with Fixed too. -pub(super) fn size_pressure(p: &Value, samples: &[Sample], cmd: &str) -> Result> { +/// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`) or, for the +/// Blob Brush, Stylus Wheel (`sizeMode: "stylusWheel"`), with `sizeVariation` in points, 0..1000: +/// the stroke's pen pressure or airbrush finger wheel along it (0..1, the size less the variation +/// at 0 and plus it at 1) and the variation. `None` for Fixed (the default), no variation or a +/// stroke without that reading (a mouse, a pen without a wheel), which keeps the size. A +/// `sizeVariation` outside its range is an error with Fixed too. +pub(super) fn size_profile(p: &Value, samples: &[Sample], cmd: &str) -> Result> { + const MODES: &str = "\"fixed\", \"pressure\" or \"stylusWheel\""; let variation = ranged(p, "sizeVariation", 0.0, SIZE_VARIATIONS, cmd)?; - match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) { - None | Some(Ok("fixed")) => Ok(None), - Some(Ok("pressure")) => Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))), - Some(Ok(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not `{other}`"))), - Some(Err(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not {other}"))), - } + let read = match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) { + None | Some(Ok("fixed")) => return Ok(None), + Some(Ok("pressure")) => stroke_pressure(samples), + Some(Ok("stylusWheel")) => stroke_wheel(samples), + Some(Ok(other)) => return Err(bad(cmd, format!("sizeMode is {MODES}, not `{other}`"))), + Some(Err(other)) => return Err(bad(cmd, format!("sizeMode is {MODES}, not {other}"))), + }; + Ok(read.filter(|_| variation > 0.0).map(|prof| (prof, variation))) } -/// The area a stroke along `spine` covers with Size set to Pressure: as wide at each point as -/// [`vectorcraft_tools::draw2::pressure_size`] gives for the pressure `prof` records there, with +/// The area a stroke along `spine` covers with Size set to Pressure or Stylus Wheel: as wide at +/// each point as [`vectorcraft_tools::draw2::pressure_size`] gives for the reading `prof` records there, with /// round ends and joins, its overlaps united into one outline. pub(super) fn pressure_region(spine: &PathData, size: f64, variation: f64, prof: &PressureProfile) -> Result { let widest = size + variation; diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index cc543f3e05..445a71b171 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -1,7 +1,7 @@ use super::common::{ PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, has_fill, has_painted_ancestor_stroke, has_painted_stroke, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, - set_geometry, sibling_with, size_pressure, target_paths, usize_opt, + set_geometry, sibling_with, size_profile, target_paths, usize_opt, }; use super::{ Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, Document, EngineError, FillRule, Join, NodeId, NodeKind, Paint, ParamCurve, PathData, Point, @@ -314,7 +314,7 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { if varies_beyond_size_pressure(&vary) { return erase_varied(s, &samples, [angle, roundness, size], vary); } - let pressure = if vary[2].0 == Variation::Pressure { size_pressure(p, &samples, C)? } else { None }; + let pressure = if vary[2].0 == Variation::Pressure { size_profile(p, &samples, C)? } else { None }; let pts: Vec = samples.into_iter().map(|s| s.pt).collect(); let r = size / 2.0; // The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it. diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 607abf8f03..a1e60d85e7 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -1,5 +1,5 @@ use super::common::{ - PenRecord, SIZES, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, ranged, samples_param, size_pressure, + PenRecord, SIZES, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, ranged, samples_param, size_profile, stroke_paint, subpath_len, target_paths, within_input_bound, }; use super::{ @@ -524,8 +524,8 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { } let tip = vectorcraft_tools::draw2::blob_tip(angle, roundness); let squash = tip.inverse(); - // Width profiles use distance along the spine, so measure pressure on the same squashed - // points that the outline reads for a non-round tip. + // Width profiles use distance along the spine, so measure the pressure or wheel on the same + // squashed points that the outline reads for a non-round tip. let mapped_samples: Vec = if roundness < 100.0 { samples .iter() @@ -538,7 +538,7 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { } else { samples.clone() }; - let pressure = size_pressure(p, &mapped_samples, C)?; + let pressure = size_profile(p, &mapped_samples, C)?; let pts: Vec = samples.into_iter().map(|s| s.pt).collect(); let mapped_pts: Vec = mapped_samples.into_iter().map(|s| s.pt).collect(); // The widest the brush gets: the area merges look in. @@ -561,7 +561,7 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { None => pressure_region(&spine(None), size, *variation, prof)?, } } - // A click: one dab as wide as the pen pressed. + // A click: one dab as wide as the pen pressed or the wheel was set. (Some((prof, variation)), false) => brush_region(&mapped_pts, vectorcraft_tools::draw2::pressure_size(size, *variation, prof.at(0.0))), (None, _) => { let fitted = fidelity diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 75d7d081d9..48145a0361 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -3,7 +3,7 @@ use serde_json::json; use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::{FillRule, PathData, Point}; -use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; +use vectorcraft_tools::{Mods, PenPose, PointerEvent, PointerKind, ToolKey}; use crate::tooling::{UiRequest, ViewInfo}; use crate::*; @@ -730,6 +730,69 @@ fn blob_brush_size_follows_the_pen_pressure() { assert!(inside(&s, drawn, 290.0, 707.0) && !inside(&s, drawn, 110.0, 703.0), "the tool's stroke follows the pen"); } +/// Blob Brush Tool Options' Size set to Stylus Wheel: the brush is Size − Variation wide where an +/// airbrush pen's finger wheel was at 0 and Size + Variation where it was at 1, in a drag, a click +/// and with a tip that is not round. A stroke without a wheel keeps the Size, pressure does not +/// change it, and an unknown mode or a wheel out of its range is refused with nothing painted. +#[test] +fn blob_brush_size_follows_the_stylus_wheel() { + let mut s = session(); + let inside = |s: &Session, id: NodeId, x: f64, y: f64| { + vectorcraft_geom::hit::fill_contains(&path(s, id).to_bezpath(), FillRule::NonZero, Point::new(x, y)) + }; + let blob = |s: &mut Session, p: serde_json::Value| NodeId(s.execute("path.blob", &p).unwrap()["id"].as_u64().unwrap()); + // The wheel at 0 at the left end and at 1 at the right: about 2 pt wide to 18 pt wide. + let wheeled = |y: f64, wheel: &dyn Fn(f64) -> serde_json::Value| { + (0..=20).map(|i| json!([100.0 + f64::from(i) * 10.0, y, null, null, null, null, wheel(f64::from(i) / 20.0)])).collect::>() + }; + let tip = json!({"size": 10, "sizeMode": "stylusWheel", "sizeVariation": 8, "merge": false}); + let a = blob(&mut s, with(&tip, json!({"points": wheeled(100.0, &|w| json!(w))}))); + assert!(inside(&s, a, 290.0, 107.0) && !inside(&s, a, 110.0, 103.0), "wide where the wheel was at 1, thin where at 0"); + let b = blob(&mut s, with(&tip, json!({"points": wheeled(200.0, &|w| json!(1.0 - w))}))); + assert!(inside(&s, b, 110.0, 207.0) && !inside(&s, b, 290.0, 203.0), "the other way round"); + // No wheel at any point, and pressure without a wheel: 10 pt wide all along. + let none = blob(&mut s, with(&tip, json!({"points": wheeled(300.0, &|_| json!(null))}))); + let pressed = (0..=20).map(|i| json!([100.0 + f64::from(i) * 10.0, 400.0, f64::from(i) / 20.0])).collect::>(); + let pressure = blob(&mut s, with(&tip, json!({"points": pressed}))); + for (id, y) in [(none, 300.0), (pressure, 400.0)] { + assert!(inside(&s, id, 110.0, y + 3.0) && inside(&s, id, 290.0, y + 3.0) && !inside(&s, id, 290.0, y + 7.0), "10 pt at y {y}"); + } + // A click paints one dab as wide as the wheel gives. + let wide = blob(&mut s, with(&tip, json!({"points": [[100, 500, null, null, null, null, 1]]}))); + let thin = blob(&mut s, with(&tip, json!({"points": [[300, 500, null, null, null, null, 0]]}))); + assert!(inside(&s, wide, 100.0, 508.0) && !inside(&s, thin, 300.0, 503.0), "a dab follows the wheel"); + // A 25% round tip lying level: about 0.5 pt tall at the left end to 4.5 pt at the right. + let flat = blob(&mut s, with(&tip, json!({"roundness": 25, "points": wheeled(600.0, &|w| json!(w))}))); + assert!(inside(&s, flat, 290.0, 601.9) && !inside(&s, flat, 110.0, 601.0), "a flat tip follows the wheel"); + // Refused, with the document and its undo steps as they were. + let (before, undo) = (paths(&s).len(), s.doc().unwrap().history.undo.len()); + for (bad, key) in [ + (json!({"points": wheeled(700.0, &|w| json!(w)), "sizeMode": "tilt", "sizeVariation": 8}), "sizeMode"), + (json!({"points": [[0, 700, null, null, null, null, 1.5], [10, 700]], "sizeMode": "stylusWheel", "sizeVariation": 8}), "wheel"), + ] { + let err = s.execute("path.blob", &bad).unwrap_err(); + assert!(err.to_string().contains(key), "{err}"); + } + assert_eq!((paths(&s).len(), s.doc().unwrap().history.undo.len()), (before, undo), "nothing changed"); + // The tool records the wheel while its Size varies with it. + let v = view(); + s.select_tool("blobBrush", v).unwrap(); + s.set_tool_option("sizeMode", &json!("stylusWheel")); + s.set_tool_option("sizeVariation", &json!(8)); + assert_eq!(s.tool_options()["sizeMode"], json!("stylusWheel")); + let ev = |kind, i: i32| PointerEvent { + pen: Some(PenPose { wheel: Some(i as f32 / 20.0), ..PenPose::default() }), + ..PointerEvent::new(kind, 100.0 + f64::from(i) * 10.0, 800.0) + }; + s.pointer(&ev(PointerKind::Down, 0), v).unwrap(); + for i in 1..20 { + s.pointer(&ev(PointerKind::Drag, i), v).unwrap(); + } + s.pointer(&ev(PointerKind::Up, 20), v).unwrap(); + let (drawn, _) = paths(&s).into_iter().find(|(_, p)| p.control_bounds().is_some_and(|b| b.y0 > 750.0)).unwrap(); + assert!(inside(&s, drawn, 290.0, 807.0) && !inside(&s, drawn, 110.0, 803.0), "the tool's stroke follows the wheel"); +} + /// Eraser Tool Options' Size set to Pressure (#3961): the tip is Size − Variation across where the /// pen pressed lightest and Size + Variation where it pressed hardest; Fixed erases at the Size. #[test] diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 69d382f2dc..db0f24740e 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -489,7 +489,10 @@ fn bad_option_values_are_errors_that_set_nothing() { (json!({"key": "bogus", "value": 1}), "tool `smooth`: unknown option `bogus`"), (json!({"tool": "pencil", "values": {"closeWithin": 5, "fidelity": "x"}}), "tool `pencil`: `fidelity` must be a number from 0.01 to 100"), (json!({"tool": "pencil", "key": "fill", "value": "yes"}), "tool `pencil`: `fill` must be true or false"), - (json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`"), + ( + json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), + "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`, `stylusWheel`", + ), (json!({"tool": "eraser", "key": "fidelity", "value": 4}), "tool `eraser`: unknown option `fidelity`"), (json!({"tool": "polygon", "key": "sides", "value": 2}), "tool `polygon`: `sides` must be a whole number from 3 to 1000"), ( diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 3c663006e5..1ec3d1eaf7 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -87,6 +87,11 @@ pub fn pressure_size(size: f64, variation: f64, pressure: f64) -> f64 { /// The narrowest a Blob Brush or Eraser stroke gets, in points (their Size field's minimum). pub const MIN_BRUSH_SIZE: f64 = 0.1; +/// The modes the Blob Brush's Size takes (`sizeMode`). The Eraser's Size takes every +/// [`vectorcraft_brush::Variation`]. +pub const BLOB_SIZE_MODES: [vectorcraft_brush::Variation; 3] = + [vectorcraft_brush::Variation::Fixed, vectorcraft_brush::Variation::Pressure, vectorcraft_brush::Variation::StylusWheel]; + /// A pen's tilt as a lean on the page (each tilt's tangent) and its angle from upright in degrees, /// as Pointer Events' tiltX and tiltY convert to an altitude and an azimuth. fn pen_lean(tilt: [f32; 2]) -> ([f64; 2], f64) { diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index dc123e6cc1..5eba8dc7d8 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -132,9 +132,10 @@ pub struct GestureTool { pub fidelity: f64, /// Brush / eraser diameter in points (the Eraser's across its tip's long axis). pub size: f64, - /// Blob Brush and Eraser Tool Options' Size mode: Fixed or Pressure for the Blob Brush (with - /// Pressure the tip is `size` − `size_variation` wide at the lightest pen pressure and `size` + - /// `size_variation` at the heaviest), and any [`Variation`] for the Eraser. + /// Blob Brush and Eraser Tool Options' Size mode: Fixed, Pressure or Stylus Wheel for the Blob + /// Brush (with Pressure the tip is `size` − `size_variation` wide at the lightest pen pressure + /// and `size` + `size_variation` at the heaviest, and with Stylus Wheel from one end of an + /// airbrush pen's finger wheel travel to the other), and any [`Variation`] for the Eraser. pub size_mode: Variation, /// Blob Brush and Eraser Tool Options' Size Variation, in points. pub size_variation: f64, @@ -987,12 +988,13 @@ impl GestureTool { } } - /// Give the Eraser's last stroke sample the pen's tilt and rotation of the event `ev`, a drag - /// within a pixel of that sample that adds none: a pen turned or tilted in place turns its tip - /// there, in the outline and in what the release erases. The sample keeps its pressure, which - /// the area outline of the drag was built with, and its pose when `ev` reads none. + /// Give the Eraser's or the Blob Brush's last stroke sample the pen's tilt, rotation and wheel + /// of the event `ev`, a drag within a pixel of that sample that adds none: a pen turned or + /// tilted in place, or its wheel turned there, changes its tip there, in the outline and in + /// what the release erases or paints. The sample keeps its pressure, which the area outline of + /// the drag was built with, and its pose when `ev` reads none. fn refresh_last_pose(&mut self, ev: &PointerEvent) { - if self.id != "eraser" || self.poses.len() != self.points.len() || ev.pen.is_none() { + if !matches!(self.id, "eraser" | "blobBrush") || self.poses.len() != self.points.len() || ev.pen.is_none() { return; } let pose = ev.pen.map(PenPose::sanitized); @@ -1112,8 +1114,8 @@ impl GestureTool { } /// The Blob Brush's or the Eraser's tip at the pointer, before and while painting: its outline - /// `size` across at its angle and roundness (the Eraser's as the pen varies them while it - /// erases, [`Self::tip_now`]), at the zoom, black on a white halo so it reads on + /// `size` across at its angle and roundness (as the pen varies them while it erases or + /// paints, [`Self::tip_now`]), at the zoom, black on a white halo so it reads on /// any art. Precise cursors show only the crosshair, and smoothing shows no tip. fn tip_outline(&self, cx: &ToolContext) -> Vec { let Some(at) = self.tip_at.filter(|_| !self.smoothing && !cx.precise_cursors) else { return vec![] }; @@ -1261,7 +1263,7 @@ impl GestureTool { outline.filter(|o| !o.elements().is_empty()) } - /// Does the tool's Size take Fixed or Pressure (the Blob Brush and the Eraser)? + /// Does the tool's Size take a variation mode (the Blob Brush and the Eraser)? fn varies_size(&self) -> bool { matches!(self.id, "blobBrush" | "eraser") } @@ -1352,13 +1354,19 @@ impl GestureTool { /// plus it as the pen reads now (the pressure once the pen has pressed less than fully, the /// tilt, rotation and wheel of the last point, and the bearing of the last point the pen leaned 1° or /// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed and a - /// pen that gives no reading, the values themselves. The Blob Brush's are its own values. + /// pen that gives no reading, the values themselves. The Blob Brush's size follows the pen the + /// same way while it paints, as `path.blob` reads the stroke, and its angle and roundness are + /// its own values (a roundness of 0 included). fn tip_now(&self) -> [f64; 3] { - if self.id != "eraser" || !self.active { + if !matches!(self.id, "eraser" | "blobBrush") || !self.active { return [self.angle, self.roundness, self.size]; } let pressure = if self.light { self.pressures.last().map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; - self.tip_for(pressure, self.poses.last().copied().flatten(), self.bearing) + let tip = self.tip_for(pressure, self.poses.last().copied().flatten(), self.bearing); + if self.id == "blobBrush" { + return [self.angle, self.roundness, tip[2]]; + } + tip } /// The tip's angle, roundness and size for a pen at `pressure` held as `pose`, leaning toward @@ -2085,10 +2093,10 @@ impl Tool for GestureTool { match key { "fidelity" => self.fidelity = v.as_f64().unwrap_or(self.fidelity).clamp(super::min_fidelity(self.id), 100.0), "size" => self.size = v.as_f64().unwrap_or(self.size).clamp(0.1, 1000.0), - // The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size - // take any mode. + // The Blob Brush's Size is Fixed, Pressure or Stylus Wheel; the Eraser's Angle, + // Roundness and Size take any mode. "sizeMode" if self.varies_size() => match v.as_str().and_then(Variation::parse) { - Some(m) if self.id == "eraser" || matches!(m, Variation::Fixed | Variation::Pressure) => self.size_mode = m, + Some(m) if self.id == "eraser" || super::BLOB_SIZE_MODES.contains(&m) => self.size_mode = m, _ => {} }, "angleMode" if self.id == "eraser" => self.angle_mode = v.as_str().and_then(Variation::parse).unwrap_or(self.angle_mode), @@ -2132,9 +2140,9 @@ impl Tool for GestureTool { "editWithin" | "closeWithin" => c::number(key, v, 0.0, 100.0), "angleVariation" => c::number(key, v, 0.0, 180.0), "roundnessVariation" => c::number(key, v, 0.0, 100.0), - // The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size - // take any mode (`set_option`). - "sizeMode" if self.id != "eraser" => c::one_of(key, v, &[Variation::Fixed.id(), Variation::Pressure.id()]), + // The Blob Brush's Size is Fixed, Pressure or Stylus Wheel; the Eraser's Angle, + // Roundness and Size take any mode (`set_option`). + "sizeMode" if self.id != "eraser" => c::one_of(key, v, &super::BLOB_SIZE_MODES.map(Variation::id)), "sizeMode" | "angleMode" | "roundnessMode" => c::one_of(key, v, &Variation::ALL.map(Variation::id)), "fill" | "altSmooth" | "livePreview" | "liveFit" | "keepSelected" | "mergeOnlySelection" => c::boolean(key, v), _ => Err(c::unknown(key)), diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 1ffcf1c37b..5df801b3a0 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -3205,7 +3205,10 @@ fn the_eraser_tip_follows_its_variation_modes() { assert_eq!(t.check_option("angleMode", &json!("wheel")), Err(format!("`angleMode` {modes}"))); assert_eq!(t.check_option("angleVariation", &json!(181)), Err("`angleVariation` must be a number from 0 to 180".into())); assert_eq!(t.check_option("roundnessVariation", &json!(500)), Err("`roundnessVariation` must be a number from 0 to 100".into())); - assert_eq!(GestureTool::new("blobBrush").check_option("sizeMode", &json!("tilt")), Err("`sizeMode` must be one of `fixed`, `pressure`".into())); + assert_eq!( + GestureTool::new("blobBrush").check_option("sizeMode", &json!("tilt")), + Err("`sizeMode` must be one of `fixed`, `pressure`, `stylusWheel`".into()) + ); // A mode it does not have leaves the mode as it was; a Variation is kept within its range. t.set_option("angleMode", &json!("wheel")); t.set_option("roundnessVariation", &json!(500)); @@ -3243,7 +3246,7 @@ fn the_eraser_tip_follows_its_variation_modes() { t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); near(tip(&t), (190.0, 47.5, 210.0, 52.5)); t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); - // The Blob Brush's Size is Fixed or Pressure, and its Angle and Roundness have no menus. + // The Blob Brush's Size is Fixed, Pressure or Stylus Wheel, and its Angle and Roundness have no menus. let mut b = GestureTool::new("blobBrush"); b.set_option("sizeMode", &json!("tilt")); b.set_option("angleMode", &json!("rotation")); @@ -3253,6 +3256,62 @@ fn the_eraser_tip_follows_its_variation_modes() { assert_eq!(b.options()["sizeMode"], json!("pressure")); } +/// The Blob Brush's Size on Stylus Wheel follows the wheel the pen recorded, in the tip outline +/// while it paints (its roundness kept as set, 0% included) and in the points the release sends; +/// a pen that gives no wheel keeps the Size. +#[test] +fn the_blob_brush_size_follows_the_stylus_wheel() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let tip = |t: &GestureTool| match &t.overlays(&cx)[..] { + [.., Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. }] => vectorcraft_geom::Shape::bounding_box(path), + o => panic!("{o:?}"), + }; + let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| { + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let mut t = GestureTool::new("blobBrush"); + assert_eq!(t.check_option("sizeMode", &json!("stylusWheel")), Ok(())); + for (k, v) in [("size", json!(20)), ("roundness", json!(50)), ("sizeMode", json!("stylusWheel")), ("sizeVariation", json!(8))] { + t.set_option(k, &v); + } + assert_eq!((t.options()["sizeMode"].clone(), t.options()["sizeVariation"].clone()), (json!("stylusWheel"), json!(8.0))); + // Before a press the outline is the set tip, 20 by 10 pt. + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 100.0, 50.0)); + near(tip(&t), (90.0, 45.0, 110.0, 55.0)); + // The wheel at the far end of its travel gives 28 by 14 pt, and half way 20 by 10. + let wheel = |w: Option| Some(PenPose { tilt: None, rotation: None, wheel: w }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + near(tip(&t), (186.0, 43.0, 214.0, 57.0)); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(0.5)), ..PointerEvent::new(PointerKind::Drag, 300.0, 50.0) }); + near(tip(&t), (290.0, 45.0, 310.0, 55.0)); + // The wheel turned with the pen held in place: the tip there and the release follow it. + t.pointer(&cx, &PointerEvent { pen: wheel(Some(0.0)), ..PointerEvent::new(PointerKind::Drag, 300.0, 50.0) }); + near(tip(&t), (294.0, 47.0, 306.0, 53.0)); + let acts = t.pointer(&cx, &PointerEvent { pen: wheel(Some(0.0)), ..PointerEvent::new(PointerKind::Up, 300.0, 50.0) }); + let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") }; + assert_eq!((c.as_str(), &v["sizeMode"], &v["sizeVariation"]), ("path.blob", &json!("stylusWheel"), &json!(8.0))); + assert_eq!( + v["points"], + json!([[100.0, 50.0, null, null, null, null, 1.0], [200.0, 50.0, null, null, null, null, 1.0], [300.0, 50.0, null, null, null, null, 0.0]]) + ); + // A pen without a wheel keeps the set tip. + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + near(tip(&t), (190.0, 45.0, 210.0, 55.0)); + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); + // A 0% round tip stays as flat as set while the wheel widens it. + t.set_option("roundness", &json!(0)); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + let flat = tip(&t); + assert!((flat.width() - 28.0).abs() < 0.01 && flat.height() < 0.1, "{flat:?}"); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); +} + /// An Eraser value on Stylus Wheel follows the wheel the pen recorded, in the tip outline while it /// erases and in the points the release sends; a pen that gives no wheel reads half way, the value /// itself. diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index aa793afef2..924f2de219 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -185,7 +185,7 @@ struct Varied<'a> { /// The rows of a tip value with a variation menu: the value with its menu of `modes` before the /// field, then the Variation field the menu's modes other than Fixed take (greyed while the -/// menu is Fixed). The Blob Brush's Size offers Fixed and Pressure, and the Eraser's Angle, +/// menu is Fixed). The Blob Brush's Size offers Fixed, Pressure and Stylus Wheel, and the Eraser's Angle, /// Roundness and Size every mode. fn varied(ui: &mut egui::Ui, d: &mut Dialog, v: &Varied, modes: &[Variation]) { let (mode_key, var_key) = (format!("{}Mode", v.key), format!("{}Variation", v.key)); @@ -296,7 +296,7 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } // The Eraser's Size rows are above. if !eraser && d.fields.contains_key("sizeMode") { - size_rows(ui, d, &[Variation::Fixed, Variation::Pressure]); + size_rows(ui, d, &vectorcraft_tools::draw2::BLOB_SIZE_MODES); } else if !eraser && d.fields.contains_key("size") { number(ui, d, ("size", tl!("Size:")), "pt", 1, (0.1, 1000.0)); } diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index e324bbbd45..bde80b55f3 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -425,6 +425,26 @@ fn the_blob_brush_and_eraser_size_can_follow_the_pen_pressure() { assert!(!text.contains("Variation:") && !text.contains("Fixed"), "{text}"); } +/// The Blob Brush's Size menu offers Stylus Wheel beside Fixed and Pressure, Fixed still the +/// default; OK sets it with the Variation. +#[test] +fn the_blob_brush_size_offers_the_stylus_wheel() { + let mut app = app(); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + assert!(painted(&mut app).contains("Fixed")); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.str("sizeMode"), "fixed", "Fixed by default"); + d.fields.insert("sizeMode".into(), json!("stylusWheel")); + d.fields.insert("sizeVariation".into(), json!(5)); + let text = painted(&mut app); + assert!(text.contains("Stylus Wheel") && !text.contains("Fixed"), "{text}"); + super::super::confirm(&mut app).unwrap(); + let o = app.session.tool_options_of("blobBrush"); + assert_eq!((o["sizeMode"].clone(), o["sizeVariation"].as_f64()), (json!("stylusWheel"), Some(5.0))); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + assert!(painted(&mut app).contains("Stylus Wheel")); +} + /// Eraser Tool Options gives Angle, Roundness and Size each a variation menu with a Variation /// field; OK sets the modes and Variations. The Blob Brush keeps one menu, on Size. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..2dd8666c9d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7026,6 +7026,16 @@ outline of the area a drag covers takes, at each step, the tip the pen's reading value shows as the value itself there, since the release draws it. `tool.setOption {tool: "eraser"}` takes the same keys, with `sizeVariation` from 0 to 1000. +`path.blob` (the Blob Brush) takes `sizeMode` with `sizeVariation` (points, 0 to 1000), as the Size menu of Blob Brush +Tool Options sets it: `"fixed"` (the default), `"pressure"` or `"stylusWheel"`. Pressure goes from the size less the +variation where the pen presses lightest to the size plus it where the pen presses hardest. Stylus Wheel goes from the +size less the variation at 0 to the size plus it at 1 of an airbrush pen's finger wheel, the seventh value of each +point; a point without a wheel counts as 0.5, the size itself, and a stroke with no wheel reading, such as a mouse +drag, paints at the size. Which way the wheel runs and the size itself without a reading are VectorCraft's own rules. +The command refuses another mode with an error that names `sizeMode`, and the document does not change. In the +desktop app the Blob Brush's tip outline at the pointer takes the size the pen gives while it paints. +`tool.setOption {tool: "blobBrush"}` takes `sizeMode` and `sizeVariation` too. + `path.eraseRegion {rect: [x, y, width, height]}` takes a rectangle in place of `points` and erases everything inside it from the paths (selected, or all), as an Alt-drag with the Eraser does ([Eraser tool reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133)). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..8e0abd5a4c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2066,6 +2066,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; Windows pointer messages have no field for it, and the web build does not read it yet. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft). + - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). From 2389cdfd7f0662dd33ab9f56baeee5e886a1208a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:03:40 -0800 Subject: [PATCH 012/101] Smooth: Smooth Tool Options' Smoothness sets how strongly a drag smooths Smooth Tool Options gets a Smoothness setting under Fidelity, from 0% to 100%, where a higher value leaves a smoother path, as the help page describes the setting: https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=164 - path.smoothRegion takes an optional `smoothness` (0 to 100, 50 when left out). It scales the spread of the averaging done before the refit in proportion: none at 0, today's spread at 50, twice it at 100. A value outside 0 to 100 is an error and changes nothing. - The Smooth tool keeps the option with its preferences and sends it with each drag; Alt smoothing with the Pencil, Paintbrush and Blob Brush uses it, as it already uses the Smooth tool's Fidelity. tool.setOption refuses a value outside 0 to 100. - The default and the way the percentage scales the smoothing are VectorCraft's own; the default keeps today's strength. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/draw2/commands.rs | 2 +- crates/engine/src/cmd/draw2/smooth.rs | 20 +++++-- crates/engine/src/tests/draw2.rs | 61 +++++++++++++++++++- crates/engine/src/tests/toolsettings.rs | 48 +++++++++++++++ crates/engine/src/tooling.rs | 11 +++- crates/tools/src/draw2/gesture.rs | 28 +++++++-- crates/tools/src/draw2/gesture/tests.rs | 49 +++++++++++++++- crates/tools/src/settings.rs | 2 +- crates/ui-egui/src/dialogs/freehand.rs | 31 +++++++++- crates/ui-egui/src/dialogs/freehand/tests.rs | 32 +++++++++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.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 | 15 ++++- docs/target-app-parity.md | 1 + 40 files changed, 303 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index e4846367b5..762616fdc3 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), smoothness?: % (50; 0 to 100, an error outside it: how far along the path each point is averaged before the refit, in proportion: none at 0, twice as far as at 50 at 100)} 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}", has_selection, smooth_region ), diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..9455a92cee 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -2,17 +2,23 @@ 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}; use super::{ - Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, json, - number_or, po, + Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, bad, + json, number_or, po, }; // ---------- Smooth ---------- /// The spread (points) of the Gaussian the Smooth tool smooths a path along its length with before -/// refitting it, as a share of the tool's reach: a third, so each point is averaged with the stretch -/// of path within the reach on either side of it. VectorCraft's own value. +/// refitting it at the default Smoothness ([`SMOOTH_SMOOTHNESS`]), as a share of the tool's reach: a +/// third, so each point is averaged with the stretch of path within the reach on either side of it. +/// The spread grows in proportion to the Smoothness, from none at 0% to twice this at 100%. +/// VectorCraft's own value. const SMOOTH_SPREAD: f64 = 1.0 / 3.0; +/// The Smoothness (percent) `path.smoothRegion` smooths with when the drag leaves it out. VectorCraft's +/// own value. +const SMOOTH_SMOOTHNESS: f64 = 50.0; + /// The degrees by which a path must turn at an anchor, and over the tool's reach and twice its reach /// on either side of it, for the Smooth tool to keep the anchor as a corner ([`smooth_corners`]): a /// turn of more than 57.5°, an angle inside the corner of less than 122.5°. VectorCraft's own value, @@ -735,7 +741,11 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { let pts = points_param(p, "points", C)?; let radius = number_or(p, "radius", 12.0, C)?.max(0.0); let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE); - let sigma = radius * SMOOTH_SPREAD; + let smoothness = number_or(p, "smoothness", SMOOTH_SMOOTHNESS, C)?; + if !(0.0..=100.0).contains(&smoothness) { + return Err(bad(C, "`smoothness` must be from 0 to 100")); + } + let sigma = radius * SMOOTH_SPREAD * smoothness / SMOOTH_SMOOTHNESS; let st = s.doc()?; let mut plan = vec![]; let (mut before, mut after) = (0, 0); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 75d7d081d9..d8494b2c1a 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -1794,6 +1794,64 @@ fn smooth_region_refits_at_the_tolerance_sent_at_any_zoom() { } } +/// A line from (100, 200) to (400, 200) jagged by up to 6 pt either way, the same every time. +fn jagged_line_anchors() -> Vec { + let mut seed = 7u64; + (0..=60) + .map(|i| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let noise = ((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0; + json!({"x": 100.0 + f64::from(i) * 5.0, "y": 200.0 + 6.0 * noise}) + }) + .collect() +} + +/// The path a `path.smoothRegion` drag along [`jagged_line_anchors`] leaves with `smoothness` (left +/// out for null), and the mean distance of its points from the line y = 200. +fn smoothed_jagged_line(smoothness: serde_json::Value) -> (PathData, f64) { + let mut s = session(); + let id = smooth_test_path(&mut s, &jagged_line_anchors(), false); + let drag: Vec<_> = (0..=64).map(|i| json!([90.0 + f64::from(i) * 5.0, 200.0])).collect(); + s.execute("path.smoothRegion", &json!({"points": drag, "radius": 12, "fidelity": 2.5, "smoothness": smoothness})).unwrap(); + let p = path(&s, id); + let samples = smooth_test_samples(&p); + let off = samples.iter().map(|q| (q.y - 200.0).abs()).sum::() / samples.len() as f64; + (p, off) +} + +/// Smooth Tool Options' Smoothness: the higher it is, the smoother the path a drag leaves, from +/// 0% to 100%. Left out, a drag smooths at 50%. +#[test] +fn a_higher_smoothness_leaves_a_smoother_path() { + let original = { + let mut s = session(); + let id = smooth_test_path(&mut s, &jagged_line_anchors(), false); + let samples = smooth_test_samples(&path(&s, id)); + samples.iter().map(|q| (q.y - 200.0).abs()).sum::() / samples.len() as f64 + }; + let offs: Vec = [0.0, 25.0, 50.0, 75.0, 100.0].iter().map(|&x| smoothed_jagged_line(json!(x)).1).collect(); + assert!(offs[0] < original, "even 0% refits within Fidelity: {offs:?}, {original} before"); + assert!(offs.windows(2).all(|w| w[1] < w[0]), "each step up smooths more: {offs:?}"); + assert_eq!(smoothed_jagged_line(json!(null)).0, smoothed_jagged_line(json!(50)).0, "left out is 50%"); +} + +/// `path.smoothRegion` refuses a Smoothness outside 0% to 100% and changes nothing. +#[test] +fn smooth_region_refuses_a_smoothness_outside_0_to_100() { + let mut s = session(); + let id = smooth_test_path(&mut s, &jagged_line_anchors(), false); + let drag = json!({"points": [[90, 200], [250, 200], [410, 200]], "radius": 12, "fidelity": 2.5}); + for x in [json!(-1), json!(-0.001), json!(100.5), json!(101), json!(1e300)] { + refuses_with(&mut s, "path.smoothRegion", &with(&drag, json!({"smoothness": x})), "`smoothness` must be from 0 to 100"); + } + for x in [json!(0), json!(100)] { + let before = path(&s, id); + s.execute("path.smoothRegion", &with(&drag, json!({"smoothness": x}))).unwrap_or_else(|e| panic!("smoothness {x}: {e}")); + assert_ne!(path(&s, id), before, "smoothness {x} smoothed nothing"); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + /// A drag of the Smooth tool along a line jagged by up to 6 pt leaves no corner between a curve and /// a line: every anchor between the path's ends turns by at most 1°. #[test] @@ -3314,7 +3372,7 @@ fn path_eraser_width_outside_its_range_is_refused() { } /// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness, -/// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change +/// width, radius, fidelity, smoothness or tolerance given as text or as another value that is not a number, and change /// nothing; null is read as the key left out. #[test] fn drawing_commands_refuse_a_size_given_as_text() { @@ -3329,6 +3387,7 @@ fn drawing_commands_refuse_a_size_given_as_text() { ("path.eraseSegments", "width"), ("path.smoothRegion", "radius"), ("path.smoothRegion", "fidelity"), + ("path.smoothRegion", "smoothness"), ("path.joinScrub", "tolerance"), ("path.blob", "size"), ("path.blob", "fidelity"), diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 69d382f2dc..a891067567 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -473,6 +473,54 @@ fn alt_smoothing_takes_the_smooth_tools_fidelity() { } } +/// The Smoothness an Alt smoothing drag sends with `path.smoothRegion` on a selected path. +fn alt_smoothness(s: &mut Session) -> Option { + use vectorcraft_tools::Action; + let mods = Mods { alt: true, ..Default::default() }; + let mut last = vec![]; + for (kind, x, y) in [(PointerKind::Down, 50.0, 150.0), (PointerKind::Drag, 150.0, 150.0), (PointerKind::Up, 250.0, 160.0)] { + let ev = PointerEvent { mods, ..PointerEvent::new(kind, x, y) }; + last = s.with_tool_cx(ViewInfo::default(), |t, cx| t.pointer(cx, &ev)); + } + last.iter().find_map(|a| match a { + Action::Exec(c, v) if c == "path.smoothRegion" => v["smoothness"].as_f64(), + _ => None, + }) +} + +/// Smooth Tool Options' Smoothness is kept with the preferences (50% until it is set), and Alt +/// smoothing with the Pencil, Paintbrush and Blob Brush uses it. A Smoothness outside 0 to 100 is +/// an error that sets nothing. +#[test] +fn the_smooth_tools_smoothness_is_kept_and_alt_smoothing_takes_it() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + select(&mut s, "smooth"); + assert_eq!(s.tool_options()["smoothness"], json!(50.0)); + for bad in [json!(-1), json!(100.5), json!("30"), json!(null)] { + let e = s.set_tool_option_cmd(&json!({"key": "smoothness", "value": bad})).unwrap_err(); + assert_eq!(e, "tool `smooth`: `smoothness` must be a number from 0 to 100", "{bad}"); + } + assert_eq!(s.tool_options()["smoothness"], json!(50.0)); + s.set_tool_option("smoothness", &json!(80)); + assert_eq!(s.prefs.tool_settings["smooth"]["smoothness"], json!(80.0)); + for id in ["pencil", "paintbrush", "blobBrush"] { + select(&mut s, id); + if id == "pencil" { + s.set_tool_option("altSmooth", &json!(true)); + } + assert_eq!(alt_smoothness(&mut s), Some(80.0), "{id}"); + assert!(s.tool_options().get("smoothness").is_none(), "{id} has no Smoothness of its own"); + } + s.set_tool_option_cmd(&json!({"tool": "smooth", "key": "smoothness", "value": 10})).unwrap(); + assert_eq!(alt_smoothness(&mut s), Some(10.0), "the Blob Brush takes the new Smoothness"); + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved).unwrap()); + select(&mut next, "smooth"); + assert_eq!(next.tool_options()["smoothness"], json!(10.0)); +} + /// `tool.setOption` with a value of the wrong type, a number out of range, an unknown value or an /// option the tool doesn't have is an error naming the tool and the option. Nothing is set, also /// when another option given with it is good, and nothing is saved or recorded for undo. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 7c1af811ed..7b3c51d1d3 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -374,12 +374,17 @@ impl Session { } } } - // Alt switches the Pencil, Paintbrush or Blob Brush to Smooth, using Smooth Tool Options' Fidelity. + // Alt switches the Pencil, Paintbrush or Blob Brush to Smooth, using Smooth Tool Options' Fidelity + // and Smoothness. if matches!(t.id(), "pencil" | "paintbrush" | "blobBrush") && wanted("smooth") - && let Some(v) = prefs.tool_settings.get("smooth").and_then(|s| s.get("fidelity")) + && let Some(saved) = prefs.tool_settings.get("smooth") { - t.set_option("smoothFidelity", v); + for (key, alt) in [("fidelity", "smoothFidelity"), ("smoothness", "smoothSmoothness")] { + if let Some(v) = saved.get(key) { + t.set_option(alt, v); + } + } } } diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index dc123e6cc1..2a5e0f9321 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -85,6 +85,9 @@ const BAND_WORK_PER_CALL: usize = 20_000; const PREVIEW_FIDELITY_PX: f64 = 0.5; /// The Smooth tool's Fidelity (screen pixels) until Smooth Tool Options sets another. const SMOOTH_FIDELITY: f64 = 2.5; +/// The Smooth tool's Smoothness (percent) until Smooth Tool Options sets another: the strength +/// `path.smoothRegion` smooths with when a drag leaves it out. VectorCraft's own value. +const SMOOTH_SMOOTHNESS: f64 = 50.0; /// How far the pointer goes from the press point, in screen pixels, before a Shift-drag of the /// Eraser takes the 45° step it lies nearest to. const ERASER_SHIFT_PX: f64 = 3.0; @@ -168,6 +171,11 @@ pub struct GestureTool { /// The Smooth tool's Fidelity (screen pixels), used when Alt switches the Pencil, Paintbrush or /// Blob Brush to Smooth. The engine sets it from Smooth Tool Options (`smoothFidelity`). smooth_fidelity: f64, + /// Smooth Tool Options' Smoothness (percent, 0 to 100): how strongly a Smooth drag smooths the + /// path before it is refitted. The Smooth tool's own (`smoothness`), and for the Pencil, + /// Paintbrush and Blob Brush the one an Alt smoothing drag uses, which the engine sets from + /// Smooth Tool Options (`smoothSmoothness`). + smoothness: f64, /// Active drag is smoothing with the Pencil, Paintbrush or Blob Brush (Alt held). smoothing: bool, /// The pointer has moved from the press point, by any distance (a move too short to add a @@ -893,6 +901,7 @@ impl GestureTool { live_preview: true, live_fit: true, smooth_fidelity: SMOOTH_FIDELITY, + smoothness: SMOOTH_SMOOTHNESS, smoothing: false, moved: false, marquee: false, @@ -1556,7 +1565,7 @@ impl GestureTool { if pts.len() >= 2 && has_selected_smooth_path(cx) { return vec![Action::Exec( "path.smoothRegion".into(), - json!({"points": points_json(pts), "radius": radius, "fidelity": cx.tol(self.smooth_fidelity)}), + json!({"points": points_json(pts), "radius": radius, "fidelity": cx.tol(self.smooth_fidelity), "smoothness": self.smoothness}), )]; } return vec![]; @@ -1621,7 +1630,7 @@ impl GestureTool { "smooth" if pts.len() >= 2 && has_selected_smooth_path(cx) => { vec![Action::Exec( "path.smoothRegion".into(), - json!({"points": points_json(pts), "radius": radius, "fidelity": cx.tol(self.fidelity)}), + json!({"points": points_json(pts), "radius": radius, "fidelity": cx.tol(self.fidelity), "smoothness": self.smoothness}), )] } "pathEraser" if has_sel => vec![Action::Exec("path.eraseSegments".into(), json!({"points": points_json(pts), "width": cx.tol(8.0)}))], @@ -2054,7 +2063,7 @@ impl Tool for GestureTool { "closeWithin": self.close_within }) } - "smooth" => json!({"fidelity": self.fidelity}), + "smooth" => json!({"fidelity": self.fidelity, "smoothness": self.smoothness}), "blobBrush" => { json!({ "fidelity": self.fidelity, @@ -2107,6 +2116,11 @@ impl Tool for GestureTool { "smoothFidelity" if matches!(self.id, "pencil" | "paintbrush" | "blobBrush") => { self.smooth_fidelity = v.as_f64().unwrap_or(self.smooth_fidelity).clamp(super::min_fidelity("smooth"), 100.0) } + // A value that is not a number from 0 to 100 leaves the Smoothness as it is. + "smoothness" if self.id == "smooth" => self.smoothness = v.as_f64().filter(|n| (0.0..=100.0).contains(n)).unwrap_or(self.smoothness), + "smoothSmoothness" if matches!(self.id, "pencil" | "paintbrush" | "blobBrush") => { + self.smoothness = v.as_f64().filter(|n| (0.0..=100.0).contains(n)).unwrap_or(self.smoothness) + } "keepSelected" => self.keep_selected = v.as_bool().unwrap_or(self.keep_selected), "mergeOnlySelection" => self.merge_only_selection = v.as_bool().unwrap_or(self.merge_only_selection), "editWithin" => self.edit_within = v.as_f64().unwrap_or(self.edit_within).clamp(0.0, 100.0), @@ -2114,17 +2128,19 @@ impl Tool for GestureTool { _ => {} } } - /// The options the tool shows ([`Self::options`]), and the Smooth tool's Fidelity that the - /// Pencil, Paintbrush and Blob Brush smooth with while Alt is held (`smoothFidelity`). + /// The options the tool shows ([`Self::options`]), and the Smooth tool's Fidelity and Smoothness + /// that the Pencil, Paintbrush and Blob Brush smooth with while Alt is held (`smoothFidelity`, + /// `smoothSmoothness`). fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { use crate::option_check as c; - let smooth_store = key == "smoothFidelity" && matches!(self.id, "pencil" | "paintbrush" | "blobBrush"); + let smooth_store = matches!(key, "smoothFidelity" | "smoothSmoothness") && matches!(self.id, "pencil" | "paintbrush" | "blobBrush"); if !smooth_store && self.options().get(key).is_none() { return Err(c::unknown(key)); } match key { "fidelity" => c::number(key, v, super::min_fidelity(self.id), 100.0), "smoothFidelity" => c::number(key, v, super::min_fidelity("smooth"), 100.0), + "smoothness" | "smoothSmoothness" => c::number(key, v, 0.0, 100.0), "size" => c::number(key, v, 0.1, 1000.0), "sizeVariation" => c::number(key, v, 0.0, 1000.0), "angle" => c::number(key, v, -180.0, 180.0), diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 1ffcf1c37b..c28adae3fe 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -651,7 +651,10 @@ fn blob_brush_alt_switches_to_the_smooth_tool() { let acts = drag_held(&mut t, &cx, &stroke, alt); assert!(acts[..acts.len() - 1].iter().all(|a| a.is_empty()), "{acts:?}"); let v = smoothed(&acts).unwrap_or_else(|| panic!("{acts:?}")); - assert_eq!(v, json!({"points": [[50.0, 150.0], [150.0, 150.0], [250.0, 160.0]], "radius": cx.tol(12.0), "fidelity": cx.tol(SMOOTH_FIDELITY)})); + assert_eq!( + v, + json!({"points": [[50.0, 150.0], [150.0, 150.0], [250.0, 160.0]], "radius": cx.tol(12.0), "fidelity": cx.tol(SMOOTH_FIDELITY), "smoothness": SMOOTH_SMOOTHNESS}) + ); // Mid-drag the cursor stays the Smooth tool's when Alt is let go, and the line is thin with // no length label. t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt)); @@ -1674,6 +1677,50 @@ fn alt_smoothing_uses_the_smooth_tools_fidelity() { } } +/// The Smooth tool sends Smooth Tool Options' Smoothness (50% until it is set) with each drag, and +/// an Alt smoothing drag with the Pencil, Paintbrush or Blob Brush sends the one the engine gives it +/// (`smoothSmoothness`). A value that is not a number from 0 to 100 is refused and sets nothing. +#[test] +fn smooth_drags_send_the_smoothness() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let pts = [(50.0, 150.0), (150.0, 150.0), (250.0, 160.0)]; + let smoothness = |acts: &[Vec]| match acts.last().and_then(|a| a.first()) { + Some(Action::Exec(c, v)) if c == "path.smoothRegion" => v["smoothness"].as_f64(), + a => panic!("expected path.smoothRegion, got: {a:?}"), + }; + let mut t = GestureTool::new("smooth"); + assert_eq!(t.options()["smoothness"], json!(50.0)); + assert_eq!(smoothness(&drag(&mut t, &cx, &pts, Mods::default())), Some(50.0)); + for bad in [json!(-1), json!(100.5), json!("30"), json!(true)] { + assert_eq!(t.check_option("smoothness", &bad), Err("`smoothness` must be a number from 0 to 100".into()), "{bad}"); + t.set_option("smoothness", &bad); + assert_eq!(t.options()["smoothness"], json!(50.0), "{bad}"); + } + for ok in [0.0, 75.0, 100.0] { + assert_eq!(t.check_option("smoothness", &json!(ok)), Ok(())); + t.set_option("smoothness", &json!(ok)); + assert_eq!(smoothness(&drag(&mut t, &cx, &pts, Mods::default())), Some(ok)); + } + let alt = Mods { alt: true, ..Default::default() }; + for (id, alt_smooth) in [("pencil", true), ("blobBrush", false), ("paintbrush", false)] { + let mut t = GestureTool::new(id); + t.set_option("altSmooth", &json!(alt_smooth)); + assert_eq!(smoothness(&drag_held(&mut t, &cx, &pts, alt)), Some(50.0), "{id}"); + assert_eq!(t.check_option("smoothSmoothness", &json!(101)), Err("`smoothSmoothness` must be a number from 0 to 100".into()), "{id}"); + t.set_option("smoothSmoothness", &json!(101)); + t.set_option("smoothness", &json!(20.0)); + assert_eq!(smoothness(&drag_held(&mut t, &cx, &pts, alt)), Some(50.0), "{id}: only smoothSmoothness sets it"); + t.set_option("smoothSmoothness", &json!(20.0)); + assert_eq!(smoothness(&drag_held(&mut t, &cx, &pts, alt)), Some(20.0), "{id}"); + assert!(t.options().get("smoothness").is_none() && t.options().get("smoothSmoothness").is_none(), "{id}"); + } +} + /// The Smooth tool's Fidelity is in screen pixels: the Smooth tool and an Alt smoothing drag with /// the Pencil, Paintbrush or Blob Brush send it in points at Fidelity / zoom, so a drag smooths as /// much on screen at any zoom. diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 1d9d8c4a54..cfb25a2030 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -63,7 +63,7 @@ const ROWS: &[Row] = &[ // Pencil Tool Options' Alt key toggles to Smooth Tool, Live preview and Live curve fitting (the // Paintbrush has none of them). (&["pencil"], None, &["altSmooth", "livePreview", "liveFit"]), - (&["smooth"], None, &["fidelity"]), + (&["smooth"], None, &["fidelity", "smoothness"]), (&["blobBrush", "eraser"], None, &["size", "sizeMode", "sizeVariation"]), (&["blobBrush"], None, &["fidelity", "keepSelected", "mergeOnlySelection"]), // Eraser Tool Options' tip shape. diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index aa793afef2..8be35b078b 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -4,7 +4,7 @@ //! (Live curve fitting, on: its preview fits the stroke while it is drawn). //! //! Fields: `tool`; `fidelity` (screen pixels for the Pencil, Paintbrush and Smooth, points for the -//! Blob Brush), `fill` (Pencil and +//! Blob Brush), `smoothness` (percent, 0 to 100; Smooth), `fill` (Pencil and //! Paintbrush), `keepSelected` (Pencil, Paintbrush and Blob Brush), `mergeOnlySelection` (Blob //! Brush), `closeWithin` and `editWithin` (screen pixels, 0 turns it off; Pencil and Paintbrush), //! `angle` (degrees) and `roundness` (percent; Blob Brush and Eraser), `livePreview` (Pencil: the stroke shows @@ -35,8 +35,9 @@ pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_wid pub const TOOLS: [&str; 5] = ["pencil", "paintbrush", "smooth", "blobBrush", "eraser"]; /// The options the dialog edits, in the order it shows them (a tool has those it reports). -const KEYS: [&str; 18] = [ +const KEYS: [&str; 19] = [ "fidelity", + "smoothness", "angle", "angleMode", "angleVariation", @@ -259,11 +260,37 @@ fn fidelity(ui: &mut egui::Ui, d: &mut Dialog) { }); } +/// The Smooth tool's Smoothness rows: the label on a line of its own, then a slider from 0% to 100% +/// across the row with the field at its end, both in whole percent. +fn smoothness(ui: &mut egui::Ui, d: &mut Dialog) { + let t = Tokens::get(ui.ctx()); + let v = d.f64("smoothness", 50.0); + let rail_w = label_w(ui); + let mut new = None; + ui.label(egui::RichText::new(tl!("Smoothness:")).size(12.5).color(t.text)); + ui.horizontal(|ui| { + let (shown, at) = (widgets::SliderValue::field(v, 0.0..=100.0, "%", 0), (v / 100.0) as f32); + let (x, _, keyed) = + widgets::color_slider_stepped(ui, "freehand-smoothness", tl!("Smoothness:"), Some(shown), at, rail_w, &|_| t.input_border); + new = x.map(|x| (f64::from(x.clamp(0.0, 1.0)) * 100.0).round()).or(keyed); + if let Some(x) = widgets::range_field(ui, "freehand-smoothness-field", v, 0.0..=100.0, "%", 0, FIELD_W) { + new = Some(x); + } + }); + if let Some(n) = new.filter(|n| *n != v) { + d.fields.insert("smoothness".into(), json!(n)); + } +} + fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if d.fields.contains_key("fidelity") { fidelity(ui, d); ui.add_space(10.0); } + if d.fields.contains_key("smoothness") { + smoothness(ui, d); + ui.add_space(10.0); + } let eraser = d.fields.contains_key("angleMode"); if eraser { // The Eraser: Angle, Roundness and Size each with every variation mode. diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index e324bbbd45..b250f627ee 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -46,6 +46,34 @@ fn a_refused_fidelity_keeps_the_dialog_open() { assert_eq!(app.session.tool_options_of("smooth")["fidelity"], json!(5.0)); } +/// Smooth Tool Options shows Smoothness under Fidelity, at 50% until it is set, and OK sets it; a +/// Smoothness the tool refuses keeps the dialog open with nothing set. The other freehand tools have +/// no Smoothness. +#[test] +fn smooth_tool_options_set_the_smoothness() { + let mut app = app(); + app.run("tool.options", json!({"tool": "smooth"})).unwrap(); + let text = painted(&mut app); + assert!(text.contains("Smoothness:") && text.contains("50%"), "{text}"); + assert!(text.find("Fidelity:") < text.find("Smoothness:"), "{text}"); + app.ui.dialog.as_mut().unwrap().fields.insert("smoothness".into(), json!(120)); + let e = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(e, "tool `smooth`: `smoothness` must be a number from 0 to 100"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + assert_eq!(app.session.tool_options_of("smooth")["smoothness"], json!(50.0)); + app.ui.dialog.as_mut().unwrap().fields.insert("smoothness".into(), json!(30)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.tool_options_of("smooth")["smoothness"], json!(30.0)); + app.run("tool.options", json!({"tool": "smooth"})).unwrap(); + assert!(painted(&mut app).contains("30%")); + for tool in ["pencil", "paintbrush", "blobBrush", "eraser"] { + app.run("tool.options", json!({"tool": tool})).unwrap(); + let text = painted(&mut app); + assert!(!text.contains("Smoothness:"), "{tool}: {text}"); + } +} + #[test] fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() { for roundness in [-5.0, 0.0, 0.05, 0.1, 1.0, 50.0, 100.0, 120.0] { @@ -186,8 +214,8 @@ fn each_tool_shows_its_options_and_ok_sets_them() { let pb_text = painted(&mut app); assert!(pb_text.contains("Paintbrush Tool Options")); assert!(!pb_text.contains("Alt key toggles to Smooth Tool") && !pb_text.contains("Live preview"), "{pb_text}"); - // Smooth has Fidelity only, the Eraser Size only, and the Blob Brush Fidelity, Size, Keep selected and Merge only - // with selection. + // Smooth has Fidelity and Smoothness only, the Eraser Size only, and the Blob Brush Fidelity, Size, Keep selected + // and Merge only with selection. app.run("tool.options", json!({"tool": "smooth"})).unwrap(); let text = painted(&mut app); assert!(text.contains("Smooth Tool Options") && text.contains("Fidelity:"), "{text}"); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..590b910eed 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1277,6 +1277,7 @@ font-technology Variable Променливи Feet & Inches Футове и инчове Fewer Elements По-малко елемента Fidelity: Точност: + Smoothness: Гладкост: Figure Space Цифрово разстояние Figure: Фигура: # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..3237c96ab3 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2812,6 +2812,7 @@ digits Malayalam Malajalam Close paths when ends are within: Zatvori putanje kad su krajevi unutar: Edit selected paths within: Uređuj odabrane putanje unutar: Fidelity: Vjernost: + Smoothness: Glatkoća: Fill new strokes Ispunjavaj nove poteze Alt key toggles to Smooth Tool Tipka Alt prebacuje na alat za zaglađivanje Live curve fitting Uklapanje krivulje uživo diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..f3edca1732 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1812,6 +1812,7 @@ digits Malayalam Malaiàlam Feet & Inches Peus i polzades Fewer Elements Menys elements Fidelity: Fidelitat: + Smoothness: Suavitat: Figure Space Espai de xifra Figure: Xifra: File Fitxer diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..1c02cde75a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2895,6 +2895,7 @@ digits Malayalam Malajálamské Close paths when ends are within: Uzavřít cesty, když jsou konce do: Edit selected paths within: Upravovat vybrané cesty do: Fidelity: Věrnost: + Smoothness: Vyhlazení: Fill new strokes Vyplňovat nové tahy Alt key toggles to Smooth Tool Klávesa Alt přepíná na nástroj Vyhlazení Live curve fitting Průběžné prokládání křivky diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..7861b3e577 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5435,6 +5435,7 @@ digits Malayalam Malayalam Close paths when ends are within: Luk stier, når enderne er inden for: Edit selected paths within: Redigér markerede stier inden for: Fidelity: Præcision: + Smoothness: Glatthed: Fill new strokes Udfyld nye konturer Alt key toggles to Smooth Tool Alt-tasten skifter til Udglatningsværktøj Live curve fitting Kurvetilpasning undervejs diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..6f3ae5de12 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1308,6 +1308,7 @@ font-technology Variable Variabel Feet & Inches Fuß und Zoll Fewer Elements Weniger -Elemente Fidelity: Genauigkeit: + Smoothness: Glättung: Figure Space Ziffernleerzeichen Figure: Ziffern: # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..1cad48c558 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1264,6 +1264,7 @@ font-technology Variable Μεταβλητές Feet & Inches Πόδια και ίντσες Fewer Elements Λιγότερα στοιχεία Fidelity: Πιστότητα: + Smoothness: Ομαλότητα: Figure Space Κενό ψηφίου Figure: Σχήμα: # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..63b874c609 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1332,6 +1332,7 @@ font-technology Variable Variables Feet & Inches Pies y pulgadas Fewer Elements Menos elementos Fidelity: Fidelidad: + Smoothness: Suavizado: Figure Space Espacio de cifra Figure: Cifras: # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..6614f9be2a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2848,6 +2848,7 @@ digits Malayalam Malajalam Close paths when ends are within: Sulje polut, kun päät ovat etäisyydellä: Edit selected paths within: Muokkaa valittuja polkuja etäisyydellä: Fidelity: Tarkkuus: + Smoothness: Pehmeys: Fill new strokes Täytä uudet viivat Alt key toggles to Smooth Tool Alt-näppäin vaihtaa Tasoitustyökaluun Live curve fitting Käyrän sovitus piirrettäessä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..6f41631ba9 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1323,6 +1323,7 @@ font-technology Variable Variables Feet & Inches Pieds et pouces Fewer Elements Moins d’éléments Fidelity: Fidélité : + Smoothness: Lissage : Figure Space Espace numérique Figure: Chiffres : # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..03255f498e 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1449,6 +1449,7 @@ Feet & Inches ફૂટ અને ઇંચ Fewer Elements ઓછા ઘટકો Fidelity: ફિડેલિટી: + Smoothness: સરળતા: Figure Space ફિગર સ્પેસ Figure: ફિગર: File ફાઇલ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..9af4268d8f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2257,6 +2257,7 @@ arrowhead Feather पंख Feet & Inches पैर & इंच Fewer Elements कम एलिमेंट Fidelity: सटीकता: + Smoothness: चिकनापन: Figure Space अंक-स्पेस Figure: आकृति: File फ़ाइल diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..6da205198a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1662,6 +1662,7 @@ digits Malayalam Malajálam Feet & Inches Láb és hüvelyk Fewer Elements Kevesebb elem Fidelity: Pontosság: + Smoothness: Simaság: Figure Space Számjegyszóköz Figure: Számjegyek: # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..dff50ede9a 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3307,6 +3307,7 @@ digits Malayalam Malayalam Close paths when ends are within: Tutup jalur bila ujungnya berada dalam jarak: Edit selected paths within: Edit jalur terpilih dalam jarak: Fidelity: Fidelitas: + Smoothness: Kehalusan: Fill new strokes Isi stroke baru Alt key toggles to Smooth Tool Tombol Alt beralih ke Alat penghalus Live curve fitting Penyesuaian kurva langsung diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..66d0c4f33a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1345,6 +1345,7 @@ font-technology Variable Variabili Feet & Inches Piedi e pollici Fewer Elements Meno elementi Fidelity: Fedeltà: + Smoothness: Uniformità: Figure Space Spazio cifra Figure: Cifre: # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..66ba8f9635 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1974,6 +1974,7 @@ antiAlias Sharp シャープ Feet & Inches フィート・インチ Fewer Elements 要素を減らす Fidelity: 精度: + Smoothness: 滑らかさ: Figure: 数字: File Format: ファイル形式: File Formats ファイル形式 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..a546fd60e0 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4797,6 +4797,7 @@ digits Malayalam მალაიალამური Close paths when ends are within: ტრაექტორიების შეკვრა, როცა ბოლოები ახლოსაა: Edit selected paths within: მონიშნული ტრაექტორიების რედაქტირება მანძილზე: Fidelity: სიზუსტე: + Smoothness: სიგლუვე: Fill new strokes ახალი შემოხაზვების შევსება The document has no colour swatches. დოკუმენტს ფერის ნიმუშები არ აქვს. Style Name: სტილის სახელი: diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..a8b3b680de 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1964,6 +1964,7 @@ antiAlias Sharp 날카롭게 Feet & Inches 피트 및 인치 Fewer Elements 요소 줄이기 Fidelity: 정확도: + Smoothness: 부드러움: Figure: 그림: File Format: 파일 형식: File Formats 파일 형식 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..669c35c98b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3301,6 +3301,7 @@ digits Malayalam Malayalam Close paths when ends are within: Paden sluiten wanneer de einden binnen: Edit selected paths within: Geselecteerde paden bewerken binnen: Fidelity: Nauwkeurigheid: + Smoothness: Gladheid: Fill new strokes Nieuwe lijnen vullen Alt key toggles to Smooth Tool Alt-toets schakelt over naar Gladmaken-gereedschap Live curve fitting Curve aanpassen tijdens het tekenen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..a616f31a16 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2810,6 +2810,7 @@ digits Malayalam Malajalam Close paths when ends are within: Zamykaj ścieżki, gdy końce są w odległości: Edit selected paths within: Edytuj zaznaczone ścieżki w odległości: Fidelity: Wierność: + Smoothness: Gładkość: Fill new strokes Wypełniaj nowe pociągnięcia Alt key toggles to Smooth Tool Klawisz Alt przełącza na narzędzie Wygładzanie Live curve fitting Dopasowywanie krzywej podczas rysowania diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..ddb851f00a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1218,6 +1218,7 @@ antiAlias Sharp Nítido Feet & Inches Pés e Polegadas Fewer Elements Menos Elementos Fidelity: Fidelidade: + Smoothness: Suavização: Figure Space Espaço de Figura Figure: Figura: # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..d7ba8fcf3e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1330,6 +1330,7 @@ font-technology Variable Вариативные Feet & Inches Футы и дюймы Fewer Elements Меньше элементов Fidelity: Точность: + Smoothness: Сглаживание: Figure Space Цифровая шпация Figure: Цифры: # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..687aa460d1 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1298,6 +1298,7 @@ font-technology Variable Variabla Feet & Inches Fot och tum Fewer Elements Färre -element Fidelity: Återgivning: + Smoothness: Mjukhet: Figure Space Siffermellanrum Figure: Figur: # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..9b68fb4e67 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1298,6 +1298,7 @@ font-technology Variable Değişken Feet & Inches Fit ve İnç Fewer Elements Daha az Öğesi Fidelity: Sadakat: + Smoothness: Pürüzsüzlük: Figure Space Şekil Alanı Figure: Şekil: File Dosya diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..d53959ff29 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1339,6 +1339,7 @@ font-technology Variable Варіативні Feet & Inches Фути та дюйми Fewer Elements Менше елементів Fidelity: Точність: + Smoothness: Згладжування: Figure Space Цифрова шпація Figure: Цифри: # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..99f4b23892 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1547,6 +1547,7 @@ digits Malayalam Malayalam Feet & Inches Feet và Inch Fewer Elements Ít phần tử hơn Fidelity: Độ trung thực: + Smoothness: Độ mịn: Figure Space Khoảng trắng chữ số Figure: Chữ số: # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..bc926ada9d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1274,6 +1274,7 @@ antiAlias Sharp 锐利 Feet & Inches 英尺和英寸 Fewer Elements 更少的 元素 Fidelity: 精确度: + Smoothness: 平滑度: Figure Space 数字空格 Figure: 数字: # Artwork drag between document tabs. diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..3145f6c923 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1309,6 +1309,7 @@ font-technology Variable 可變 Feet & Inches 英呎與英吋 Fewer Elements 減少 元素 Fidelity: 精確度: + Smoothness: 平滑度: Figure Space 數字空格 Figure: 數字: # Artwork drag between document tabs. diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..bfaf43e458 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7042,7 +7042,7 @@ in `path.convertAnchor`; `t` in `path.insertAnchor`; `fidelity` and the `within` `brush.freehand`, which runs it); `size`, `sizeVariation`, `angle`, `angleVariation`, `roundness` and `roundnessVariation` in `path.eraseRegion`; `size`, `sizeVariation`, `angle`, `roundness` and `fidelity` in `path.blob`; `width` in `path.eraseSegments`; -`radius` and `fidelity` in `path.smoothRegion`; `tolerance` in `path.joinScrub`; `dx` and `dy` in `path.moveAnchors`; +`radius`, `fidelity` and `smoothness` in `path.smoothRegion`; `tolerance` in `path.joinScrub`; `dx` and `dy` in `path.moveAnchors`; and `dx`, `dy`, `tol` and `radius` in `path.reshape`. A null is read as a key left out. `path.convertAnchor` refuses an `x` without a `y`, or a `y` without an `x`, with "x and y must be given together". `path.freehand`, `path.curvature`, `path.knife`, `path.eraseRegion`, `path.eraseSegments`, `path.smoothRegion`, `path.joinScrub` and @@ -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`'s `smoothness` (0 to 100, 50 when left out) sets how strongly the path is smoothed before it is +refitted within `fidelity`: each point is averaged with the stretch of path around it, over a stretch that grows in +proportion to `smoothness`, so a higher value leaves a smoother path. At 0 the path is only refitted within +`fidelity`, and 100 averages over twice the stretch that 50 does. A `smoothness` outside 0 to 100 is refused with +"`smoothness` must be from 0 to 100" and changes nothing. The default and the way the percentage scales the smoothing +are VectorCraft's own. The Smooth tool sends its Smooth Tool Options' Smoothness (`tool.setOption {tool: "smooth", +key: "smoothness"}`, 0 to 100, 50 by default) with each drag. + 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 @@ -13481,8 +13489,9 @@ The second call returns the error ``tool `smooth`: `fidelity` must be a number f The Pencil's, the Paintbrush's and the Smooth tool's `fidelity` is in screen pixels: the tools send `path.freehand` and `path.smoothRegion` the option divided by the zoom, so a stroke keeps as many points and a Smooth drag smooths as much -at any zoom. The Smooth tool's `fidelity` (0.05 to 100 px, 2.5 by default) is also the one an Alt smoothing drag with -the Pencil, Paintbrush or Blob Brush uses. The Blob Brush's `fidelity` is in points. +at any zoom. The Smooth tool's `fidelity` (0.05 to 100 px, 2.5 by default) and `smoothness` (0 to 100, 50 by default) +are also the ones an Alt smoothing drag with the Pencil, Paintbrush or Blob Brush uses. The Blob Brush's `fidelity` is +in points. `tool.options {tool}` opens what double-clicking the tool's button opens (its params doc lists every tool), in the desktop app. The Flare tool's are its Flare Tool Options (dialog `flareOptions`): `diameter` and `pathLength` (pt), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..b472e82686 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1432,6 +1432,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Curvature point markers are circular, with no direction handles. While drawing, its own point feedback replaces generic selection markers; existing paths use the selection overlay, including partial selections and Hide Edges. Anchor Size applies, and Direct Selection and Pen retain their handles. The real egui-frame regressions in `crates/ui-egui/src/canvas.rs` verify marker positions, counts and unchanged documents (#1236, in part); the existing-path interpolation request remains open. The curve through the points (`curvature_spline` in `crates/tools/src/draw2.rs`) makes each stretch of three points follow the circle through them: a smooth point's handles lie along that circle's tangent, each `chord / (3 cos²(α/2))` long (α between handle and chord, capped at 90°), and the ends of an open path mirror their neighbour's tangent in their chord, so a J or a U curves evenly, a turn tighter than 30° comes to a point, and uneven spacing doesn't loop; the rubber band, a dragged or inserted point and `path.convertAnchor` to smooth use the same rule, while the Pencil's fitting keeps its own; `tests/draw2.rs` checks that the rubber band is the path the click makes (#1236, in part). The Smooth tool smooths only the stretch of path under the drag (#1547, fixes #1512). A path the Smooth tool changes stays selected whole, and the anchor points and segments selected on it with Direct Selection are deselected. Selected paths the drag does not change keep their selected anchors, and undo restores the earlier selection (`tests/draw2.rs`, `smoothing_a_path_drops_its_direct_selected_anchors`). While the Smooth tool drags with a path selected that it can smooth, a dashed outline shows the band it smooths: everything within its radius of the drag (12 screen pixels, VectorCraft's own value), round at both ends; Alt smoothing with the Pencil, Paintbrush and Blob Brush shows the same band. While Alt is held during a Paintbrush stroke or before a press with no path selected that the Smooth tool can act on, the Paintbrush shows a closing cursor (a crosshair with a ring), and so does the Pencil with Alt key toggles to Smooth Tool off when Alt is pressed after the drag starts; releasing the mouse button with Alt still held closes the path. Before a Paintbrush press with such a path selected, Alt shows the Smooth cursor, and holding Alt at the press smooths that path with the Smooth tool's radius and Smooth Tool Options' Fidelity. A Pencil drag started with Shift or Alt held draws a straight line instead, which stays open. Smooth Tool Options' Fidelity is in pixels, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=79) gives it: the Smooth tool, and an Alt smoothing drag with the Pencil, Paintbrush or Blob Brush, refits the path at Fidelity divided by the zoom, so a drag smooths a path as much on screen at 25 % as at 800 %. Reading the pixels as screen pixels is VectorCraft's own rule, as for the Pencil and the Paintbrush (#5729); the range (0.05 to 100 px) and the default (2.5 px) are VectorCraft's own values, and a saved Fidelity keeps its number (`crates/tools/src/draw2/gesture/tests.rs` test `smooth_fidelity_is_in_screen_pixels_at_any_zoom`, `crates/engine/src/tests/draw2.rs` test `smooth_region_refits_at_the_tolerance_sent_at_any_zoom`). + Smooth Tool Options has Smoothness under Fidelity, from 0% to 100%, where a higher value gives a smoother path, as [the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=164) describes the setting: the Smooth tool, and an Alt smoothing drag with the Pencil, Paintbrush or Blob Brush, sends it as `path.smoothRegion`'s `smoothness`, and a Smoothness outside 0 to 100 is an error in `tool.setOption` and `path.smoothRegion`. The default (50%) and the way the percentage scales the smoothing (none before the refit at 0%, twice the default's stretch at 100%) are VectorCraft's own (`crates/engine/src/tests/draw2.rs` test `a_higher_smoothness_leaves_a_smoother_path`, `crates/engine/src/tests/toolsettings.rs` test `the_smooth_tools_smoothness_is_kept_and_alt_smoothing_takes_it`). With Shift held at the press, the Pencil draws a straight line from the press point to the pointer at 45° steps from the Constrain Angle, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes; pressed on an end of a selected open path, the line continues the path from that end (part of #3799). With Option/Alt held at the press and Alt key toggles to Smooth Tool off, the Pencil draws a straight line at any angle, and it stays open when Alt is still held at the release; Shift and Alt together keep the 45° steps (#3799). While Shift or Alt is held before the press, the Pencil shows a straight-line cursor (a crosshair with a short level line), as the page describes. Over an end of a selected open path, where the stroke continues the path, freehand or as a straight line, it shows a path-continuation cursor (a crosshair with a short line rising to the right), as [Extend paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/extend-paths-with-the-pencil-tool.html) describes, and again while a continuing stroke ends near an open end of another selected path, where the release connects the two ([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)). A continuing stroke, a straight line too, that ends within Close Paths When Ends Are Within of the path's other end shows the closing cursor, and the release closes the path; Alt held at the release closes a continuing freehand stroke too (a straight line stays open, as above). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. A shape just drawn stays adjustable with its tool: its Live Shape widgets drag, a press on its centre point (Show Center) moves the selection with the Selection tool's move arrow, snapping and Alt copy, and a press in the rotate zone just outside a bounding-box corner turns it about the centre with the Selection tool's rotate cursor (#5477; tests `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner` and, through the engine, `shapetools.rs`). A drag on one of its eight bounding-box handles scales it as the Selection tool's handles do, with their cursors and snapping, instead of drawing a new shape from the handle. A shape tool takes a press as a handle's only on the drawn handle square (VectorCraft's own rule: 3 screen points from its centre along each axis at the default Anchor Size, a half point more or less per step; the Selection tool takes 5), so a press just beside a handle still draws (tests `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_shape_tool_draws_from_a_press_just_beside_a_handle` and `a_shape_tool_scales_the_shape_just_drawn_by_its_bounding_box_handle`). With such a tool, a double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel, and the tool, the selection and the document stay as they were (test `a_double_click_on_a_corner_widget_shows_the_transform_panel`). The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays by 0.1 radian at each drag update in which the pointer's document y grows, and back by as much at each one in which it falls, Shift held keeps their turn, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). From 34a0070618ff759a92263e215befd6be1a8759fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:17:24 -0800 Subject: [PATCH 013/101] Path Precision Tools: the Tangent Circle Tool's options set its preview and how near it snaps The Tangent Circle Tool's options dialog and tool.setOption take five more options, kept with the preferences: center and radii show or hide the preview's center cross and the lines to the two touch points, color sets the color of the circle, the cross, the lines and the no-circle note (red, blue, magenta, green, black or gray), snapTolerance sets how near (screen pixels, 0 to 25) the pointer picks a segment, and snapWithoutGuides keeps that reach with Smart Guides off. With Smart Guides on, their Snapping Tolerance counts when it is larger; with snapping off a segment is picked within the Selection Tolerance. The help page lists these options: https://docs.astutegraphics.com/subscribe/tangent-circle-tool The defaults (both shown, red, 3 px, snapping on) are VectorCraft's own. With Smart Guides on, the default reach is now their Snapping Tolerance (4 px) instead of the 3 px Selection Tolerance. Of the segments within reach the tool now picks the nearest one, not the first one found, so a larger tolerance does not pick a farther path over a nearer one. tool.setOption gives an error for an unknown color, a tolerance outside its range or a value of the wrong type, and sets none of the values. Docs: docs/mcp.md, docs/target-app-parity.md, docs/ui-parity.md. --- crates/tools/src/addons/tangent_circle.rs | 262 +++++++++++++++++-- crates/tools/src/settings.rs | 2 +- crates/ui-egui/src/addons/pathtools.rs | 47 +++- crates/ui-egui/src/addons/pathtools/tests.rs | 72 +++++ crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/gu.tsv | 5 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + docs/mcp.md | 15 +- docs/target-app-parity.md | 2 + docs/ui-parity.md | 2 +- 35 files changed, 490 insertions(+), 25 deletions(-) diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index b40cffd8e7..9ae74c0936 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -16,6 +16,16 @@ //! document, or a change to the first segment that leaves no undo step (a live preview, or one that //! was canceled) forgets the first segment. The circles are looked for again whenever either //! segment's shape differs from the one they were found on. +//! +//! The tool's options (its options dialog, `tool.setOption`; kept with the preferences): `radius`; +//! `center` and `radii` show or hide the circle's center cross and the lines from its center to the +//! two points it touches; `color` is the color of the circle, the cross, those lines and the note +//! (one of [`COLORS`]); `snapTolerance` is how near (screen pixels) the pointer picks a segment +//! with Smart Guides on, where Smart Guides' Snapping Tolerance counts instead when it is larger, +//! or with Smart Guides off while `snapWithoutGuides` is on. Without snapping a segment is picked +//! within the selection tolerance, as a click on a path picks it, and that is also the least reach +//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default the +//! cross and the lines show, the color is red, the tolerance is 3 px and `snapWithoutGuides` is on. use kurbo::{CubicBez, Shape}; use serde_json::{Value, json}; @@ -42,6 +52,22 @@ pub const NO_CIRCLE: &str = "No tangent circle here"; const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff]; const RED: [u8; 3] = [0xe0, 0x3c, 0x3c]; const GREY: [u8; 3] = [0x80, 0x80, 0x80]; +/// The colors the `color` option takes, by option value, with the color the circle, its center +/// cross, its radii and the note are drawn in. Red is the first. +pub const COLORS: &[(&str, [u8; 3])] = &[ + ("red", RED), + ("blue", crate::draw2::FEEDBACK), + ("magenta", [0xd6, 0x2c, 0xd6]), + ("green", [0x1f, 0xb4, 0x4b]), + ("black", [0x00, 0x00, 0x00]), + ("gray", GREY), +]; +/// The snapping tolerance the tool starts with (screen pixels). +pub const SNAP_PX: f64 = 3.0; +/// The snapping tolerance the `snapTolerance` option takes (screen pixels). +pub const SNAP_RANGE: (f64, f64) = (0.0, 25.0); +/// The option keys that are true or false. +const SWITCHES: &[&str] = &["center", "radii", "snapWithoutGuides"]; /// A segment under the pointer: where on it, and the segment itself. #[derive(Clone, Debug, PartialEq)] @@ -72,6 +98,14 @@ struct Press { pub struct TangentCircleTool { radius: f64, + /// Whether the preview shows the center cross and the radii. + center: bool, + radii: bool, + /// An entry of [`COLORS`]. + color: usize, + /// The snapping tolerance (screen pixels), and whether the tool snaps with Smart Guides off. + snap_px: f64, + snap_without_guides: bool, first: Option, hover: Option, press: Option, @@ -91,13 +125,45 @@ type CacheKey = (NodeId, usize, usize, Option, CubicBez, Vec); impl Default for TangentCircleTool { fn default() -> Self { - Self { radius: RADIUS, first: None, hover: None, press: None, picking: false, found: None, looked: false, pointer: Point::ZERO, cache: None } + Self { + radius: RADIUS, + center: true, + radii: true, + color: 0, + snap_px: SNAP_PX, + snap_without_guides: true, + first: None, + hover: None, + press: None, + picking: false, + found: None, + looked: false, + pointer: Point::ZERO, + cache: None, + } } } -/// The path segment under `p`, of any editable path. -fn pick_at(cx: &ToolContext, p: Point) -> Option { - let (id, subpath, segment, t) = crate::draw2::hit_segment(cx, p, cx.pick_tol())?; +/// The nearest path segment within `reach` of `p`, of any editable path; of segments at the same +/// distance, one of a selected path, then the one on top. +fn pick_at(cx: &ToolContext, p: Point, reach: f64) -> Option { + let mut best: Option<((NodeId, usize, usize, f64), f64)> = None; + for id in crate::draw2::candidate_paths(cx) { + let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue }; + // A path whose control points' box, with its edges, lies out of reach holds no point within + // reach. + let near = |b: vectorcraft_geom::Rect| p.x >= b.x0 - reach && p.x <= b.x1 + reach && p.y >= b.y0 - reach && p.y <= b.y1 + reach; + if pd.control_bounds().is_none_or(|b| !near(b)) { + continue; + } + if let Some((subpath, segment, t, _, d)) = pd.nearest(p) + && d <= reach + && best.is_none_or(|(_, b)| d < b) + { + best = Some(((id, subpath, segment, t), d)); + } + } + let ((id, subpath, segment, t), _) = best?; let sp = cx.doc.node(id)?.path_data()?.subpaths.get(subpath)?; if segment >= sp.segment_count() { return None; @@ -197,6 +263,26 @@ fn segment_path(c: &CubicBez) -> BezPath { } impl TangentCircleTool { + /// How near (document units) the pointer picks a segment: with Smart Guides on, the snapping + /// tolerance or Smart Guides' Snapping Tolerance, whichever is larger; with them off, the + /// snapping tolerance while `snapWithoutGuides` is on, and otherwise none. Never less than the + /// selection tolerance. + fn reach(&self, cx: &ToolContext) -> f64 { + let pick = cx.pick_tol(); + if cx.smart_guides { + pick.max(cx.tol(self.snap_px)).max(cx.snap_tol()) + } else if self.snap_without_guides { + pick.max(cx.tol(self.snap_px)) + } else { + pick + } + } + + /// The color the preview is drawn in. + fn preview_color(&self) -> [u8; 3] { + COLORS.get(self.color).map_or(RED, |(_, rgb)| *rgb) + } + /// The radius a drag gives, with Shift in round steps. fn shown_radius(cx: &ToolContext, r: f64, shift: bool) -> f64 { if !shift { @@ -304,12 +390,12 @@ impl Tool for TangentCircleTool { self.pointer = ev.pos; match ev.kind { PointerKind::Move => { - self.hover = pick_at(cx, ev.pos); + self.hover = pick_at(cx, ev.pos, self.reach(cx)); self.look(cx, ev.pos, ev.mods); vec![] } PointerKind::Down => { - let Some(pick) = pick_at(cx, ev.pos) else { return vec![] }; + let Some(pick) = pick_at(cx, ev.pos, self.reach(cx)) else { return vec![] }; self.forget_if_changed(cx); let Some(first) = self.first.clone() else { self.first = Some(pick); @@ -415,21 +501,26 @@ impl Tool for TangentCircleTool { { out.push(Overlay::Line { a: press.at, b: self.pointer, color: GREY, dashed: false }); } + let color = self.preview_color(); if let Some(c) = &self.found { let (at, r) = (c.circle.center, c.circle.radius); // A tolerance of at least a ten-thousandth of the radius keeps a huge circle to a few // dozen segments. let tol = cx.tol(0.1).max(r * 1e-4); - out.push(Overlay::Path { path: kurbo::Circle::new(at, r).to_path(tol), color: RED, width: 1.0, dashed: false }); - let arm = cx.tol(4.0); - out.push(Overlay::Line { a: at - kurbo::Vec2::new(arm, 0.0), b: at + kurbo::Vec2::new(arm, 0.0), color: RED, dashed: false }); - out.push(Overlay::Line { a: at - kurbo::Vec2::new(0.0, arm), b: at + kurbo::Vec2::new(0.0, arm), color: RED, dashed: false }); - out.push(Overlay::Line { a: at, b: c.first, color: RED, dashed: true }); - out.push(Overlay::Line { a: at, b: c.second, color: RED, dashed: true }); + out.push(Overlay::Path { path: kurbo::Circle::new(at, r).to_path(tol), color, width: 1.0, dashed: false }); + if self.center { + let arm = cx.tol(4.0); + out.push(Overlay::Line { a: at - kurbo::Vec2::new(arm, 0.0), b: at + kurbo::Vec2::new(arm, 0.0), color, dashed: false }); + out.push(Overlay::Line { a: at - kurbo::Vec2::new(0.0, arm), b: at + kurbo::Vec2::new(0.0, arm), color, dashed: false }); + } + if self.radii { + out.push(Overlay::Line { a: at, b: c.first, color, dashed: true }); + out.push(Overlay::Line { a: at, b: c.second, color, dashed: true }); + } out.push(Overlay::Measure { p: self.pointer, text: format!("R: {}", cx.len(r)) }); } else if self.looked { // A label, which the canvas shows in the interface language. - out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color: RED }); + out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color }); } out } @@ -439,14 +530,29 @@ impl Tool for TangentCircleTool { } fn options(&self) -> Value { - json!({ "radius": self.radius }) + json!({ + "radius": self.radius, + "center": self.center, + "radii": self.radii, + "color": COLORS.get(self.color).map_or("red", |(name, _)| *name), + "snapTolerance": self.snap_px, + "snapWithoutGuides": self.snap_without_guides, + }) } + /// Sets one option; a value the option does not take leaves it as it was. fn set_option(&mut self, key: &str, v: &Value) { - if key == "radius" - && let Some(r) = v.as_f64().filter(|r| (RADIUS_RANGE.0..=RADIUS_RANGE.1).contains(r)) - { - self.radius = r; + if self.check_option(key, v).is_err() { + return; + } + match key { + "radius" => self.radius = v.as_f64().unwrap_or(self.radius), + "center" => self.center = v.as_bool().unwrap_or(self.center), + "radii" => self.radii = v.as_bool().unwrap_or(self.radii), + "color" => self.color = v.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)).unwrap_or(self.color), + "snapTolerance" => self.snap_px = v.as_f64().unwrap_or(self.snap_px), + "snapWithoutGuides" => self.snap_without_guides = v.as_bool().unwrap_or(self.snap_without_guides), + _ => {} } } @@ -454,6 +560,9 @@ impl Tool for TangentCircleTool { use crate::option_check as c; match key { "radius" => c::number(key, v, RADIUS_RANGE.0, RADIUS_RANGE.1), + "snapTolerance" => c::number(key, v, SNAP_RANGE.0, SNAP_RANGE.1), + "color" => c::one_of(key, v, &COLORS.iter().map(|(name, _)| *name).collect::>()), + k if SWITCHES.contains(&k) => c::boolean(key, v), _ => Err(c::unknown(key)), } } @@ -598,6 +707,123 @@ mod tests { assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); } + #[test] + fn the_preview_options_set_its_cross_radii_and_color() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let green = COLORS.iter().find(|(name, _)| *name == "green").map(|(_, rgb)| *rgb); + let lines = + |ov: &[Overlay], dashed_lines: bool| ov.iter().filter(|o| matches!(o, Overlay::Line { dashed, .. } if *dashed == dashed_lines)).count(); + let mut t = TangentCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Move, 200.0, 139.0)); + // By default: the red circle, its center cross (two lines) and its two radii. + let ov = t.overlays(&cx); + assert_eq!((lines(&ov, false), lines(&ov, true)), (2, 2), "{ov:?}"); + assert!(ov.iter().any(|o| matches!(o, Overlay::Path { color, width, .. } if *color == RED && *width == 1.0)), "{ov:?}"); + t.set_option("center", &json!(false)); + let ov = t.overlays(&cx); + assert_eq!((lines(&ov, false), lines(&ov, true)), (0, 2), "no cross: {ov:?}"); + t.set_option("radii", &json!(false)); + t.set_option("color", &json!("green")); + let ov = t.overlays(&cx); + assert_eq!((lines(&ov, false), lines(&ov, true)), (0, 0), "no radii: {ov:?}"); + assert!(ov.iter().any(|o| matches!(o, Overlay::Path { color, .. } if Some(*color) == green)), "{ov:?}"); + assert!(ov.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 20.00"))), "the radius still shows: {ov:?}"); + // The note takes the color too. + t.set_option("radius", &json!(5)); + t.pointer(&cx, &shifted(PointerKind::Move, 200.0, 140.0)); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Label { text, color, .. } if text == NO_CIRCLE && Some(*color) == green))); + } + + #[test] + fn the_preview_and_snap_options_take_only_their_values() { + let mut t = TangentCircleTool::default(); + let o = t.options(); + assert_eq!( + (&o["center"], &o["radii"], &o["color"], &o["snapTolerance"], &o["snapWithoutGuides"]), + (&json!(true), &json!(true), &json!("red"), &json!(3.0), &json!(true)) + ); + for (key, good) in [ + ("center", json!(false)), + ("radii", json!(false)), + ("snapWithoutGuides", json!(false)), + ("color", json!("gray")), + ("snapTolerance", json!(0)), + ("snapTolerance", json!(25)), + ("snapTolerance", json!(7.5)), + ] { + assert_eq!(t.check_option(key, &good), Ok(()), "{key} {good}"); + t.set_option(key, &good); + let now = t.options()[key].clone(); + assert!(now == good || (good.is_number() && now.as_f64() == good.as_f64()), "{key}: {now} for {good}"); + } + let colors = "`color` must be one of `red`, `blue`, `magenta`, `green`, `black`, `gray`"; + for (key, bad, error) in [ + ("center", json!(1), "`center` must be true or false"), + ("radii", json!("no"), "`radii` must be true or false"), + ("snapWithoutGuides", Value::Null, "`snapWithoutGuides` must be true or false"), + ("color", json!("orange"), colors), + ("color", json!("Red"), colors), + ("color", json!(0), colors), + ("snapTolerance", json!(-1), "`snapTolerance` must be a number from 0 to 25"), + ("snapTolerance", json!(26), "`snapTolerance` must be a number from 0 to 25"), + ("snapTolerance", json!("3"), "`snapTolerance` must be a number from 0 to 25"), + ] { + assert_eq!(t.check_option(key, &bad), Err(error.into()), "{key} {bad}"); + let before = t.options(); + t.set_option(key, &bad); + assert_eq!(t.options(), before, "{key} {bad}"); + } + } + + #[test] + fn the_snap_options_set_how_near_a_segment_is_picked() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + // At 100%, Selection Tolerance 3 px; the first line is at y = 100. + let picks = |t: &mut TangentCircleTool, cx: &ToolContext, y: f64| { + t.forget(); + t.pointer(cx, &ev(PointerKind::Down, 150.0, y)); + t.pointer(cx, &ev(PointerKind::Up, 150.0, y)); + t.first.is_some() + }; + let guides = |tolerance: f64| ToolContext { smart_guides: true, snapping_tolerance: tolerance, ..cx(&d, &sel, &p) }; + let no_guides = ToolContext { smart_guides: false, ..cx(&d, &sel, &p) }; + let mut t = TangentCircleTool::default(); + // Smart Guides on: their Snapping Tolerance when it is larger than the tool's. + assert!(picks(&mut t, &guides(10.0), 109.0)); + assert!(!picks(&mut t, &guides(10.0), 111.0)); + t.set_option("snapTolerance", &json!(12)); + assert!(picks(&mut t, &guides(4.0), 111.0), "the tool's when it is larger"); + assert!(!picks(&mut t, &guides(4.0), 113.0)); + // Smart Guides off: the tool's tolerance while it snaps without them. + t.set_option("snapTolerance", &json!(8)); + assert!(picks(&mut t, &no_guides, 107.0)); + assert!(!picks(&mut t, &no_guides, 109.0)); + // Without snapping, only the Selection Tolerance; a tolerance below it does not shrink it. + t.set_option("snapWithoutGuides", &json!(false)); + assert!(!picks(&mut t, &no_guides, 105.0)); + assert!(picks(&mut t, &no_guides, 102.5)); + t.set_option("snapWithoutGuides", &json!(true)); + t.set_option("snapTolerance", &json!(0)); + assert!(picks(&mut t, &no_guides, 102.5)); + // Over the gap between the two lines, the nearer one is picked, though both are in reach. + t.set_option("snapTolerance", &json!(25)); + t.forget(); + t.pointer(&no_guides, &ev(PointerKind::Move, 150.0, 122.0)); + assert!(t.hover.as_ref().is_some_and(|h| (h.p.y - 140.0).abs() < 1e-9), "{:?}", t.hover); + t.pointer(&no_guides, &ev(PointerKind::Move, 150.0, 118.0)); + assert!(t.hover.as_ref().is_some_and(|h| (h.p.y - 100.0).abs() < 1e-9), "{:?}", t.hover); + // A segment exactly at the reach is in reach, on either side of it. + t.pointer(&no_guides, &ev(PointerKind::Move, 150.0, 75.0)); + assert!(t.hover.as_ref().is_some_and(|h| (h.p.y - 100.0).abs() < 1e-9), "{:?}", t.hover); + t.pointer(&no_guides, &ev(PointerKind::Move, 150.0, 165.0)); + assert!(t.hover.as_ref().is_some_and(|h| (h.p.y - 140.0).abs() < 1e-9), "{:?}", t.hover); + } + #[test] fn a_drag_sets_the_radius_with_shift_steps_and_a_slow_drag() { let d = doc(); diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 1d9d8c4a54..e1ffc243c3 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -108,7 +108,7 @@ const ROWS: &[Row] = &[ (&[crate::addons::extend_path::ID], None, &["mode"]), (&[crate::addons::corner_tool::ID], None, &["radius", "kind"]), (&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]), - (&[crate::addons::tangent_circle::ID], None, &["radius"]), + (&[crate::addons::tangent_circle::ID], None, &["radius", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]), (&[crate::addons::smart_pen::ID], None, &["next"]), // The kind first: a new kind resets the values after it. (&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]), diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 3e7b864c05..5921bee7fc 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -238,13 +238,35 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { return false; } if d.str("__tool") == tangent_circle_tool::ID { + let label_w = tangent_circle_label_w(ui); let (lo, hi) = tangent_circle_tool::RADIUS_RANGE; let r = d.f64("radius", tangent_circle_tool::RADIUS); - widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { + widgets::label_row(ui, tl!("Radius:"), label_w, |ui| { if let Some(x) = widgets::range_field(ui, "tangent-circle-radius", r, lo..=hi, " pt", 2, 96.0) { d.fields.insert("radius".into(), json!(x)); } }); + for (key, label) in [("center", tl!("Circle Center")), ("radii", tl!("Circle Radii Lines"))] { + tangent_circle_check(ui, d, key, label); + } + let color = d.str("color"); + let at = tangent_circle_tool::COLORS.iter().position(|(name, _)| *name == color).unwrap_or(0); + widgets::label_row(ui, tl!("Color:"), label_w, |ui| { + let shown = TANGENT_CIRCLE_COLORS.get(at).copied().unwrap_or("Red"); + if let Some((name, _)) = widgets::dropdown_named(ui, "tangent-circle-color", Some(tl!("Color:")), shown, &TANGENT_CIRCLE_COLORS, 110.0) + .and_then(|i| tangent_circle_tool::COLORS.get(i)) + { + d.fields.insert("color".into(), json!(name)); + } + }); + let (lo, hi) = tangent_circle_tool::SNAP_RANGE; + let snap = d.f64("snapTolerance", tangent_circle_tool::SNAP_PX); + widgets::label_row(ui, tl!("Snap Tolerance:"), label_w, |ui| { + if let Some(x) = widgets::range_field(ui, "tangent-circle-snap", snap, lo..=hi, " px", 2, 72.0) { + d.fields.insert("snapTolerance".into(), json!(x)); + } + }); + tangent_circle_check(ui, d, "snapWithoutGuides", tl!("Snap When Smart Guides Are Off")); return false; } let rows = [ @@ -266,6 +288,29 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { false } +/// The labels of the Tangent Circle tool's colors ([`tangent_circle_tool::COLORS`]), in its order. +const TANGENT_CIRCLE_COLORS: [&str; 6] = ["Red", "Blue", "Magenta", "Green", "Black", "Gray"]; + +/// The labels of the Tangent Circle tool's rows with a field beside them. +const TANGENT_CIRCLE_LABELS: [&str; 3] = ["Radius:", "Color:", "Snap Tolerance:"]; + +/// The width of the Tangent Circle tool's label column: [`LABEL_W`], or the widest of +/// [`TANGENT_CIRCLE_LABELS`] in the interface language with a gap after it, when that is wider. +fn tangent_circle_label_w(ui: &Ui) -> f32 { + TANGENT_CIRCLE_LABELS + .iter() + .map(|label| ui.painter().layout_no_wrap(tl!(label).to_string(), egui::FontId::proportional(12.5), egui::Color32::PLACEHOLDER).size().x + 8.0) + .fold(LABEL_W, f32::max) +} + +/// A check box for the Tangent Circle tool's option `key`, labeled `label`. +fn tangent_circle_check(ui: &mut Ui, d: &mut Dialog, key: &str, label: &str) { + let on = d.bool(key); + if widgets::check(ui, label, on, true) { + d.fields.insert(key.into(), json!(!on)); + } +} + /// OK: set the tool's options. When the tool refuses one of them, nothing is set and the dialog /// stays open. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 2c49c661fe..6f8d101f11 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -110,6 +110,78 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err()); } +/// The Tangent Circle tool's options dialog shows the preview and snapping options, OK sets them, +/// and a value the tool refuses sets none of them and keeps the dialog open. +#[test] +fn the_tangent_circle_options_set_the_preview_and_snapping() { + let mut app = app(); + app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.bool("center"), d.bool("radii"), d.str("color")), (true, true, "red".to_string())); + assert_eq!((d.f64("snapTolerance", 0.0), d.bool("snapWithoutGuides")), (3.0, true)); + let text = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for label in ["Circle Center", "Circle Radii Lines", "Color:", "Red", "Snap Tolerance:", "Snap When Smart Guides Are Off"] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + for (key, v) in [ + ("center", json!(false)), + ("radii", json!(false)), + ("color", json!("magenta")), + ("snapTolerance", json!(9)), + ("snapWithoutGuides", json!(false)), + ] { + d.fields.insert(key.into(), v); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let o = app.session.tool_options_of("tangentCircle"); + assert_eq!((&o["center"], &o["radii"], &o["color"], &o["snapWithoutGuides"]), (&json!(false), &json!(false), &json!("magenta"), &json!(false))); + assert_eq!(o["snapTolerance"].as_f64(), Some(9.0)); + // A negative tolerance is refused: nothing changes and the dialog stays open. + app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("center".into(), json!(true)); + d.fields.insert("snapTolerance".into(), json!(-2)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("`snapTolerance` must be a number from 0 to 25"), "{e}"); + assert!(app.ui.dialog.is_some()); + assert_eq!(app.session.tool_options_of("tangentCircle")["center"], json!(false)); + // Every color has a label, in the same order. + assert_eq!(super::TANGENT_CIRCLE_COLORS.len(), vectorcraft_tools::addons::tangent_circle::COLORS.len()); + for (label, (name, _)) in super::TANGENT_CIRCLE_COLORS.iter().zip(vectorcraft_tools::addons::tangent_circle::COLORS) { + assert_eq!(label.to_lowercase(), *name); + } +} + +/// The Tangent Circle tool's options dialog shows a fractional snapping tolerance as it is, and its +/// labels end before the fields beside them. +#[test] +fn the_tangent_circle_options_show_a_fractional_tolerance_beside_its_whole_label() { + fn texts(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.galley.rect.translate(t.pos.to_vec2()))), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let mut app = app(); + app.run("tool.setOption", json!({"tool": "tangentCircle", "values": {"snapTolerance": 7.5}})).unwrap(); + app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx())).textures_delta.clear(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let mut painted = vec![]; + out.shapes.iter().for_each(|c| texts(&c.shape, &mut painted)); + let at = |text: &str| painted.iter().find(|(t, _)| t == text).map(|(_, r)| *r).unwrap_or_else(|| panic!("no {text} in {painted:?}")); + let (label, field) = (at("Snap Tolerance:"), at("7.5 px")); + assert!(label.right() <= field.left(), "{label:?} runs into {field:?}"); + assert!(label.right() <= at("36 pt").left(), "the Radius field lines up with it"); + assert_eq!(app.session.tool_options_of("tangentCircle")["snapTolerance"].as_f64(), Some(7.5)); +} + #[test] fn the_parametric_shape_panel_opens_from_the_submenu_and_shows_the_shape() { let mut app = app(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..46b2273344 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7587,6 +7587,10 @@ breakText Glyphs Глифи Tangent Circle Допирателна окръжност Tangent Circle Tool Инструмент „Допирателна окръжност“ No tangent circle here Тук няма допирателна окръжност + Circle Center Център на окръжността + Circle Radii Lines Линии на радиусите + Snap Tolerance: Толеранс на прилепване: + Snap When Smart Guides Are Off Прилепване при изключени интелигентни водачи Circle: Окръжност: @msg `ids` names an object twice `ids` посочва обект два пъти @msg select two or three paths or compound paths изберете два или три пътя или съставни пътя diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..796b299720 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7636,6 +7636,10 @@ shape Open Otvoren Tangent Circle Tangentna kružnica Tangent Circle Tool Alat tangentna kružnica No tangent circle here Ovdje nema tangentne kružnice + Circle Center Središte kružnice + Circle Radii Lines Linije poluprečnika + Snap Tolerance: Tolerancija hvatanja: + Snap When Smart Guides Are Off Hvatanje kad su pametne vodilice isključene Circle: Kružnica: @msg `ids` names an object twice `ids` navodi objekat dvaput @msg select two or three paths or compound paths odaberite dvije ili tri putanje ili složene putanje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..4c4f72db56 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8468,6 +8468,10 @@ breakText Glyphs Glifs Tangent Circle Cercle tangent Tangent Circle Tool Eina de cercle tangent No tangent circle here Aquí no hi ha cap cercle tangent + Circle Center Centre del cercle + Circle Radii Lines Línies dels radis + Snap Tolerance: Tolerància d’ajust: + Snap When Smart Guides Are Off Ajusta amb les guies intel·ligents desactivades Circle: Cercle: @msg `ids` names an object twice `ids` indica un objecte dues vegades @msg select two or three paths or compound paths seleccioneu dos o tres camins o camins compostos diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..c06a96a0f9 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8449,6 +8449,10 @@ breakText Glyphs Glyfy Tangent Circle Tečná kružnice Tangent Circle Tool Nástroj Tečná kružnice No tangent circle here Zde není žádná tečná kružnice + Circle Center Střed kružnice + Circle Radii Lines Čáry poloměrů + Snap Tolerance: Tolerance přichytávání: + Snap When Smart Guides Are Off Přichytávat při vypnutých chytrých vodítkách Circle: Kružnice: @msg `ids` names an object twice `ids` uvádí některý objekt dvakrát @msg select two or three paths or compound paths vyberte dvě nebo tři cesty nebo složené cesty diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..0c79eed842 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10505,6 +10505,10 @@ breakText Glyphs Glyffer Tangent Circle Tangentcirkel Tangent Circle Tool Tangentcirkel-værktøj No tangent circle here Ingen tangentcirkel her + Circle Center Cirklens centrum + Circle Radii Lines Radiuslinjer + Snap Tolerance: Snap-tolerance: + Snap When Smart Guides Are Off Snap, når smarte hjælpelinjer er slået fra Circle: Cirkel: @msg `ids` names an object twice `ids` nævner et objekt to gange @msg select two or three paths or compound paths vælg to eller tre stier eller sammensatte stier diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..fee80c1e97 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8074,6 +8074,10 @@ breakText Glyphs Glyphen Tangent Circle Tangentialkreis Tangent Circle Tool Tangentialkreis-Werkzeug No tangent circle here Hier kein Tangentialkreis + Circle Center Kreismittelpunkt + Circle Radii Lines Radiuslinien + Snap Tolerance: Einrasttoleranz: + Snap When Smart Guides Are Off Einrasten bei ausgeschalteten intelligenten Hilfslinien Circle: Kreis: @msg `ids` names an object twice `ids` nennt ein Objekt zweimal @msg select two or three paths or compound paths wählen Sie zwei oder drei Pfade oder zusammengesetzte Pfade aus diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..82f1ab269a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8440,6 +8440,10 @@ breakText Glyphs Γλύφοι Tangent Circle Εφαπτόμενος κύκλος Tangent Circle Tool Εφαπτόμενος κύκλος (Tangent Circle Tool) No tangent circle here Δεν υπάρχει εφαπτόμενος κύκλος εδώ + Circle Center Κέντρο κύκλου + Circle Radii Lines Γραμμές ακτίνων + Snap Tolerance: Ανοχή προσκόλλησης: + Snap When Smart Guides Are Off Προσκόλληση με ανενεργούς έξυπνους οδηγούς Circle: Κύκλος: @msg `ids` names an object twice το `ids` αναφέρει ένα αντικείμενο δύο φορές @msg select two or three paths or compound paths επιλέξτε δύο ή τρεις διαδρομές ή σύνθετες διαδρομές diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..3afad60b1e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8426,6 +8426,10 @@ breakText Glyphs Glifos Tangent Circle Círculo tangente Tangent Circle Tool Herramienta Círculo tangente No tangent circle here No hay círculo tangente aquí + Circle Center Centro del círculo + Circle Radii Lines Líneas de radio + Snap Tolerance: Tolerancia de ajuste: + Snap When Smart Guides Are Off Ajustar con las guías inteligentes desactivadas Circle: Círculo: @msg `ids` names an object twice `ids` indica un objeto dos veces @msg select two or three paths or compound paths seleccione dos o tres trazados o trazados compuestos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..e720421c14 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8516,6 +8516,10 @@ breakText Glyphs Merkit Tangent Circle Sivuava ympyrä Tangent Circle Tool Sivuava ympyrä -työkalu No tangent circle here Tässä ei ole sivuavaa ympyrää + Circle Center Ympyrän keskipiste + Circle Radii Lines Säteiden viivat + Snap Tolerance: Tartuntatoleranssi: + Snap When Smart Guides Are Off Tartu, kun älykkäät apuviivat eivät ole käytössä Circle: Ympyrä: @msg `ids` names an object twice `ids` mainitsee saman objektin kahdesti @msg select two or three paths or compound paths valitse kaksi tai kolme polkua tai yhdistelmäpolkua diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..dbbe8a8d65 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8445,6 +8445,10 @@ breakText Glyphs Glyphes Tangent Circle Cercle tangent Tangent Circle Tool Outil Cercle tangent No tangent circle here Aucun cercle tangent ici + Circle Center Centre du cercle + Circle Radii Lines Lignes des rayons + Snap Tolerance: Tolérance du magnétisme : + Snap When Smart Guides Are Off Magnétisme avec les repères commentés désactivés Circle: Cercle : @msg `ids` names an object twice `ids` désigne deux fois le même objet @msg select two or three paths or compound paths sélectionnez deux ou trois tracés ou tracés transparents diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..e68835cefe 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4336,6 +4336,11 @@ arrowhead Feather પીંછું Tangent Circle સ્પર્શક વર્તુળ Tangent Circle Tool સ્પર્શક વર્તુળ ટૂલ No tangent circle here અહીં કોઈ સ્પર્શક વર્તુળ નથી + Circle Center વર્તુળનું કેન્દ્ર + Circle Radii Lines ત્રિજ્યા રેખાઓ + Snap Tolerance: સ્નેપ સહનશીલતા: + Snap When Smart Guides Are Off સ્માર્ટ ગાઇડ બંધ હોય ત્યારે સ્નેપ કરો + Magenta મેજેન્ટા Tangent Circle… સ્પર્શક વર્તુળ… Taper ટેપર Target લક્ષ્ય diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..cc5be75191 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5889,6 +5889,10 @@ arrowhead Feather पंख Tangent Circle स्पर्शी वृत्त Tangent Circle Tool स्पर्शी वृत्त टूल No tangent circle here यहाँ कोई स्पर्शी वृत्त नहीं है + Circle Center वृत्त का केंद्र + Circle Radii Lines त्रिज्या रेखाएँ + Snap Tolerance: स्नैप सहिष्णुता: + Snap When Smart Guides Are Off स्मार्ट गाइड्स बंद होने पर स्नैप करें Tangent Circle… स्पर्शी वृत्त… Taper टेपर Target लक्ष्य diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..01cbf908a9 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8435,6 +8435,10 @@ breakText Glyphs Glifák Tangent Circle Érintőkör Tangent Circle Tool Érintőkör eszköz No tangent circle here Itt nincs érintőkör + Circle Center Kör középpontja + Circle Radii Lines Sugárvonalak + Snap Tolerance: Illesztési tűrés: + Snap When Smart Guides Are Off Illesztés kikapcsolt intelligens segédvonalaknál Circle: Kör: @msg `ids` names an object twice `ids`: egy objektumot kétszer nevez meg @msg select two or three paths or compound paths jelölj ki két vagy három útvonalat vagy összetett útvonalat diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..b43a891873 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8290,6 +8290,10 @@ breakText Glyphs Glif Tangent Circle Lingkaran singgung Tangent Circle Tool Alat lingkaran singgung No tangent circle here Tidak ada lingkaran singgung di sini + Circle Center Pusat lingkaran + Circle Radii Lines Garis jari-jari + Snap Tolerance: Toleransi kancing: + Snap When Smart Guides Are Off Kancing saat panduan cerdas nonaktif Circle: Lingkaran: @msg `ids` names an object twice `ids` menyebut satu objek dua kali @msg select two or three paths or compound paths pilih dua atau tiga jalur atau jalur gabungan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..c4d2d3bef5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8112,6 +8112,10 @@ breakText Glyphs Glifi Tangent Circle Cerchio tangente Tangent Circle Tool Strumento Cerchio tangente No tangent circle here Nessun cerchio tangente qui + Circle Center Centro del cerchio + Circle Radii Lines Linee dei raggi + Snap Tolerance: Tolleranza di aggancio: + Snap When Smart Guides Are Off Aggancia con le guide sensibili disattivate Circle: Cerchio: @msg `ids` names an object twice `ids` indica due volte lo stesso oggetto @msg select two or three paths or compound paths seleziona due o tre tracciati o tracciati composti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..436a410fef 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -10001,6 +10001,10 @@ breakText Glyphs 字形 Tangent Circle 接円 Tangent Circle Tool 接円ツール No tangent circle here ここに接円はありません + Circle Center 円の中心 + Circle Radii Lines 半径の線 + Snap Tolerance: スナップ許容値: + Snap When Smart Guides Are Off スマートガイドがオフのときもスナップ Circle: 円: @msg `ids` names an object twice `ids` に同じオブジェクトが 2 回指定されています @msg select two or three paths or compound paths パスまたは複合パスを 2 つか 3 つ選択してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..6b7621d4ce 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10623,6 +10623,10 @@ breakText Glyphs გლიფები Tangent Circle მხები წრე Tangent Circle Tool მხები წრის ხელსაწყო No tangent circle here აქ მხები წრე არ არის + Circle Center წრის ცენტრი + Circle Radii Lines რადიუსის ხაზები + Snap Tolerance: მიბმის დაშვება: + Snap When Smart Guides Are Off მიბმა, როცა ჭკვიანი დამხმარე ხაზები გამორთულია Circle: წრე: @msg `ids` names an object twice `ids` ერთსა და იმავე ობიექტს ორჯერ მიუთითებს @msg select two or three paths or compound paths მონიშნეთ ორი ან სამი ტრაექტორია ან შედგენილი ტრაექტორია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..64a60438bd 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8084,6 +8084,10 @@ breakText Glyphs 글리프 Tangent Circle 접원 Tangent Circle Tool 접원 도구 No tangent circle here 여기에는 접원이 없음 + Circle Center 원 중심 + Circle Radii Lines 반지름 선 + Snap Tolerance: 스냅 허용 오차: + Snap When Smart Guides Are Off 스마트 안내선이 꺼져 있을 때 스냅 Circle: 원: @msg `ids` names an object twice `ids`에 같은 오브젝트가 두 번 있습니다 @msg select two or three paths or compound paths 패스나 컴파운드 패스를 두 개 또는 세 개 선택하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..453255c84a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10343,6 +10343,10 @@ breakText Glyphs Glyphs Tangent Circle Raakcirkel Tangent Circle Tool Raakcirkel-gereedschap No tangent circle here Hier geen raakcirkel + Circle Center Middelpunt van cirkel + Circle Radii Lines Straallijnen + Snap Tolerance: Snapping-tolerantie: + Snap When Smart Guides Are Off Snappen als slimme hulplijnen uit zijn Circle: Cirkel: @msg `ids` names an object twice `ids` noemt een object twee keer @msg select two or three paths or compound paths selecteer twee of drie paden of samengestelde paden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..5f41c83584 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8308,6 +8308,10 @@ breakText Glyphs Glify Tangent Circle Okrąg styczny Tangent Circle Tool Narzędzie Okrąg styczny No tangent circle here Brak okręgu stycznego w tym miejscu + Circle Center Środek okręgu + Circle Radii Lines Linie promieni + Snap Tolerance: Tolerancja przyciągania: + Snap When Smart Guides Are Off Przyciągaj przy wyłączonych inteligentnych liniach pomocniczych Circle: Okrąg: @msg `ids` names an object twice `ids` wskazuje ten sam obiekt dwa razy @msg select two or three paths or compound paths zaznacz dwie lub trzy ścieżki lub ścieżki złożone diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..29cf345aa6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8468,6 +8468,10 @@ breakText Glyphs Glifos Tangent Circle Círculo tangente Tangent Circle Tool Ferramenta Círculo tangente No tangent circle here Nenhum círculo tangente aqui + Circle Center Centro do Círculo + Circle Radii Lines Linhas dos Raios + Snap Tolerance: Tolerância de Ajuste: + Snap When Smart Guides Are Off Ajustar com as Guias Inteligentes Desligadas Circle: Círculo: @msg `ids` names an object twice `ids` indica um objeto duas vezes @msg select two or three paths or compound paths selecione dois ou três caminhos ou caminhos compostos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..ee3f2d2b8a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8440,6 +8440,10 @@ breakText Glyphs Глифы Tangent Circle Касательная окружность Tangent Circle Tool Инструмент «Касательная окружность» No tangent circle here Здесь нет касательной окружности + Circle Center Центр окружности + Circle Radii Lines Линии радиусов + Snap Tolerance: Допуск привязки: + Snap When Smart Guides Are Off Привязка при выключенных умных направляющих Circle: Окружность: @msg `ids` names an object twice `ids` указывает объект дважды @msg select two or three paths or compound paths выделите два или три контура или составных контура diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..c6fbba6091 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8484,6 +8484,10 @@ breakText Glyphs Glyfer Tangent Circle Tangentcirkel Tangent Circle Tool Tangentcirkelverktyget No tangent circle here Ingen tangentcirkel här + Circle Center Cirkelns mittpunkt + Circle Radii Lines Radielinjer + Snap Tolerance: Fästtolerans: + Snap When Smart Guides Are Off Fäst när smarta stödlinjer är av Circle: Cirkel: @msg `ids` names an object twice `ids` anger ett objekt två gånger @msg select two or three paths or compound paths markera två eller tre banor eller sammansatta banor diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..94ef18a271 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10339,6 +10339,10 @@ breakText Glyphs Glifler Tangent Circle Teğet Daire Tangent Circle Tool Teğet Daire Aracı No tangent circle here Burada teğet daire yok + Circle Center Daire Merkezi + Circle Radii Lines Yarıçap Çizgileri + Snap Tolerance: Yapışma Toleransı: + Snap When Smart Guides Are Off Akıllı Kılavuzlar Kapalıyken Yapış Circle: Daire: @msg `ids` names an object twice `ids` bir nesneyi iki kez belirtiyor @msg select two or three paths or compound paths iki veya üç yol ya da bileşik yol seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..2efdc32d6c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8094,6 +8094,10 @@ breakText Glyphs Гліфи Tangent Circle Дотичне коло Tangent Circle Tool Інструмент «Дотичне коло» No tangent circle here Тут немає дотичного кола + Circle Center Центр кола + Circle Radii Lines Лінії радіусів + Snap Tolerance: Допуск прив’язки: + Snap When Smart Guides Are Off Прив’язка, коли розумні напрямні вимкнено Circle: Коло: @msg `ids` names an object twice `ids` указує об’єкт двічі @msg select two or three paths or compound paths виділіть два або три контури чи складені контури diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..83c630a692 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8140,6 +8140,10 @@ breakText Glyphs Glyph Tangent Circle Đường tròn tiếp xúc Tangent Circle Tool Công cụ Đường tròn tiếp xúc No tangent circle here Không có đường tròn tiếp xúc ở đây + Circle Center Tâm đường tròn + Circle Radii Lines Đường bán kính + Snap Tolerance: Dung sai hút: + Snap When Smart Guides Are Off Hút khi tắt đường căn thông minh Circle: Đường tròn: @msg `ids` names an object twice `ids` nêu một đối tượng hai lần @msg select two or three paths or compound paths chọn hai hoặc ba đường dẫn hoặc đường dẫn phức hợp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..534aedde82 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8318,6 +8318,10 @@ breakText Glyphs 字形 Tangent Circle 相切圆 Tangent Circle Tool 相切圆工具 No tangent circle here 此处没有相切圆 + Circle Center 圆心 + Circle Radii Lines 半径线 + Snap Tolerance: 吸附容差: + Snap When Smart Guides Are Off 智能参考线关闭时也吸附 Circle: 圆: @msg `ids` names an object twice `ids` 重复指定了同一个对象 @msg select two or three paths or compound paths 请选择两个或三个路径或复合路径 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..60c203089e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8142,6 +8142,10 @@ breakText Glyphs 字符 Tangent Circle 相切圓 Tangent Circle Tool 相切圓工具 No tangent circle here 此處沒有相切圓 + Circle Center 圓心 + Circle Radii Lines 半徑線 + Snap Tolerance: 靠齊容許度: + Snap When Smart Guides Are Off 智慧型參考線關閉時也靠齊 Circle: 圓: @msg `ids` names an object twice `ids` 將同一個物件指定了兩次 @msg select two or three paths or compound paths 請選取兩個或三個路徑或複合路徑 diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..5adc7e015a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14545,8 +14545,9 @@ Tools: preferences): `diameter` (0.25 to 200 pt, 20), `tolerance` (how near two anchors count as coincident, 0 to 3 pt, 0.002) and `together` (Keep Shared Points Together). - **Tangent Circle Tool** (`tangentCircle`): draws a circle on two path segments of any unlocked paths, selected or - not. A click picks the first segment; over a second segment the circle that would be drawn shows (red) with its - center, its radii to the two touch points and its radius, or a note that there is none. A click there draws the + not. A click picks the segment nearest the pointer within reach (see `snapTolerance` below) as the first segment; + over a second segment the circle that would be drawn shows (in `color`) with its center cross, its radii to the two + touch points (`center`, `radii`) and its radius, or a note that there is none. A click there draws the circle that is tangent to the first segment at the point clicked and touches the second (its center on the first segment's normal there). With Shift the circle instead has the tool's `radius` and may touch the first segment anywhere along it. A drag from the second segment sets the radius to the drag's length, and the circle may again @@ -14566,8 +14567,14 @@ Tools: change to the first segment that makes no undo step (a live preview, or one that was canceled) forgets the first segment. The circle is looked for again whenever either segment no longer has the shape it was found on, so a canceled preview does not leave a circle worked out on the previewed paths. - Option (`tool.setOption`, or a double-click on the tool): `radius` (pt, 0.01 to 1000000, 36). `tool.setOption` - gives an error for a value outside that range or one that is not a number, and for any other option. + Options (`tool.setOption`, or a double-click on the tool; kept with the preferences): `radius` (pt, 0.01 to + 1000000, 36); `center` and `radii` (true or false, both true) show the center cross and the radii; `color` (`red`, + `blue`, `magenta`, `green`, `black` or `gray`; `red`) is the color of the circle, the cross, the radii and the note; + `snapTolerance` (screen pixels, 0 to 25, 3; VectorCraft's own range and default) is how near the pointer picks a + segment while Smart Guides are on (their Snapping Tolerance counts instead when it is larger) or while they are off + with `snapWithoutGuides` (true or false, true) on. Otherwise a segment is picked within the Selection Tolerance, which is also the least reach with snapping. + `tool.setOption` gives an error for a value outside an option's range, of the wrong type, or a color not listed, and + for any other option, and then sets none of the values. - **Trim at Crossings Tool** (`trimAtCrossings`): removes stretches of paths between the places where they are crossed, on any path that can be edited, selected or not. A click runs `addon.pathtools.trim` with `at`, for the path within 4 screen pixels of the pointer. A drag draws a rectangle and runs it with `rect` on release; once the pointer has diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..db4b346bce 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2997,6 +2997,8 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +The tool's options dialog also sets the preview and how a segment is picked, the options the help page lists (https://docs.astutegraphics.com/subscribe/tangent-circle-tool): Circle Center and Circle Radii Lines (`center`, `radii`) show or hide the center cross and the radii, Color (`color`: red, blue, magenta, green, black or gray) colors the circle, the cross, the radii and the note, Snap Tolerance (`snapTolerance`, screen pixels) is how near the pointer picks a segment with Smart Guides on, the Smart Guides Snapping Tolerance counting when it is larger, and Snap When Smart Guides Are Off (`snapWithoutGuides`) keeps that reach with Smart Guides off; without it the Selection Tolerance applies. Of the segments within reach the nearest is picked. The defaults (both shown, red, 3 px, snapping on) and the 0 to 25 px range are VectorCraft's own; they are kept with the preferences, and `tool.setOption` gives an error for a value an option does not take. Tests: `addons::tangent_circle::tests` in `vectorcraft-tools` (the preview options, the snapping reach, the options' values) and `the_tangent_circle_options_set_the_preview_and_snapping` in `vectorcraft-ui-egui`. + ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, since 2026-11-16; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut) removes stretches of paths between the places where they are crossed by another path or by themselves, on any path that can be edited, selected or not. A click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; each is one undo step, and Escape during a drag removes nothing. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, a path that nothing crosses is removed whole, and the stretches that stay get no new anchors. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing. Add Points at / Split at Crossings share the crossing search: segments that meet at an anchor now count where they cross again elsewhere, and with Self Crossings a curved segment that loops over itself crosses itself. Command `addon.pathtools.trim`; `vectorcraft_pathops::addons::pathtools::{crossings_on, spans, without_spans}`. Hovering shows in red the stretch a click would remove, worked out by the same code the command uses (`vectorcraft_tools::addons::trim::plan`), and a drag that reaches at most 32 paths shows what its release would remove; a preview spends at most a twentieth of the crossing work a click may (2026-11-15; tests `hovering_*`, `in_isolation_mode_*`, `a_path_whose_crossings_*` and `a_small_drag_*` in `addons::trim` in `vectorcraft-tools`, `hovering_with_the_tool_shows_the_stretch_its_click_removes` and `what_the_tool_shows_*` in `vectorcraft-engine`). Not yet: crossings with type, images and symbol instances. Tests: `crossings_on_*`, `segments_*`, `a_segment_that_loops_over_itself_crosses_itself`, `one_work_budget_*`, `spans_divide_*`, `a_subpath_without_*` and `a_slice_*` in `addons::pathtools::tests` in `vectorcraft-pathops`, `addons::trim` in `vectorcraft-tools` (click, rectangle, freehand line, Escape), `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine` (a middle and an end stretch, a closed path opening, a rectangle and a line as one undo step, locked and hidden paths, guides and clipping paths, paths nothing crosses, compound path members, the selection, 3,000 other paths, a path too large to search left alone until touched, bad params refused), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui`, `edit_toolbar::tests` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. The tool shows the Knife's cursor, now drawn as a knife with the blade's point on the hotspot (2026-11-16; tests `trim_at_crossings_is_in_the_scissors_flyout` and `a_saved_toolbar_without_trim_at_crossings_keeps_its_layout` in `edit_toolbar::tests`, `trim_at_crossings_is_in_the_scissors_group_once` in `addons::tests`, `headless_backend_methods` in `vectorcraft-mcp`, `the_knife_shows_a_knife_with_its_point_on_the_hotspot` in `cursors::tests` and `drawing_tools_show_their_own_cursor` in `vectorcraft-tools`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..f761aa98f7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -554,7 +554,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 › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.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 › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.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 › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.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 › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none; one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.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 › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none (its options show or hide the center cross and the radii, set their color, and set how near a segment is picked with Smart Guides on or off); one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.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 › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its 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 › 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 | From 0098c45951371dd84dcf74de63a72235668c9839 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:22:05 -0800 Subject: [PATCH 014/101] Blob Brush: a stroke at one point paints a dab, and the tip shows what the release paints A Pressure or Stylus Wheel stroke whose samples all lie at one point gave path.blob a spine with no length, and the command failed with "empty brush stroke". It now paints one dab sized from the first sample's reading, as a single point does. When Size changes from Fixed to Pressure or Stylus Wheel during a drag, the release sends no pressure or wheel for the stroke, so it paints at the Size. The tip outline now reads the pressure and the pen pose only when the release reads them, for the Blob Brush and the Eraser. --- crates/engine/src/cmd/draw2/freehand.rs | 5 ++++- crates/engine/src/tests/draw2.rs | 7 +++++++ crates/tools/src/draw2/gesture.rs | 11 +++++++---- crates/tools/src/draw2/gesture/tests.rs | 15 +++++++++++++++ docs/mcp.md | 5 ++++- docs/target-app-parity.md | 2 +- 6 files changed, 38 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index a1e60d85e7..d8499deeee 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -556,9 +556,12 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { Some(tol) => Some(pressure_region(&spine(Some(tol)), size, *variation, prof)?).filter(|r| !r.is_empty()), None => None, }; + let dab = || brush_region(&mapped_pts[..1], vectorcraft_tools::draw2::pressure_size(size, *variation, prof.at(0.0))); match fitted { Some(r) => r, - None => pressure_region(&spine(None), size, *variation, prof)?, + // Samples that all lie at one point give a spine with no length: one dab from the + // first reading, as a click paints. + None => Some(pressure_region(&spine(None), size, *variation, prof)?).filter(|r| !r.is_empty()).unwrap_or_else(dab), } } // A click: one dab as wide as the pen pressed or the wheel was set. diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 48145a0361..2fd2224984 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -761,6 +761,13 @@ fn blob_brush_size_follows_the_stylus_wheel() { let wide = blob(&mut s, with(&tip, json!({"points": [[100, 500, null, null, null, null, 1]]}))); let thin = blob(&mut s, with(&tip, json!({"points": [[300, 500, null, null, null, null, 0]]}))); assert!(inside(&s, wide, 100.0, 508.0) && !inside(&s, thin, 300.0, 503.0), "a dab follows the wheel"); + // A stroke whose samples all lie at one point paints a dab sized from its first reading, with + // the wheel and with pressure. + let still = blob(&mut s, with(&tip, json!({"points": [[500, 500, null, null, null, null, 1], [500, 500, null, null, null, null, 0]]}))); + let pressed_still = blob(&mut s, with(&tip, json!({"sizeMode": "pressure", "points": [[700, 500, 1], [700, 500, 0]]}))); + for (id, x) in [(still, 500.0), (pressed_still, 700.0)] { + assert!(inside(&s, id, x, 508.0) && !inside(&s, id, x, 510.0), "a dab from the first reading at x {x}"); + } // A 25% round tip lying level: about 0.5 pt tall at the left end to 4.5 pt at the right. let flat = blob(&mut s, with(&tip, json!({"roundness": 25, "points": wheeled(600.0, &|w| json!(w))}))); assert!(inside(&s, flat, 290.0, 601.9) && !inside(&s, flat, 110.0, 601.0), "a flat tip follows the wheel"); diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 5eba8dc7d8..2601b27a33 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1353,16 +1353,19 @@ impl GestureTool { /// value on a mode that follows the pen goes from the value less its Variation to the value /// plus it as the pen reads now (the pressure once the pen has pressed less than fully, the /// tilt, rotation and wheel of the last point, and the bearing of the last point the pen leaned 1° or - /// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed and a - /// pen that gives no reading, the values themselves. The Blob Brush's size follows the pen the + /// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed, a + /// pen that gives no reading and a reading the release does not send (a mode set during the + /// drag), the values themselves. The Blob Brush's size follows the pen the /// same way while it paints, as `path.blob` reads the stroke, and its angle and roundness are /// its own values (a roundness of 0 included). fn tip_now(&self) -> [f64; 3] { if !matches!(self.id, "eraser" | "blobBrush") || !self.active { return [self.angle, self.roundness, self.size]; } - let pressure = if self.light { self.pressures.last().map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; - let tip = self.tip_for(pressure, self.poses.last().copied().flatten(), self.bearing); + // What the release does not read ([`Self::reads_pressures`], [`Self::reads_poses`]) reads ½. + let pressure = if self.reads_pressures() { self.pressures.last().map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; + let (pose, bearing) = if self.reads_poses() { (self.poses.last().copied().flatten(), self.bearing) } else { (None, None) }; + let tip = self.tip_for(pressure, pose, bearing); if self.id == "blobBrush" { return [self.angle, self.roundness, tip[2]]; } diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 5df801b3a0..323bef8015 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -3310,6 +3310,21 @@ fn the_blob_brush_size_follows_the_stylus_wheel() { let flat = tip(&t); assert!((flat.width() - 28.0).abs() < 0.01 && flat.height() < 0.1, "{flat:?}"); t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); + // Size set from Fixed to Stylus Wheel or Pressure during a drag: the release reads no wheel or + // pressure for the points before it, so the tip keeps the Size, as the release paints. + t.set_option("roundness", &json!(50)); + for (mode, pressure) in [("stylusWheel", 1.0), ("pressure", 0.25)] { + t.set_option("sizeMode", &json!("fixed")); + let ev = |kind, x| PointerEvent { pen: wheel(Some(1.0)), pressure, ..PointerEvent::new(kind, x, 50.0) }; + t.pointer(&cx, &ev(PointerKind::Down, 100.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 200.0)); + t.set_option("sizeMode", &json!(mode)); + t.pointer(&cx, &ev(PointerKind::Drag, 300.0)); + near(tip(&t), (290.0, 45.0, 310.0, 55.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 300.0)); + let Some(Action::Exec(_, v)) = acts.first() else { panic!("{acts:?}") }; + assert_eq!(v["points"], json!([[100.0, 50.0], [200.0, 50.0], [300.0, 50.0]]), "{mode}"); + } } /// An Eraser value on Stylus Wheel follows the wheel the pen recorded, in the tip outline while it diff --git a/docs/mcp.md b/docs/mcp.md index 2dd8666c9d..79b2f548cb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7032,8 +7032,11 @@ variation where the pen presses lightest to the size plus it where the pen press size less the variation at 0 to the size plus it at 1 of an airbrush pen's finger wheel, the seventh value of each point; a point without a wheel counts as 0.5, the size itself, and a stroke with no wheel reading, such as a mouse drag, paints at the size. Which way the wheel runs and the size itself without a reading are VectorCraft's own rules. +With Pressure or Stylus Wheel, a stroke whose points all lie at one place paints one dab sized from its first point's +reading, as a single point does. The command refuses another mode with an error that names `sizeMode`, and the document does not change. In the -desktop app the Blob Brush's tip outline at the pointer takes the size the pen gives while it paints. +desktop app the Blob Brush's tip outline at the pointer takes the size the pen gives while it paints, and keeps the +size when Size is set to Pressure or Stylus Wheel during the drag, which the release then paints at. `tool.setOption {tool: "blobBrush"}` takes `sizeMode` and `sizeVariation` too. `path.eraseRegion {rect: [x, y, width, height]}` takes a rectangle in place of `points` and erases everything inside diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8e0abd5a4c..547b0e23b0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2066,7 +2066,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; Windows pointer messages have no field for it, and the web build does not read it yet. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft). - - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). + - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. A stroke whose points all lie at one place paints one dab sized from its first reading, on Pressure too. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too, and keeps the Size when the menu changes during the drag, as the release paints. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). From cee4f8d276fcee3ad2b22c24ed8d296b6b0af7ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:04:01 -0800 Subject: [PATCH 015/101] Parametric Shape: measure the box the same way before and after a W or H edit With `reference`, `addon.pathtools.shape.set` measured the shape's box before the edit with Use Preview Bounds and fell back to the geometric box when the preview gave none, and it chose again after the edit. When the preview gave a box before the edit and none after it, or the reverse, the shape moved by the difference between two different boxes. The measure used before the edit is now used after it. The params text and docs/mcp.md now say that snapping to the pixel grid and an attachment to a path apply after the reference point is kept, as they do for the Transform panel's W and H. The docs line in docs/target-app-parity.md changes only the lines it needs. --- .../engine/src/cmd/addons/pathtools/shape.rs | 21 +++++++++++-------- docs/mcp.md | 5 +++-- docs/target-app-parity.md | 6 +++--- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs index 551d5c7dba..6c16893aba 100644 --- a/crates/engine/src/cmd/addons/pathtools/shape.rs +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Edit Parametric Shape", [], None, - "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do), otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}", + "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}", has_doc, set ), @@ -108,21 +108,24 @@ fn set(s: &mut Session, p: &Value) -> Result { if shape != old { // Without a center, the reference point of the bounding box (as the Transform panel and // `object.setBounds` measure it; the geometric box where the preview leaves none) keeps - // its place: the new outline moves onto it. + // its place: the new outline moves onto it. The box after the edit is measured the same way + // as the box before it. let how = s.bounds_measure(); - let boxed = move |d: &Document| { - effects::preview::oriented_bounds_with(d, &[id], how) - .or_else(|| effects::preview::oriented_bounds_with(d, &[id], effects::preview::Measure { preview: false, ..how })) - }; + let geometric = effects::preview::Measure { preview: false, ..how }; + let boxed = |d: &Document, m: effects::preview::Measure| effects::preview::oriented_bounds_with(d, &[id], m).map(|b| (m, b)); let keep = match reference.filter(|_| p.get("center").is_none_or(Value::is_null)) { - Some(i) => Some((i, boxed(&s.doc()?.doc).ok_or_else(|| EngineError::Other("no bounds".into()))?.reference_point(i))), + Some(i) => { + let d = &s.doc()?.doc; + let (m, b) = boxed(d, how).or_else(|| boxed(d, geometric)).ok_or_else(|| EngineError::Other("no bounds".into()))?; + Some((i, m, b.reference_point(i))) + } None => None, }; let path = outline(&shape, C)?; s.edit(EDIT, |d, sel| { shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path); - if let Some((i, was)) = keep - && let Some(now) = boxed(d).map(|b| b.reference_point(i)) + if let Some((i, m, was)) = keep + && let Some(now) = boxed(d, m).map(|(_, b)| b.reference_point(i)) && now != was { let mut moved = shape; diff --git a/docs/mcp.md b/docs/mcp.md index bafdc73f8f..4ddf7b463c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14751,8 +14751,9 @@ Commands: - `addon.pathtools.shape.set {id, …}` changes a parametric shape's numbers (the same keys; a new `kind` takes its own defaults for the values not given) and redraws it in place. With `reference` (0 to 8 on the 9-point grid of the bounding box as `object.setBounds` measures it, rotated with rotated objects) and no `center`, that point of the box - keeps its place, as with the Transform panel's W and H; otherwise the shape's center stays. A `reference` outside 0 - to 8 is an error. With no change it makes no step. → `{id, shape}` (its numbers now, so `{id}` alone reads them; + keeps its place, as with the Transform panel's W and H; otherwise the shape's center stays. Snapping to the pixel + grid and an attachment to a path apply after that, as they do for the Transform panel's W and H, and can move the + point. A `reference` outside 0 to 8 is an error. With no change it makes no step. → `{id, shape}` (its numbers now, so `{id}` alone reads them; `null` when snapping to the pixel grid left a plain path). - `addon.pathtools.shape.convert {ids?}` makes the selected plain closed paths that are rectangles, ellipses or polygons with equal sides and corners (stretched along their own axes at most) parametric shapes with the same diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6e2efc2feb..b49b61dfa4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2821,9 +2821,9 @@ ellipse, polygon and star with 3 to 1,000 sides or points, ring, arrow, cross, h limited to the middle of a side): a drag from the centre sizes and turns one, the arrow keys change its count and values while dragging, handles edit a selected one, a double-click places one with the last settings, and its panel edits the numbers (its W and H keep the point chosen in the shared reference point locator in place). A shape is a plain path -whose numbers and outline fingerprint sit in one object-data entry that SVG export leaves out; moving, rotating or -scaling it keeps it editable, editing its anchors makes it a plain path. Convert to Parametric Shape recognises plain -rectangles, ellipses and regular polygons. Geometry in +whose numbers and outline fingerprint sit in one object-data entry that SVG export +leaves out; moving, rotating or scaling it keeps it editable, editing its anchors makes it a plain path. Convert to +Parametric Shape recognises plain rectangles, ellipses and regular polygons. Geometry in `vectorcraft_pathops::addons::pathtools::shapes`. Tests: `shapes` in `vectorcraft-pathops` (each kind, ranges, recovery after transforms, recognition), `addons::parametric_shape` in `vectorcraft-tools` (drag, keys, handles, stored data), `cmd::addons::pathtools::tests` in `vectorcraft-engine` (each command one undo step, bad params refused, From 28de8119c6f88b4ea4876fedf36f4f57d16bfde1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:04:43 -0800 Subject: [PATCH 016/101] Canvas: a long dashed overlay line draws only the dashes on screen A dashed tool overlay line was dashed over its whole screen length, so a line that runs far past the canvas at a high zoom built a dash shape for every 7 px of it, nearly all of them off screen. A line millions of pixels long built hundreds of thousands of shapes every frame. The line is now clipped to the canvas in f64 before it is dashed, with the pattern started where the whole line would have it, so the visible dashes stay where they were. A line off the canvas, or with an end at infinity, draws nothing. --- crates/ui-egui/src/canvas/overlays.rs | 45 +++++++++++++++++-- crates/ui-egui/src/canvas/tests.rs | 64 +++++++++++++++++++++++++++ 2 files changed, 105 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b4d2d44aac..b94a739997 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -8,7 +8,7 @@ use super::artboards::names_an_artboard; use super::input::marquee_through; use super::outline::{KEY_OUTLINE, c32, node_outline, selection_hit_at, stroke_path, to_screen_path, too_many_anchors}; use super::selection_marks::{MarkOptions, SelectionMarks}; -use super::{BezPath, Color32, CornerRadius, NodeKind, Overlay, Pos2, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, vec2}; +use super::{BezPath, Color32, CornerRadius, NodeKind, Overlay, Point, Pos2, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, vec2}; pub(super) fn hover_highlight(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { let Some(h) = app.hover_doc else { return }; @@ -452,6 +452,42 @@ pub(super) fn dashes_from(line: &[Pos2], s: Stroke, from: f64, out: &mut Vec) { + if !(a.is_finite() && b.is_finite()) { + return; + } + let r = clip.expand(s.width.max(1.0)); + let (left, right, top, bottom) = (f64::from(r.left()), f64::from(r.right()), f64::from(r.top()), f64::from(r.bottom())); + let d = b - a; + let (mut t0, mut t1) = (0.0_f64, 1.0_f64); + // Each edge as (the run toward it, the room before it), as `grid::clip_segment` does in `f32`. + for (run, room) in [(-d.x, a.x - left), (d.x, right - a.x), (-d.y, a.y - top), (d.y, bottom - a.y)] { + if run == 0.0 { + if room < 0.0 { + return; + } + } else if run < 0.0 { + t0 = t0.max(room / run); + } else { + t1 = t1.min(room / run); + } + } + if t0 > t1 { + return; + } + let at = |t: f64| { + let p = a + d * t; + egui::pos2(p.x as f32, p.y as f32) + }; + // How far along the whole line the part on the canvas starts. + dashes_from(&[at(t0), at(t1)], s, d.hypot() * t0, out); +} + /// Add to `out` each line of `line` that has a length as its own [`Shape::LineSegment`], as /// [`Shape::dashed_line`] draws a dash. fn segments(line: &[Pos2], s: Stroke, out: &mut Vec) { @@ -562,11 +598,12 @@ pub(super) fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t: } Overlay::Line { a, b, color, dashed } => { let s = Stroke::new(1.0, c32(*color)); - let (a, b) = (xf.to_screen(*a), xf.to_screen(*b)); if *dashed { - p.extend(Shape::dashed_line(&[a, b], s, 4.0, 3.0)); + let mut dashes = vec![]; + dashed_line_in(p.clip_rect(), xf.affine() * *a, xf.affine() * *b, s, &mut dashes); + p.extend(dashes); } else { - p.line_segment([a, b], s); + p.line_segment([xf.to_screen(*a), xf.to_screen(*b)], s); } } Overlay::Anchor { p: pt, color, filled, size } => anchor_square(p, xf.to_screen(*pt), c32(*color), *filled, *size), diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..c040e31d35 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -211,6 +211,70 @@ fn a_line_dashed_in_pieces_dashes_as_the_whole_line_does() { } } +/// A dashed [`Overlay::Line`] much longer than the canvas draws only the dashes on the canvas, +/// where the whole line dashed in one go has them, and a line off the canvas or with an end at +/// infinity draws none. +#[test] +fn a_long_dashed_overlay_line_draws_only_the_dashes_on_the_canvas() { + let s = Stroke::new(1.0, Color32::WHITE); + let clip = egui::Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + // The stretches of x the dashes cover inside `lo..hi`, each dash as one stretch. + let spans = |shapes: &[Shape], lo: f32, hi: f32| -> Vec<(f32, f32)> { + let mut out: Vec<(f32, f32)> = shapes + .iter() + .map(|s| match s { + Shape::LineSegment { points: [a, b], .. } => (a.x.min(b.x).max(lo), a.x.max(b.x).min(hi)), + other => panic!("{other:?}"), + }) + .filter(|(a, b)| b > a) + .collect(); + out.sort_by(|a, b| a.0.total_cmp(&b.0)); + out + }; + // A line from 1,000 px left of the canvas to 1,500 px right of it, along y = 150. + let (a, b) = (pos2(-1000.0, 150.0), pos2(1900.0, 150.0)); + let mut drawn = vec![]; + overlays::dashed_line_in(clip, Point::new(-1000.0, 150.0), Point::new(1900.0, 150.0), s, &mut drawn); + let (lo, hi) = (clip.left() - 1.0, clip.right() + 1.0); + let (want, got) = (spans(&Shape::dashed_line(&[a, b], s, 4.0, 3.0), lo, hi), spans(&drawn, lo, hi)); + assert_eq!(want.len(), got.len(), "{want:?} {got:?}"); + assert!(want.iter().zip(&got).all(|(w, g)| (w.0 - g.0).abs() < 1e-2 && (w.1 - g.1).abs() < 1e-2), "{want:?} {got:?}"); + assert!(drawn.len() <= 60, "only the dashes on the canvas: {}", drawn.len()); + // Ends 10,000,000,000 px away on both sides still keep the part on the canvas. + let mut far = vec![]; + overlays::dashed_line_in(clip, Point::new(-1e10, 150.0), Point::new(1e10, 150.0), s, &mut far); + let far = spans(&far, lo, hi); + assert!(far.len() >= 50 && far.len() <= 60, "{far:?}"); + assert!(far.iter().all(|(a, b)| b - a <= 4.0 + 1e-3), "{far:?}"); + // Drawn through the overlays at a view where the line is 2,000,000 px long. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, crate::theme::Brightness::MediumDark); + let prefs = vectorcraft_engine::Prefs::default(); + let segments = |line: Overlay| { + let raw = egui::RawInput { screen_rect: Some(clip), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + let t = Tokens::get(ui.ctx()); + let xf = Xf { rect: ui.max_rect(), zoom: 1.0, center: Point::new(200.0, 150.0), rot: 0.3 }; + overlays::draw_overlays( + ui.painter(), + &xf, + std::slice::from_ref(&line), + &t, + overlays::HandleLook::of(&prefs), + &mut overlays::SharedPaths::default(), + ); + }); + out.textures_delta.clear(); + out.shapes.iter().filter(|c| matches!(c.shape, Shape::LineSegment { .. })).count() + }; + let line = |a: Point, b: Point| Overlay::Line { a, b, color: [0xff, 0, 0], dashed: true }; + let n = segments(line(Point::new(-1e6, 150.0), Point::new(1e6, 150.0))); + assert!(n > 0 && n <= 80, "{n} dashes"); + assert_eq!(segments(line(Point::new(-1e6, 5000.0), Point::new(1e6, 5000.0))), 0, "a line off the canvas"); + assert_eq!(segments(line(Point::new(0.0, 150.0), Point::new(f64::INFINITY, 150.0))), 0, "an end at infinity"); +} + #[test] fn subpixel_dock_layout_does_not_change_pointer_document_coordinates() { let mut observed = Vec::new(); From f2d3b09fe6d3b72462869437741ac72b40a54c7d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 05:06:52 -0800 Subject: [PATCH 017/101] Scripts: app, documents, selection and page items for scripts Scripts get an app object with its documents, the active document and its selection, and the page items of a document, read and edited through commands so each edit is one undo step and is journaled. Host classes in the JavaScript engine give each document or item one object while a script holds it, answer `in` and indexed reads, and throw on stale objects and on members that are not available yet. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 1745 +++++++++++++++++++++++++ crates/engine/src/script/mod.rs | 28 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dom.rs | 681 ++++++++++ crates/engine/src/tests/script_run.rs | 5 +- crates/js/src/builtins.rs | 2 +- crates/js/src/heap.rs | 4 +- crates/js/src/host.rs | 45 +- crates/js/src/host_classes.rs | 259 ++++ crates/js/src/interp.rs | 41 +- crates/js/src/lib.rs | 2 + crates/js/src/realm.rs | 11 + docs/mcp.md | 51 + docs/target-app-parity.md | 1 + 14 files changed, 2860 insertions(+), 16 deletions(-) create mode 100644 crates/engine/src/script/dom.rs create mode 100644 crates/engine/src/tests/script_dom.rs create mode 100644 crates/js/src/host_classes.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs new file mode 100644 index 0000000000..5763591ec7 --- /dev/null +++ b/crates/engine/src/script/dom.rs @@ -0,0 +1,1745 @@ +//! The script object model: the global `app`, the open documents, their selection and the art in +//! them, as the help pages , +//! , +//! , +//! and +//! describe them. +//! +//! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the +//! document's [`crate::DocState::uid`] and, for art, the object's id, and every read looks the +//! document and the object up again. An object that was deleted, a document that was closed and an +//! object from an earlier run of a named engine throw an error on every member. Every change runs +//! a command, as `vc.run` does, so it joins the run's transaction and its one undo step for each +//! changed document; a change that changes nothing runs no command. A change to a document that is +//! not the active one makes it active for the command and makes the other one active again after. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - Collections list documents in tab order and art in paint order (bottom first), counted from 0. +//! `pageItems` lists every object, with the objects inside groups and compound paths after the +//! group or compound path, and leaves out layers and ruler guides. An index out of range gives +//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches. +//! - Script coordinates are points with Y up from the bottom of the first artboard +//! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of +//! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run. +//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`. +//! - `app.activeDocument` with no document open throws `No active document`. +//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object +//! must be one of that document's that can be selected, or nothing changes. +//! - Members the help pages list that are not here yet throw an error that says so. + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; + +use super::{Host, Link, command, current, data_size}; +use crate::{DocState, Document, NodeId, NodeKind, Session}; + +/// The error for a member read or called with no document open. +pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; +/// The error for an object that was deleted, or that came from an earlier run. +pub const STALE_ITEM: &str = "Stale page item"; +/// The error for a document that was closed, or that came from an earlier run. +pub const STALE_DOCUMENT: &str = "Stale document"; +/// The error of `index` and `getByName` when nothing matches. +pub const NOT_FOUND: &str = "Not found"; +/// The most objects one read of a selection gives, and the most a selection assignment takes. +pub const MAX_LISTED: usize = 10_000; +/// The longest name an object or a path query may have, in bytes. +pub const MAX_TEXT_BYTES: usize = 4096; +/// The most artboards `Documents.add` makes. +pub const MAX_ARTBOARDS: f64 = 100.0; +/// The largest width or height `Documents.add` takes, in points, as `file.new` takes them. +pub const MAX_SIZE: f64 = 3_999_856.0; + +/// The page item classes, with the typename of each kind of object ([`typename`]). +const ITEM_CLASSES: &[&str] = &[ + "PathItem", + "CompoundPathItem", + "GroupItem", + "GraphItem", + "TextFrame", + "PlacedItem", + "RasterItem", + "SymbolItem", + "MeshItem", + "BlendItem", + "EnvelopeItem", + "RepeatItem", + "PlacedDocumentItem", + "IntertwineItem", +]; + +/// `app.coordinateSystem`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum Coords { + #[default] + Document, + Artboard, +} + +const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; +const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; + +/// What the object model keeps for one run: its coordinate system and the last list of a +/// document's page items, kept while that document is unchanged. +#[derive(Default)] +pub(super) struct State { + coords: Cell, + items: RefCell>, +} + +/// A document's uid, the document as it was, and the ids of its page items then. +type ItemList = (u64, Arc, Rc>); + +type Answer = std::result::Result; + +/// A member function: the run's host and the call's arguments, `this` first. +type Member = fn(&Host, &[Data]) -> Answer; + +fn function(link: &Link, f: Member) -> HostFunction { + let l = link.clone(); + Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16 + a.iter().map(data_size).sum::())?; + f(&h, &a) + }) +} + +fn get(link: &Link, f: Member) -> HostMember { + HostMember::Get(function(link, f)) +} + +fn property(link: &Link, g: Member, s: Member) -> HostMember { + HostMember::Property { get: function(link, g), set: function(link, s) } +} + +fn method(link: &Link, f: Member) -> HostMember { + HostMember::Method(function(link, f)) +} + +/// A member the help pages list that is not available yet: reading or assigning it throws, after +/// the check that a document or page item `this` is still there. +fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { + let message = format!("{class}.{name} is not available yet"); + let l = link.clone(); + let f: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + match class { + "Document" => { + doc_of(&h, arg(&a, 0), "Document")?; + } + "PageItem" => { + item_of(&h, arg(&a, 0))?; + } + _ => {} + } + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Property { get: f.clone(), set: f }) +} + +fn text(s: impl Into) -> Data { + Data::String(s.into()) +} + +fn num(n: f64) -> Data { + Data::Number(n) +} + +fn pair(p: [f64; 2]) -> Data { + Data::Array(vec![num(p[0]), num(p[1])]) +} + +fn arg(a: &[Data], i: usize) -> &Data { + a.get(i).unwrap_or(&Data::Undefined) +} + +/// A whole number from a handle or an argument, within 0 and 2^53. +#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] +fn whole(n: f64) -> Option { + (n.is_finite() && n.fract() == 0.0 && (0.0..=9_007_199_254_740_992.0).contains(&n)).then_some(n as u64) +} + +#[allow(clippy::cast_precision_loss)] +fn float(n: u64) -> f64 { + n as f64 +} + +/// A node id in a handle: its high and low 32 bits, each exact as a number. +fn id_parts(id: NodeId) -> [f64; 2] { + [float(id.0 >> 32), float(id.0 & 0xffff_ffff)] +} + +/// The node id [`id_parts`] gave as `high` and `low`. +fn id_of(high: f64, low: f64) -> Option { + let (high, low) = (whole(high)?, whole(low)?); + (high <= 0xffff_ffff && low <= 0xffff_ffff).then_some(NodeId((high << 32) | low)) +} + +/// A finite number argument, or a `TypeError` naming `what`. +fn number(d: &Data, what: &str) -> std::result::Result { + match d { + Data::Number(n) if n.is_finite() => Ok(*n), + _ => Err(HostError::Type(format!("{what} must be a finite number"))), + } +} + +/// A coordinate argument: a finite number within the canvas. +fn coordinate(d: &Data, what: &str) -> std::result::Result { + let n = number(d, what)?; + if n.abs() > crate::MAX_COORD * 2.0 { + return Err(HostError::Range(format!("{what} is outside the canvas"))); + } + Ok(n) +} + +/// A point argument `[x, y]`. +fn point(d: &Data, what: &str) -> std::result::Result<[f64; 2], HostError> { + match d { + Data::Array(a) if a.len() == 2 => Ok([coordinate(&a[0], what)?, coordinate(&a[1], what)?]), + _ => Err(HostError::Type(format!("{what} must be an array of two numbers"))), + } +} + +fn boolean(d: &Data, what: &str) -> std::result::Result { + match d { + Data::Bool(b) => Ok(*b), + _ => Err(HostError::Type(format!("{what} must be true or false"))), + } +} + +/// The handle of `d` when it is an object of `class` (or of a page item class, for `"PageItem"`). +fn handle_of(d: &Data, class: &str) -> Option> { + let (c, handle) = host_ref_parts(d)?; + let matches = if class == "PageItem" { ITEM_CLASSES.contains(&c) } else { c == class }; + matches.then_some(handle) +} + +/// A document an object of the model names: its index among the open documents and its uid. +#[derive(Clone, Copy)] +struct Doc { + index: usize, + uid: u64, +} + +/// A page item: its document and its id. +#[derive(Clone, Copy)] +struct Item { + doc: Doc, + id: NodeId, +} + +/// The open document with `uid`, when the run's number in a handle is this run's. +fn find_doc(h: &Host, run: f64, uid: f64) -> Option { + if whole(run) != Some(h.run) { + return None; + } + let uid = whole(uid)?; + let s = h.session.borrow(); + s.documents().iter().position(|d| d.uid == uid).map(|index| Doc { index, uid }) +} + +/// The document `d` names: a `Document` or a `PageItems` object. +fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result { + let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) }; + match handle.as_slice() { + [run, uid] => find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into())), + _ => Err(HostError::Type(format!("this is not a {class}"))), + } +} + +/// The page item `d` names, which must still be in its document. +fn item_of(h: &Host, d: &Data) -> std::result::Result { + let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let s = h.session.borrow(); + let st = &s.documents()[doc.index]; + if st.doc.node(id).is_none_or(|n| typename(n).is_none()) { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok(Item { doc, id }) +} + +/// The typename of a node, or `None` for one that is not a page item (a layer or a ruler guide). +fn typename(n: &crate::doc::Node) -> Option<&'static str> { + Some(match &n.kind { + NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => return None, + NodeKind::Group { .. } if n.extras().graph.is_some() => "GraphItem", + NodeKind::Group { .. } => "GroupItem", + NodeKind::Path { .. } => "PathItem", + NodeKind::Compound { .. } => "CompoundPathItem", + NodeKind::Text(_) => "TextFrame", + NodeKind::Image(image) if image.link.is_some() => "PlacedItem", + NodeKind::Image(_) => "RasterItem", + NodeKind::SymbolInstance { .. } => "SymbolItem", + NodeKind::Mesh(_) => "MeshItem", + NodeKind::Blend { .. } => "BlendItem", + NodeKind::Envelope { .. } => "EnvelopeItem", + NodeKind::Repeat(_) => "RepeatItem", + NodeKind::PlacedDocument(_) => "PlacedDocumentItem", + NodeKind::Intertwine { .. } => "IntertwineItem", + }) +} + +fn doc_ref(h: &Host, uid: u64) -> Data { + host_ref("Document", &[float(h.run), float(uid)]) +} + +fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { + match st.doc.node(id) { + Some(n) => match typename(n) { + Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + }, + None => Data::Null, + } +} + +/// The ids of a document's page items in paint order ([`State`] keeps the last list). +fn page_items(h: &Host, st: &DocState) -> Rc> { + if let Some((uid, doc, ids)) = &*h.dom.items.borrow() + && *uid == st.uid + && Arc::ptr_eq(doc, &st.doc) + { + return ids.clone(); + } + fn walk(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + match &n.kind { + NodeKind::Layer { children, .. } => walk(children, out), + NodeKind::RulerGuide { .. } => {} + NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { + out.push(n.id); + walk(children, out); + } + _ => out.push(n.id), + } + } + } + let mut ids = Vec::new(); + walk(&st.doc.layers, &mut ids); + let ids = Rc::new(ids); + *h.dom.items.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); + ids +} + +/// The objects directly in the layers and sublayers of a document: what deleting every page item +/// deletes. +fn top_items(d: &Document) -> Vec { + fn walk(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + match &n.kind { + NodeKind::Layer { children, .. } => walk(children, out), + NodeKind::RulerGuide { .. } => {} + _ => out.push(n.id), + } + } + } + let mut out = Vec::new(); + walk(&d.layers, &mut out); + out +} + +/// Whether `n` and every object inside it are shown and unlocked. +fn all_editable(n: &crate::doc::Node) -> bool { + n.visible && !n.locked && n.children().is_none_or(|c| c.iter().all(|c| all_editable(c))) +} + +/// Whether the object and every layer and group it is in are shown and unlocked. +fn editable(d: &Document, id: NodeId) -> bool { + d.ancestry(id).is_some_and(|a| a.iter().chain(std::iter::once(&id)).all(|i| d.node(*i).is_some_and(|n| n.visible && !n.locked))) +} + +/// The two rectangles script coordinates are measured from. +struct Frame { + /// The first artboard's left edge and bottom edge. + left0: f64, + bottom0: f64, + /// The active artboard's left edge and top edge. + left: f64, + top: f64, +} + +/// The index of the active artboard of `st`, as the view keeps it. +fn active_artboard(st: &DocState) -> usize { + let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id); + st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0) +} + +fn frame(st: &DocState) -> std::result::Result { + let (Some(first), Some(active)) = (st.doc.artboards.first(), st.doc.artboards.get(active_artboard(st))) else { + return Err(HostError::Error("the document has no artboards".into())); + }; + Ok(Frame { left0: first.rect.x0, bottom0: first.rect.y1, left: active.rect.x0, top: active.rect.y0 }) +} + +impl Frame { + /// A point in document coordinates as the script sees it in `c`. + fn to_script(&self, c: Coords, p: Point) -> [f64; 2] { + match c { + Coords::Document => [p.x - self.left0, self.bottom0 - p.y], + Coords::Artboard => [p.x - self.left, p.y - self.top], + } + } + + /// A point the script gave in `c`, in document coordinates. + fn to_document(&self, c: Coords, p: [f64; 2]) -> Point { + match c { + Coords::Document => Point::new(p[0] + self.left0, self.bottom0 - p[1]), + Coords::Artboard => Point::new(p[0] + self.left, p[1] + self.top), + } + } + + /// `[left, top, right, bottom]` of `r` as the script sees it. + fn bounds(&self, c: Coords, r: Rect) -> Data { + let a = self.to_script(c, Point::new(r.x0, r.y0)); + let b = self.to_script(c, Point::new(r.x1, r.y1)); + Data::Array(vec![num(a[0]), num(a[1]), num(b[0]), num(b[1])]) + } +} + +fn coords_of(d: &Data) -> std::result::Result { + match d { + Data::String(s) if s == DOCUMENT_COORDS => Ok(Coords::Document), + Data::String(s) if s == ARTBOARD_COORDS => Ok(Coords::Artboard), + _ => Err(HostError::Type("give a CoordinateSystem value".into())), + } +} + +/// Selects `before` again in the active document `doc` with the selection commands, so that the +/// journal holds the change: the whole objects, then the direct-selected anchors and segments, the +/// ruler guides and the key object, guide or anchor. Objects that are now deleted, hidden or +/// locked are left out. +fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -> std::result::Result<(), HostError> { + // Slices selected with the Slice Selection tool are the whole selection when there are any. + let slices: Vec = before.slices.iter().filter(|i| doc.is_slice(**i)).map(|i| i.0).collect(); + if !slices.is_empty() { + command(h, "object.slice.select", &json!({"slices": slices}))?; + return Ok(()); + } + let keep = |id: &NodeId| editable(doc, *id); + let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id); + let whole: Vec = before.objects.iter().filter(|i| keep(i) && !partial(i)).map(|i| i.0).collect(); + if whole.is_empty() { + command(h, "select.none", &json!({}))?; + } else { + command(h, "select.set", &json!({"ids": whole}))?; + } + let items: Vec = before + .anchors + .iter() + .filter(|(i, _)| keep(i)) + .map(|(i, a)| json!({"id": i.0, "anchors": a.iter().map(|(p, k)| [p, k]).collect::>()})) + .collect(); + if !items.is_empty() { + command(h, "select.anchorsMany", &json!({"items": items, "mode": "add"}))?; + } + for (i, segments) in before.segments.iter().filter(|(i, _)| keep(i)) { + let segments: Vec<[usize; 2]> = segments.iter().map(|(p, k)| [*p, *k]).collect(); + command(h, "select.segments", &json!({"id": i.0, "segments": segments, "mode": "add"}))?; + } + let guides: Vec = doc.ruler_guides().into_iter().filter_map(|g| g.id).collect(); + let index = |id: &NodeId| guides.iter().position(|g| g == id); + let picked: Vec = before.guides.iter().filter_map(index).collect(); + // Guides that are locked now, and a key that no longer qualifies (the objects beside it are + // gone), stay unselected: those commands refuse them and change nothing. + if !picked.is_empty() { + let _ = command(h, "guide.select", &json!({"indexes": picked, "toggle": true})); + } + let key = if let Some((id, (p, k))) = before.key_anchor.filter(|(id, _)| keep(id)) { + Some(json!({"id": id.0, "anchor": [p, k]})) + } else if let Some(id) = before.key.filter(keep) { + Some(json!({"id": id.0})) + } else { + before.key_guide.as_ref().and_then(index).map(|g| json!({"guide": g})) + }; + if let Some(key) = key { + let _ = command(h, "select.key", &key); + } + Ok(()) +} + +/// Runs `f` with the document `uid` active, and makes the document that was active before active +/// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s +/// commands changed it (commands given ids select them first), direct-selected anchors, segments, +/// ruler guides, slices and the key included, less the objects that are now deleted, hidden or +/// locked. +fn on_doc( + h: &Host, + uid: u64, + keep_selection: bool, + f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + let (index, active, before) = { + let s = h.session.borrow(); + let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + (index, s.active_index(), s.documents()[index].selection.clone()) + }; + let switch = active != Some(index); + if switch { + command(h, "document.activate", &json!({"index": index}))?; + } + let r = f(h); + if keep_selection { + let doc = { + let s = h.session.borrow(); + s.active().filter(|st| st.uid == uid && st.selection != before).map(|st| st.doc.clone()) + }; + if let Some(doc) = doc { + let back = restore_selection(h, &doc, &before); + if r.is_ok() { + back?; + } + } + } + if switch && let Some(a) = active { + let back = command(h, "document.activate", &json!({"index": a})); + if r.is_ok() { + back?; + } + } + r +} + +/// Runs `id` with `params` on the item's document, its selection kept. +fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { + on_doc(h, item.doc.uid, true, |h| command(h, id, params)) +} + +/// Reads the document of `doc` with `f`. +fn with_doc(h: &Host, doc: Doc, f: impl FnOnce(&Session, &DocState) -> T) -> T { + let s = h.session.borrow(); + f(&s, &s.documents()[doc.index]) +} + +// ---- Application ---- + +fn app_documents(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Documents", &[])) +} + +fn app_active(h: &Host, _: &[Data]) -> Answer { + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) +} + +fn app_set_active(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 1), "Document")?; + if h.session.borrow().active_index() != Some(doc.index) { + command(h, "document.activate", &json!({"index": doc.index}))?; + } + Ok(Data::Undefined) +} + +fn app_selection(h: &Host, _: &[Data]) -> Answer { + let uid = h.session.borrow().active().map(|st| st.uid); + match uid { + Some(uid) => selection_of(h, uid), + None => Ok(Data::Null), + } +} + +fn app_coords(h: &Host, _: &[Data]) -> Answer { + Ok(text(if h.dom.coords.get() == Coords::Document { DOCUMENT_COORDS } else { ARTBOARD_COORDS })) +} + +fn app_set_coords(h: &Host, a: &[Data]) -> Answer { + h.dom.coords.set(coords_of(arg(a, 1))?); + Ok(Data::Undefined) +} + +/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter +/// or a `\`) letters in one case. +fn path_key(p: &str) -> String { + let windows = p.contains('\\') || p.as_bytes().get(1) == Some(&b':'); + let p = p.replace('\\', "/"); + let p = p.trim_end_matches('/').to_string(); + if windows { p.to_lowercase() } else { p } +} + +/// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is +/// compared as text with the documents' files and is not resolved; a document whose file the +/// automation read roots do not allow does not count, and that check can look the file up on disk. +fn app_is_open(h: &Host, a: &[Data]) -> Answer { + let Data::String(path) = arg(a, 1) else { return Err(HostError::Type("getIsFileOpen needs a path, as a string".into())) }; + if path.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the path is too long".into())); + } + let unc = path.starts_with("\\\\") || path.starts_with("//"); + if path.is_empty() || path.contains('\0') || unc || path.split(['/', '\\']).any(|c| c == "..") { + return Err(HostError::Error("getIsFileOpen cannot check that path".into())); + } + let key = path_key(path); + let s = h.session.borrow(); + let open = s.documents().iter().filter_map(|d| d.path.as_deref()).any(|p| path_key(p) == key && crate::file_access::check_read(p).is_ok()); + Ok(Data::Bool(open)) +} + +// ---- Documents ---- + +fn docs_length(h: &Host, _: &[Data]) -> Answer { + Ok(num(float(h.session.borrow().documents().len() as u64))) +} + +fn app_ref(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Application", &[])) +} + +fn docs_at(h: &Host, a: &[Data]) -> Answer { + let s = h.session.borrow(); + let at = match arg(a, 1) { + Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)), + _ => None, + }; + Ok(at.map_or(Data::Undefined, |st| doc_ref(h, st.uid))) +} + +fn docs_by_name(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?; + Ok(doc_ref(h, st.uid)) +} + +fn docs_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => docs_by_name(h, a), + Data::Number(_) => match docs_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `file.new`'s `artboardLayout.layout` and whether it runs right to left, for a +/// `DocumentArtboardLayout` value. +fn layout_of(d: &Data) -> std::result::Result<(&'static str, bool), HostError> { + let Data::String(s) = d else { return Err(HostError::Type("artboardLayout must be a DocumentArtboardLayout value".into())) }; + Ok(match s.strip_prefix("DocumentArtboardLayout.").unwrap_or("") { + "GridByRow" => ("gridByRow", false), + "GridByCol" => ("gridByColumn", false), + "Row" => ("row", false), + "Column" => ("column", false), + "RLGridByRow" => ("gridByRow", true), + "RLGridByCol" => ("gridByColumn", true), + "RLRow" => ("row", true), + _ => return Err(HostError::Type("artboardLayout must be a DocumentArtboardLayout value".into())), + }) +} + +/// The settings of a new document a script gives, each `None` when it was left out. +#[derive(Default)] +struct NewDoc<'a> { + color_space: Option<&'a Data>, + width: Option<&'a Data>, + height: Option<&'a Data>, + artboards: Option<&'a Data>, + layout: Option<&'a Data>, + spacing: Option<&'a Data>, + rows_or_cols: Option<&'a Data>, + units: Option<&'a Data>, + title: Option<&'a Data>, + preview: Option<&'a Data>, + resolution: Option<&'a Data>, +} + +/// `d`, unless it is `undefined`. +fn given(d: &Data) -> Option<&Data> { + (!matches!(d, Data::Undefined)).then_some(d) +} + +impl NewDoc<'_> { + /// `file.new`'s params for these settings, checked before anything is made. + fn params(&self) -> std::result::Result, HostError> { + let mut p = serde_json::Map::new(); + if let Some(d) = self.color_space { + let mode = match d { + Data::String(s) if s == "DocumentColorSpace.RGB" => "rgb", + Data::String(s) if s == "DocumentColorSpace.CMYK" => "cmyk", + _ => return Err(HostError::Type("colorSpace must be a DocumentColorSpace value".into())), + }; + p.insert("colorMode".into(), json!(mode)); + } + for (d, key) in [(self.width, "width"), (self.height, "height")] { + if let Some(d) = d { + let v = number(d, key)?; + if v <= 0.0 || v > MAX_SIZE { + return Err(HostError::Range(format!("{key} must be more than 0 and at most 3999856 points"))); + } + p.insert(key.into(), json!(v)); + } + } + let count = match self.artboards { + Some(d) => { + let n = number(d, "numArtBoards")?; + if n.fract() != 0.0 || !(1.0..=MAX_ARTBOARDS).contains(&n) { + return Err(HostError::Range("numArtBoards must be a whole number from 1 to 100".into())); + } + p.insert("artboards".into(), json!(n)); + n + } + None => 1.0, + }; + let mut layout = serde_json::Map::new(); + if let Some(d) = self.layout { + let (name, rtl) = layout_of(d)?; + layout.insert("layout".into(), json!(name)); + layout.insert("rightToLeft".into(), json!(rtl)); + } + if let Some(d) = self.spacing { + let v = number(d, "artboardSpacing")?; + if !(0.0..=MAX_SIZE).contains(&v) { + return Err(HostError::Range("artboardSpacing must be from 0 to 3999856 points".into())); + } + layout.insert("spacing".into(), json!(v)); + } + if let Some(d) = self.rows_or_cols { + let n = number(d, "artboardRowsOrCols")?; + if n.fract() != 0.0 || n < 1.0 || n > count { + return Err(HostError::Range("artboardRowsOrCols must be a whole number from 1 to numArtBoards".into())); + } + // A grid filled by column takes the number of rows; `file.new` takes columns. + let by_column = layout.get("layout").is_some_and(|l| l == "gridByColumn"); + let columns = if by_column { (count / n).ceil() } else { n }; + layout.insert("columns".into(), json!(columns)); + } + if !layout.is_empty() { + p.insert("artboardLayout".into(), Value::Object(layout)); + } + if let Some(d) = self.units { + let units = match d { + Data::String(s) => match s.strip_prefix("RulerUnits.").unwrap_or("") { + u @ ("Points" | "Picas" | "Inches" | "Millimeters" | "Centimeters" | "Pixels") => u, + "Qs" | "Unknown" => return Err(HostError::Range(format!("a new document cannot have the units {s}"))), + _ => return Err(HostError::Type("units must be a RulerUnits value".into())), + }, + _ => return Err(HostError::Type("units must be a RulerUnits value".into())), + }; + p.insert("units".into(), json!(units)); + } + if let Some(d) = self.title { + let Data::String(t) = d else { return Err(HostError::Type("title must be a string".into())) }; + if t.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the title is too long".into())); + } + p.insert("name".into(), json!(t)); + } + if let Some(d) = self.preview { + let mode = match d { + Data::String(s) if s == "DocumentPreviewMode.DefaultPreview" => "default", + Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => "pixel", + Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => "overprint", + _ => return Err(HostError::Type("previewMode must be a DocumentPreviewMode value".into())), + }; + p.insert("previewMode".into(), json!(mode)); + } + if let Some(d) = self.resolution { + let ppi = match d { + Data::String(s) if s == "DocumentRasterResolution.ScreenResolution" => 72, + Data::String(s) if s == "DocumentRasterResolution.MediumResolution" => 150, + Data::String(s) if s == "DocumentRasterResolution.HighResolution" => 300, + _ => return Err(HostError::Type("rasterResolution must be a DocumentRasterResolution value".into())), + }; + p.insert("rasterEffectsPpi".into(), json!(ppi)); + } + Ok(p) + } +} + +/// Runs `file.new` with `p`. → the new document, which is the active one. +fn new_document(h: &Host, p: serde_json::Map) -> Answer { + command(h, "file.new", &Value::Object(p))?; + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) +} + +/// `documents.add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, +/// artboardRowsOrCols?)`: a new document from `file.new`, which becomes the active one. +fn docs_add(h: &Host, a: &[Data]) -> Answer { + let settings = NewDoc { + color_space: given(arg(a, 1)), + width: given(arg(a, 2)), + height: given(arg(a, 3)), + artboards: given(arg(a, 4)), + layout: given(arg(a, 5)), + spacing: given(arg(a, 6)), + rows_or_cols: given(arg(a, 7)), + ..NewDoc::default() + }; + new_document(h, settings.params()?) +} + +/// The error of `addDocument` with `showOptionsDialog` true: a script cannot open the New +/// Document dialog. +pub const DIALOG_UNAVAILABLE: &str = "Dialog unavailable"; + +/// The New Document profile a startup preset names (`None`: no profile), and the color mode the +/// basic presets give. +fn startup_preset(name: &str) -> Option<(Option<&'static str>, Option<&'static str>)> { + let name = name.strip_prefix("DocumentPresetType.").unwrap_or(name); + let squashed: String = name.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); + Some(match squashed.as_str() { + "basiccmyk" => (None, Some("cmyk")), + "basicrgb" => (None, Some("rgb")), + "video" | "film&video" => (Some("Film & Video"), None), + _ => { + let same = |p: &&str| p.chars().filter(|c| !c.is_whitespace()).collect::().eq_ignore_ascii_case(&squashed); + (Some(crate::cmd::newdoc::profile_names().find(same)?), None) + } + }) +} + +/// `documents.addDocument(startupPreset, presetSettings?, showOptionsDialog?)`: a new document from +/// the New Document profile `startupPreset` names, with the settings `presetSettings` gives in +/// place of the profile's. +fn docs_add_document(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("addDocument needs a startup preset's name".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the startup preset's name is too long".into())); + } + let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?; + let settings = match given(arg(a, 2)) { + None | Some(Data::Null) => Vec::new(), + Some(Data::Object(o)) => o.clone(), + Some(_) => return Err(HostError::Type("presetSettings must be a DocumentPreset".into())), + }; + let field = |k: &str| settings.iter().find(|(n, _)| n == k).map(|(_, v)| v).and_then(given); + for k in ["documentBleedLink", "documentBleedOffsetRect", "transparencyGrid"] { + if field(k).is_some_and(|d| !matches!(d, Data::Null)) { + return Err(HostError::Error(format!("DocumentPreset.{k} is not available yet"))); + } + } + let new = NewDoc { + color_space: field("colorMode"), + width: field("width"), + height: field("height"), + artboards: field("numArtboards"), + layout: field("artboardLayout"), + spacing: field("artboardSpacing"), + rows_or_cols: field("artboardRowsOrCols"), + units: field("units"), + title: field("title"), + preview: field("previewMode"), + resolution: field("rasterResolution"), + }; + let mut p = new.params()?; + match given(arg(a, 3)) { + None => {} + Some(Data::Bool(false)) => {} + Some(Data::Bool(true)) => return Err(HostError::Error(DIALOG_UNAVAILABLE.into())), + Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())), + } + // The document starts from the first preset of the profile's category (Print: Letter). + let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next()); + if let Some(first) = first { + p.insert("preset".into(), json!(first.name)); + } + p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n))); + if let Some(m) = mode { + p.entry("colorMode").or_insert_with(|| json!(m)); + } + new_document(h, p) +} + +/// `new DocumentPreset()`: a record of new-document settings with the defaults the help page +/// gives; the other settings are +/// left out. +fn new_preset(_: &[Data]) -> Answer { + let item = |k: &str, v: Data| (k.to_string(), v); + Ok(Data::Object(vec![ + item("typename", text("DocumentPreset")), + item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), + item("artboardRowsOrCols", num(1.0)), + item("artboardSpacing", num(20.0)), + item("height", num(792.0)), + item("numArtboards", num(1.0)), + item("width", num(612.0)), + ])) +} + +// ---- Document ---- + +fn this_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Document") +} + +fn doc_typename(h: &Host, a: &[Data]) -> Answer { + this_doc(h, a)?; + Ok(text("Document")) +} + +fn doc_parent(h: &Host, a: &[Data]) -> Answer { + this_doc(h, a)?; + Ok(host_ref("Application", &[])) +} + +fn doc_name(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(text(with_doc(h, doc, |_, st| st.title()))) +} + +fn doc_size(h: &Host, a: &[Data], width: bool) -> Answer { + let doc = this_doc(h, a)?; + with_doc(h, doc, |_, st| { + let r = st.doc.artboards.first().map(|b| b.rect).ok_or_else(|| HostError::Error("the document has no artboards".into()))?; + Ok(num(if width { r.width() } else { r.height() })) + }) +} + +fn doc_width(h: &Host, a: &[Data]) -> Answer { + doc_size(h, a, true) +} + +fn doc_height(h: &Host, a: &[Data]) -> Answer { + doc_size(h, a, false) +} + +fn doc_units(h: &Host, a: &[Data]) -> Answer { + use crate::doc::Unit; + let doc = this_doc(h, a)?; + let unit = with_doc(h, doc, |_, st| st.doc.units); + Ok(text(match unit { + Unit::Points => "RulerUnits.Points", + Unit::Picas => "RulerUnits.Picas", + Unit::Inches => "RulerUnits.Inches", + Unit::Millimeters => "RulerUnits.Millimeters", + Unit::Centimeters => "RulerUnits.Centimeters", + Unit::Pixels => "RulerUnits.Pixels", + Unit::Q => "RulerUnits.Qs", + _ => "RulerUnits.Unknown", + })) +} + +fn doc_color_space(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let cmyk = with_doc(h, doc, |_, st| st.doc.color_mode == crate::doc::ColorMode::Cmyk); + Ok(text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })) +} + +fn doc_ruler_origin(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + with_doc(h, doc, |_, st| { + let f = frame(st)?; + Ok(pair(f.to_script(Coords::Document, st.doc.ruler_origin_for(active_artboard(st))))) + }) +} + +/// `rulerOrigin = [x, y]`, in document coordinates: `document.setRulerOrigin` for the active +/// artboard. The art stays where it is. +fn doc_set_ruler_origin(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let p = point(arg(a, 1), "rulerOrigin")?; + let (to, now, artboard) = with_doc(h, doc, |_, st| { + let f = frame(st)?; + let artboard = active_artboard(st); + Ok::<_, HostError>((f.to_document(Coords::Document, p), st.doc.ruler_origin_for(artboard), artboard)) + })?; + if to.distance(now) > 1e-9 { + on_doc(h, doc.uid, false, |h| command(h, "document.setRulerOrigin", &json!({"x": to.x, "y": to.y, "artboard": artboard})))?; + } + Ok(Data::Undefined) +} + +/// `convertCoordinate(point, source, destination)`: `point` from one coordinate system of the +/// document to another. Nothing changes. +fn doc_convert(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let p = point(arg(a, 1), "point")?; + let (from, to) = (coords_of(arg(a, 2))?, coords_of(arg(a, 3))?); + with_doc(h, doc, |_, st| { + let f = frame(st)?; + Ok(pair(f.to_script(to, f.to_document(from, p)))) + }) +} + +fn doc_page_items(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("PageItems", &[float(h.run), float(doc.uid)])) +} + +fn doc_selection(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + selection_of(h, doc.uid) +} + +/// The selection of the document `uid`: `null` when nothing is selected, otherwise a new list of +/// the selected objects. +fn selection_of(h: &Host, uid: u64) -> Answer { + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let ids: Vec = st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect(); + if ids.is_empty() { + return Ok(Data::Null); + } + if ids.len() > MAX_LISTED { + return Err(HostError::Range(format!("the selection has more than {MAX_LISTED} objects"))); + } + h.charge_call(16 * ids.len() as u64)?; + Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) +} + +/// The ids an assignment to a document's selection gives: one page item, a list of them, `null` or +/// `[]`. Every one must be an object of that document that can be selected. +fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { + let list: Vec<&Data> = match v { + Data::Null | Data::Undefined => Vec::new(), + Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), + Data::Array(a) => a.iter().collect(), + d => vec![d], + }; + let mut ids: Vec = Vec::with_capacity(list.len()); + for d in list { + let item = item_of(h, d)?; + let ok = item.doc.uid == doc.uid + && with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id)); + if !ok { + let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); + return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + } + if !ids.contains(&item.id) { + ids.push(item.id); + } + } + Ok(ids) +} + +fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let ids = selection_ids(h, doc, arg(a, 1))?; + set_selection(h, doc, ids) +} + +/// Makes `ids` the selection of `doc`, with no command when it already is: the same objects, each +/// selected as a whole, and no ruler guide, slice or key. +fn set_selection(h: &Host, doc: Doc, ids: Vec) -> Answer { + let same = with_doc(h, doc, |_, st| { + let sel = &st.selection; + sel.objects == ids + && sel.anchors.is_empty() + && sel.segments.is_empty() + && sel.guides.is_empty() + && sel.slices.is_empty() + && sel.key.is_none() + && sel.key_guide.is_none() + && sel.key_anchor.is_none() + }); + if same { + return Ok(Data::Undefined); + } + on_doc(h, doc.uid, false, |h| { + if ids.is_empty() { + command(h, "select.none", &json!({})) + } else { + command(h, "select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})) + } + })?; + Ok(Data::Undefined) +} + +// ---- PageItems ---- + +fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "PageItems") +} + +fn items_length(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let n = with_doc(h, doc, |_, st| page_items(h, st).len()); + Ok(num(float(n as u64))) +} + +fn items_typename(h: &Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(text("PageItems")) +} + +fn items_parent(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn items_at(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn items_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = page_items(h, st); + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn items_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => items_by_name(h, a), + Data::Number(_) => match items_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `pageItems.removeAll()`: deletes every object of the document in one command. A hidden or +/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted. +fn items_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let (ids, refused) = with_doc(h, doc, |_, st| { + let ids = top_items(&st.doc); + let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); + let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); + (ids, refused) + }); + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- PageItem ---- + +fn this_item(h: &Host, a: &[Data]) -> std::result::Result { + item_of(h, arg(a, 0)) +} + +/// Reads the item `this` names with `f`, given its document and node. +fn read_item(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Node) -> Answer) -> Answer { + let item = this_item(h, a)?; + with_doc(h, item.doc, |_, st| match st.doc.node(item.id) { + Some(n) => f(st, n), + None => Err(HostError::Error(STALE_ITEM.into())), + }) +} + +fn item_typename(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(typename(n).unwrap_or("PageItem")))) +} + +fn item_parent(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).map_or(Data::Null, |p| item_ref(h, st, p)))) +} + +fn item_name(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(n.name.clone().unwrap_or_default()))) +} + +/// Runs `object.setProps` with `props` for the item, unless `unchanged` says the node has them. +fn set_props(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Node) -> bool, props: Value) -> Answer { + let item = this_item(h, a)?; + let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(unchanged)); + if !same { + let mut p = props; + if let Some(o) = p.as_object_mut() { + o.insert("ids".into(), json!([item.id.0])); + } + edit_item(h, item, "object.setProps", &p)?; + } + Ok(Data::Undefined) +} + +fn item_set_name(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("name must be a string".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name})) +} + +fn note_of(n: &crate::doc::Node) -> &str { + n.extras().attrs.as_deref().map_or("", |a| a.note.as_str()) +} + +fn item_note(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(note_of(n)))) +} + +/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. +fn item_set_note(h: &Host, a: &[Data]) -> Answer { + let Data::String(note) = arg(a, 1) else { return Err(HostError::Type("note must be a string".into())) }; + if note.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the note is too long".into())); + } + let item = this_item(h, a)?; + let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| note_of(n) == note.trim())); + if !same { + edit_item(h, item, "attributes.set", &json!({"ids": [item.id.0], "note": note}))?; + } + Ok(Data::Undefined) +} + +fn item_hidden(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(Data::Bool(!n.visible))) +} + +fn item_set_hidden(h: &Host, a: &[Data]) -> Answer { + let hidden = boolean(arg(a, 1), "hidden")?; + set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden})) +} + +fn item_locked(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(Data::Bool(n.locked))) +} + +fn item_set_locked(h: &Host, a: &[Data]) -> Answer { + let locked = boolean(arg(a, 1), "locked")?; + set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) +} + +fn item_opacity(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4))) +} + +fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "opacity")?; + if !(0.0..=100.0).contains(&v) { + return Err(HostError::Range("opacity must be from 0 to 100".into())); + } + set_props(h, a, |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v})) +} + +fn item_selected(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)))) +} + +fn item_set_selected(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let on = boolean(arg(a, 1), "selected")?; + let mut ids = with_doc(h, item.doc, |_, st| st.selection.objects.clone()); + if ids.contains(&item.id) == on { + return Ok(Data::Undefined); + } + if on { + let mut given = selection_ids(h, item.doc, arg(a, 0))?; + ids.append(&mut given); + } else { + ids.retain(|i| *i != item.id); + } + set_selection(h, item.doc, ids) +} + +/// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the +/// document's [`Frame`]. +fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Rect, Frame), HostError> { + with_doc(h, item.doc, |_, st| { + let r = st.doc.bounds_of(&[item.id], visual).ok_or_else(|| HostError::Error("the object has no bounds".into()))?; + Ok((r, frame(st)?)) + }) +} + +fn bounds(h: &Host, a: &[Data], visual: bool) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, visual)?; + Ok(f.bounds(h.dom.coords.get(), r)) +} + +fn item_geometric(h: &Host, a: &[Data]) -> Answer { + bounds(h, a, false) +} + +fn item_visible(h: &Host, a: &[Data]) -> Answer { + bounds(h, a, true) +} + +fn item_position(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, false)?; + Ok(pair(f.to_script(h.dom.coords.get(), Point::new(r.x0, r.y0)))) +} + +fn item_left(h: &Host, a: &[Data]) -> Answer { + match item_position(h, a)? { + Data::Array(p) => Ok(p.into_iter().next().unwrap_or(Data::Undefined)), + d => Ok(d), + } +} + +fn item_top(h: &Host, a: &[Data]) -> Answer { + match item_position(h, a)? { + Data::Array(p) => Ok(p.into_iter().nth(1).unwrap_or(Data::Undefined)), + d => Ok(d), + } +} + +fn item_width(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(num(item_rect(h, item, false)?.0.width())) +} + +fn item_height(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(num(item_rect(h, item, false)?.0.height())) +} + +/// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one +/// stays). +fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, false)?; + let c = h.dom.coords.get(); + let now = f.to_script(c, Point::new(r.x0, r.y0)); + let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); + let (dx, dy) = (to.x - r.x0, to.y - r.y0); + if dx.abs() > 1e-9 || dy.abs() > 1e-9 { + edit_item(h, item, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?; + } + Ok(Data::Undefined) +} + +fn item_set_position(h: &Host, a: &[Data]) -> Answer { + let p = point(arg(a, 1), "position")?; + move_to(h, a, Some(p[0]), Some(p[1])) +} + +fn item_set_left(h: &Host, a: &[Data]) -> Answer { + let x = coordinate(arg(a, 1), "left")?; + move_to(h, a, Some(x), None) +} + +fn item_set_top(h: &Host, a: &[Data]) -> Answer { + let y = coordinate(arg(a, 1), "top")?; + move_to(h, a, None, Some(y)) +} + +/// Scales the item about its top-left corner to `size` points wide (`width`) or tall. +fn resize(h: &Host, a: &[Data], width: bool) -> Answer { + let what = if width { "width" } else { "height" }; + let size = number(arg(a, 1), what)?; + if size <= 0.0 || size > MAX_SIZE { + return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points"))); + } + let item = this_item(h, a)?; + let (r, _) = item_rect(h, item, false)?; + let now = if width { r.width() } else { r.height() }; + if now <= 0.0 { + return Err(HostError::Error(format!("the object has no {what} to scale"))); + } + if (now - size).abs() < 1e-9 { + return Ok(Data::Undefined); + } + let pct = size / now * 100.0; + let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; + let p = json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}); + edit_item(h, item, "object.scale", &p)?; + Ok(Data::Undefined) +} + +fn item_set_width(h: &Host, a: &[Data]) -> Answer { + resize(h, a, true) +} + +fn item_set_height(h: &Host, a: &[Data]) -> Answer { + resize(h, a, false) +} + +fn item_editable(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)))) +} + +/// The item's place in its parent's stacking order, from 1 at the bottom. +fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let at = with_doc(h, item.doc, |_, st| st.doc.position(item.id).map(|(_, i, _)| i)); + at.map(|i| num(float(i as u64 + 1))).ok_or_else(|| HostError::Error(STALE_ITEM.into())) +} + +fn item_remove(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?; + Ok(Data::Undefined) +} + +/// The error of `move` and `duplicate` given an object of another document. +pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; + +/// An `ElementPlacement` value. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Placement { + /// `INSIDE` and `PLACEATBEGINNING`: on top of the container's contents. + Top, + /// `PLACEATEND`: under the container's contents. + Bottom, + /// `PLACEBEFORE`: directly above the relative object, in its parent. + Above, + /// `PLACEAFTER`: directly below the relative object, in its parent. + Below, +} + +fn placement_of(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(Placement::Top), + Data::String(s) => match s.as_str() { + "ElementPlacement.INSIDE" | "ElementPlacement.PLACEATBEGINNING" => Ok(Placement::Top), + "ElementPlacement.PLACEATEND" => Ok(Placement::Bottom), + "ElementPlacement.PLACEBEFORE" => Ok(Placement::Above), + "ElementPlacement.PLACEAFTER" => Ok(Placement::Below), + _ => Err(HostError::Type("insertionLocation must be an ElementPlacement value".into())), + }, + _ => Err(HostError::Type("insertionLocation must be an ElementPlacement value".into())), + } +} + +/// Where `move` and `duplicate` put an object relative to `target`: the parent it goes into and +/// the target it goes beside, checked against the object `item` before anything changes. +struct Destination { + parent: NodeId, + beside: Option, + how: Placement, +} + +/// The object a relative object of `move` or `duplicate` names: a page item or a layer of the +/// same document as `item`. A copy (`copy`) may go directly above or below `item` itself, as +/// `layer.move` puts copies. +fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result { + let how = placement_of(how)?; + let beside = matches!(how, Placement::Above | Placement::Below); + let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); + let Some(&[run, uid, high, low]) = handle.as_deref() else { + if handle_of(target, "Document").is_some() { + return Err(HostError::Error("a document as the relative object is not available yet".into())); + } + return Err(HostError::Type("the relative object must be a page item or a layer".into())); + }; + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if doc.uid != item.doc.uid { + return Err(HostError::Error(CROSS_DOCUMENT.into())); + } + let target = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + with_doc(h, doc, |_, st| { + let d = &st.doc; + let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let inside = d.ancestry(target).is_some_and(|a| a.iter().any(|i| *i == item.id && *i != target)); + if inside || (target == item.id && !(copy && beside)) { + return Err(HostError::Error("an object cannot go into itself".into())); + } + let (parent, beside) = match how { + Placement::Top | Placement::Bottom => { + if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) { + return Err(HostError::Error(format!("{} cannot hold objects", typename(t).unwrap_or("Layer")))); + } + (target, None) + } + Placement::Above | Placement::Below => { + let parent = d.parent_of(target).ok_or_else(|| HostError::Error("an object cannot go beside a top-level layer".into()))?; + (parent, Some(target)) + } + }; + if !editable(d, parent) { + return Err(HostError::Error("the layer or group is hidden or locked".into())); + } + if !editable(d, item.id) { + let name = d.node(item.id).and_then(typename).unwrap_or("page item"); + return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0))); + } + Ok(Destination { parent, beside, how }) + }) +} + +/// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. +fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { + let index = with_doc(h, doc, |_, st| { + let d = &st.doc; + let from = d.position(id); + let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent))); + let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0; + let at = match (to.how, to.beside) { + (Placement::Top, _) => count, + (Placement::Bottom, _) => 0, + (how, Some(b)) => { + let (_, mut i, _) = d.position(b).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if let Some((Some(p), j, _)) = from + && p == to.parent + && j < i + { + i -= 1; + } + if how == Placement::Above { i + 1 } else { i } + } + (_, None) => count, + }; + Ok::<_, HostError>(if clips { at.max(1) } else { at }) + })?; + let now = with_doc(h, doc, |_, st| st.doc.position(id)); + if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) { + return Ok(()); + } + on_doc(h, doc.uid, true, |h| command(h, "node.move", &json!({"id": id.0, "parent": to.parent.0, "index": index})))?; + Ok(()) +} + +/// `move(relativeObject, insertionLocation?)`: moves the item into or beside `relativeObject`, a +/// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`). +fn item_move(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + if matches!(arg(a, 1), Data::Undefined) { + return Err(HostError::Type("move needs a relative object".into())); + } + let to = destination(h, item, arg(a, 1), arg(a, 2), false)?; + place(h, item.doc, item.id, &to)?; + Ok(arg(a, 0).clone()) +} + +/// `duplicate(relativeObject?, insertionLocation?)`: a copy of the item, directly above it as +/// Edit › Duplicate makes one, or into or beside `relativeObject` as `move` puts it. → the copy. +/// When `node.move` refuses the place, the copy is deleted and the error is thrown. +fn item_duplicate(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let to = match arg(a, 1) { + Data::Undefined => { + if !matches!(arg(a, 2), Data::Undefined) { + return Err(HostError::Type("duplicate needs a relative object for an insertionLocation".into())); + } + None + } + target => Some(destination(h, item, target, arg(a, 2), true)?), + }; + let r = edit_item(h, item, "edit.duplicate", &json!({"ids": [item.id.0]}))?; + let id = match &r { + Data::Object(o) => o.iter().find(|(k, _)| k == "ids").and_then(|(_, v)| match v { + Data::Array(ids) => ids.first().and_then(|d| if let Data::Number(n) = d { whole(*n) } else { None }), + _ => None, + }), + _ => None, + }; + let id = id.ok_or_else(|| HostError::Error("the copy was not made".into()))?; + if let Some(to) = to + && let Err(e) = place(h, item.doc, NodeId(id), &to) + { + edit_item(h, item, "edit.clear", &json!({"ids": [id]}))?; + return Err(e); + } + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, NodeId(id))) +} + +/// `zOrder(method)`: one of the four Object › Arrange commands for the item. +fn item_z_order(h: &Host, a: &[Data]) -> Answer { + let id = match arg(a, 1) { + Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront", + Data::String(s) if s == "ZOrderMethod.BRINGFORWARD" => "object.arrange.bringForward", + Data::String(s) if s == "ZOrderMethod.SENDBACKWARD" => "object.arrange.sendBackward", + Data::String(s) if s == "ZOrderMethod.SENDTOBACK" => "object.arrange.sendToBack", + _ => return Err(HostError::Type("zOrder needs a ZOrderMethod value".into())), + }; + let item = this_item(h, a)?; + let (before, after) = with_doc(h, item.doc, |_, st| { + let at = st.doc.position(item.id); + let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); + (at.map(|(_, i, _)| i), count) + }); + let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) }; + let top = i + 1 >= after; + let unchanged = match id { + "object.arrange.bringToFront" | "object.arrange.bringForward" => top, + _ => i == 0, + }; + if !unchanged { + edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; + } + Ok(Data::Undefined) +} + +fn layer_name(h: &Host, a: &[Data]) -> Answer { + let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); + with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) +} + +fn layer_typename(h: &Host, a: &[Data]) -> Answer { + layer_name(h, a)?; + Ok(text("Layer")) +} + +fn typename_of(name: &'static str) -> HostMember { + HostMember::Get(Rc::new(move |_| Ok(text(name)))) +} + +fn class(name: &str, parent: Option<&str>, members: Vec<(String, HostMember)>, index: Option) -> HostClass { + HostClass { name: name.into(), parent: parent.map(Into::into), members, index, construct: None } +} + +fn named(items: Vec<(&str, HostMember)>) -> Vec<(String, HostMember)> { + items.into_iter().map(|(n, m)| (n.to_string(), m)).collect() +} + +/// The enumerations, as frozen objects whose members are `"Name.MEMBER"` strings. +const ENUMS: &[(&str, &[&str])] = &[ + ("ElementPlacement", &["INSIDE", "PLACEAFTER", "PLACEATBEGINNING", "PLACEATEND", "PLACEBEFORE"]), + ("ZOrderMethod", &["BRINGFORWARD", "SENDBACKWARD", "BRINGTOFRONT", "SENDTOBACK"]), + ("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]), + ("DocumentColorSpace", &["CMYK", "RGB"]), + ("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]), + ("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]), + ("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]), + ("DocumentPreviewMode", &["DefaultPreview", "OverprintPreview", "PixelPreview"]), + ("DocumentRasterResolution", &["ScreenResolution", "HighResolution", "MediumResolution"]), + ( + "DocumentTransparencyGrid", + &[ + "TransparencyGridBlue", + "TransparencyGridDark", + "TransparencyGridGreen", + "TransparencyGridLight", + "TransparencyGridMedium", + "TransparencyGridNone", + "TransparencyGridOrange", + "TransparencyGridPurple", + "TransparencyGridRed", + ], + ), +]; + +/// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` +/// holds. +pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { + for (name, members) in ENUMS { + let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } + let l = link; + let mut application = named(vec![ + ("typename", typename_of("Application")), + ("documents", get(l, app_documents)), + ("activeDocument", property(l, app_active, app_set_active)), + ("selection", get(l, app_selection)), + ("coordinateSystem", property(l, app_coords, app_set_coords)), + ("getIsFileOpen", method(l, app_is_open)), + ]); + application.push(later(l, "Application", "beep")); + let preset = { + let l = link.clone(); + let f: HostFunction = Rc::new(move |a: Vec| { + current(&l)?.charge_call(64)?; + new_preset(&a) + }); + HostClass { name: "DocumentPreset".into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } + }; + let mut classes = vec![ + class("Application", None, application, None), + preset, + class( + "Documents", + None, + named(vec![ + ("typename", typename_of("Documents")), + ("length", get(l, docs_length)), + ("parent", get(l, app_ref)), + ("index", method(l, docs_index)), + ("getByName", method(l, docs_by_name)), + ("add", method(l, docs_add)), + ("addDocument", method(l, docs_add_document)), + ]), + Some(function(l, docs_at)), + ), + ]; + let mut document = named(vec![ + ("typename", get(l, doc_typename)), + ("parent", get(l, doc_parent)), + ("name", get(l, doc_name)), + ("width", get(l, doc_width)), + ("height", get(l, doc_height)), + ("rulerUnits", get(l, doc_units)), + ("documentColorSpace", get(l, doc_color_space)), + ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin)), + ("convertCoordinate", method(l, doc_convert)), + ("pageItems", get(l, doc_page_items)), + ("selection", property(l, doc_selection, doc_set_selection)), + ]); + document.extend( + ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] + .into_iter() + .map(|m| later(l, "Document", m)), + ); + classes.push(class("Document", None, document, None)); + classes.push(class( + "PageItems", + None, + named(vec![ + ("typename", get(l, items_typename)), + ("length", get(l, items_length)), + ("parent", get(l, items_parent)), + ("index", method(l, items_index)), + ("getByName", method(l, items_by_name)), + ("removeAll", method(l, items_remove_all)), + ]), + Some(function(l, items_at)), + )); + let mut page_item = named(vec![ + ("typename", get(l, item_typename)), + ("parent", get(l, item_parent)), + ("name", property(l, item_name, item_set_name)), + ("note", property(l, item_note, item_set_note)), + ("hidden", property(l, item_hidden, item_set_hidden)), + ("locked", property(l, item_locked, item_set_locked)), + ("selected", property(l, item_selected, item_set_selected)), + ("opacity", property(l, item_opacity, item_set_opacity)), + ("position", property(l, item_position, item_set_position)), + ("left", property(l, item_left, item_set_left)), + ("top", property(l, item_top, item_set_top)), + ("width", property(l, item_width, item_set_width)), + ("height", property(l, item_height, item_set_height)), + ("geometricBounds", get(l, item_geometric)), + ("visibleBounds", get(l, item_visible)), + ("controlBounds", get(l, item_visible)), + ("editable", get(l, item_editable)), + ("zOrderPosition", get(l, item_z_order_position)), + ("duplicate", method(l, item_duplicate)), + ("move", method(l, item_move)), + ("remove", method(l, item_remove)), + ("zOrder", method(l, item_z_order)), + ]); + page_item.extend( + [ + "artworkKnockout", + "blendingMode", + "isIsolated", + "layer", + "pixelAligned", + "sliced", + "tags", + "uRL", + "uuid", + "visibilityVariable", + "wrapInside", + "wrapOffset", + "wrapped", + "bringInPerspective", + "resize", + "rotate", + "transform", + "translate", + ] + .into_iter() + .map(|m| later(l, "PageItem", m)), + ); + classes.push(class("PageItem", None, page_item, None)); + classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); + realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..5ec5e2e92b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -51,6 +51,7 @@ pub mod console; pub mod dialogs; pub mod dollar; +pub mod dom; pub mod include; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; @@ -799,6 +800,8 @@ 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 run's state of the script object model (`app`). + dom: dom::State, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -1293,6 +1296,15 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result std::result::Result { + let id = id.to_string(); + let params = params.clone(); let session = host.session.clone(); let started = clock(); let r = { @@ -1564,11 +1576,17 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { /// `e`'s message, with what to do about a failure that comes from a script written for another /// program. A message the script supplied itself ([`RunError::authored`]) is given as it is. fn explained(e: &RunError) -> String { - const HOST_OBJECTS: &[&str] = &["app", "Window", "BridgeTalk", "activeDocument", "documents"]; + const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"]; + const APP_MEMBERS: &[&str] = &["activeDocument", "documents", "selection"]; let message = &e.message; - let names_host_object = - message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); - if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object { + let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next()); + let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f)); + if e.kind == RunErrorKind::Thrown + && !e.authored + && let Some(member) = first.filter(|f| APP_MEMBERS.contains(f)) + { + format!("{message} (use `app.{member}`)") + } else if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object { format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)") } else { message.to_string() @@ -2040,6 +2058,7 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), + dom: dom::State::default(), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { @@ -2076,6 +2095,7 @@ impl Session { .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(()) }) + .and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) .and_then(|()| { let r = realm.start(&expanded.source); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d92bcb7d71..adcaefd59d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -172,6 +172,7 @@ mod scalestrokes; mod script_console; mod script_dialogs; mod script_dollar; +mod script_dom; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs new file mode 100644 index 0000000000..c3eaea7f4f --- /dev/null +++ b/crates/engine/src/tests/script_dom.rs @@ -0,0 +1,681 @@ +//! The script object model: `app`, its documents, their selection and page items. + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// A 400 × 300 pt document with two rectangles. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +#[test] +fn app_documents_track_active_tab_and_new_document() { + let mut s = Session::new(); + assert_eq!(log(&mut s, "vc.log(app.documents.length); vc.log(app.typename);"), vec![json!(0), json!("Application")]); + assert!(failure(&mut s, "app.activeDocument;").contains("No active document")); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let out = log( + &mut s, + "var d = app.documents; vc.log(d.length); vc.log(app.activeDocument.width);\ + app.activeDocument = d[0]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\ + vc.log(d[5] === undefined); vc.log(app.activeDocument instanceof Document);\ + var n = d.add(DocumentColorSpace.CMYK, 50, 60, 2);\ + vc.log(d.length); vc.log(app.activeDocument.name === n.name); vc.log(n.documentColorSpace); vc.log(n.height);\ + vc.log(d.getByName(n.name).width);", + ); + let expected = [json!(2), json!(200), json!(400), json!("Application"), json!(true), json!(true), json!(3), json!(true)]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("DocumentColorSpace.CMYK"), json!(60), json!(50)]); + assert_eq!(s.documents().len(), 3); + assert_eq!(s.active_index(), Some(2)); + assert_eq!(s.documents()[2].doc.artboards.len(), 2); + // A bad argument changes nothing. + assert!(failure(&mut s, "app.documents.add(DocumentColorSpace.RGB, -5);").contains("width")); + assert!(failure(&mut s, "app.documents.add('RGB');").contains("colorSpace")); + assert!(failure(&mut s, "app.documents.add(undefined, 10, 10, 101);").contains("numArtBoards")); + assert!(failure(&mut s, "app.documents.index('none');").contains("Not found")); + assert_eq!(s.documents().len(), 3); +} + +#[test] +fn page_items_are_live_and_typed_for_all_node_kinds() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + rect(&mut s, 200.0, 200.0, 10.0, 10.0); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, t = [];\ + for (var i = 0; i < p.length; i++) t.push(p[i].typename);\ + vc.log(t.join(','));\ + vc.log(p[1].parent.typename); vc.log(p[0].parent.typename); vc.log(p.parent.typename);\ + p[3].remove(); vc.log(p.length); vc.log(p[-1] === undefined && p[1.5] === undefined && p[99] === undefined);\ + vc.log(p[1] instanceof PathItem && p[1] instanceof PageItem);", + ); + assert_eq!( + out, + vec![ + json!("GroupItem,PathItem,PathItem,PathItem,TextFrame"), + json!("GroupItem"), + json!("Layer"), + json!("Document"), + json!(4), + json!(true), + json!(true) + ] + ); +} + +#[test] +fn page_item_geometry_uses_document_coordinates_with_y_up() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0];\ + vc.log(i.geometricBounds); vc.log(i.position); vc.log([i.left, i.top, i.width, i.height]);\ + app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; vc.log(i.position);\ + app.coordinateSystem = CoordinateSystem.DOCUMENTCOORDINATESYSTEM;\ + i.position = [20, 250]; i.width = 60; vc.log(i.geometricBounds);", + ); + assert_eq!(out[0], json!([10, 280, 40, 240])); + assert_eq!(out[1], json!([10, 280])); + assert_eq!(out[2], json!([10, 280, 30, 40])); + assert_eq!(out[3], json!([10, 20])); + assert_eq!(out[4], json!([20, 250, 80, 210])); +} + +#[test] +fn convert_coordinate_pair_is_inverse_and_y_up() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, D = CoordinateSystem.DOCUMENTCOORDINATESYSTEM, A = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;\ + var p = d.convertCoordinate([10, 100], A, D); vc.log(p); vc.log(d.convertCoordinate(p, D, A));\ + vc.log(d.convertCoordinate([3, 4], D, D));", + ); + assert_eq!(out, vec![json!([10, 200]), json!([10, 100]), json!([3, 4])]); + assert!( + failure( + &mut s, + "app.activeDocument.convertCoordinate([1, NaN], CoordinateSystem.DOCUMENTCOORDINATESYSTEM, CoordinateSystem.DOCUMENTCOORDINATESYSTEM);" + ) + .contains("finite") + ); + assert!( + failure(&mut s, "app.activeDocument.convertCoordinate([1, 2], 'x', CoordinateSystem.DOCUMENTCOORDINATESYSTEM);").contains("CoordinateSystem") + ); +} + +#[test] +fn ruler_origin_round_trips_without_moving_art() { + let (mut s, a, _) = doc(); + let art = format!("{:?}", s.active().unwrap().doc.layers); + let out = log(&mut s, "var d = app.activeDocument; vc.log(d.rulerOrigin); d.rulerOrigin = [50, 60]; vc.log(d.rulerOrigin);"); + assert_eq!(out, vec![json!([0, 300]), json!([50, 60])]); + assert_eq!(s.active().unwrap().doc.ruler_origin_for(0), vectorcraft_geom::Point::new(50.0, 240.0)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art); + assert!(s.active().unwrap().doc.node(a).is_some()); + let steps = undo_steps(&s); + log(&mut s, "var d = app.activeDocument; d.rulerOrigin = d.rulerOrigin;"); + assert_eq!(undo_steps(&s), steps, "setting the same origin adds no step"); + assert!(failure(&mut s, "app.activeDocument.rulerOrigin = [1e12, 0];").contains("outside the canvas")); +} + +#[test] +fn page_item_properties_join_one_undo_step() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0];\ + i.name = 'box'; i.opacity = 40; i.locked = true; i.locked = false; i.hidden = true; i.hidden = false;\ + vc.log([i.name, i.opacity, i.locked, i.hidden, i.editable, i.zOrderPosition]);\ + vc.log(app.activeDocument.pageItems.getByName('box').name);", + ); + assert_eq!(out, vec![json!(["box", 40, false, false, true, 1]), json!("box")]); + let st = s.active().unwrap(); + let n = st.doc.node(a).unwrap(); + assert_eq!((n.name.as_deref(), (n.opacity * 100.0).round()), (Some("box"), 40.0)); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + let steps = undo_steps(&s); + log(&mut s, "var i = app.activeDocument.pageItems[0]; i.name = 'box'; i.opacity = 40; i.hidden = false;"); + assert_eq!(undo_steps(&s), steps, "values that change nothing add no step"); + for (source, part) in [ + ("app.activeDocument.pageItems[0].opacity = 101;", "opacity"), + ("app.activeDocument.pageItems[0].hidden = 'yes';", "hidden"), + ("app.activeDocument.pageItems[0].width = 0;", "width"), + ("app.activeDocument.pageItems[0].position = [1];", "position"), + ] { + assert!(failure(&mut s, source).contains(part), "{source}"); + } +} + +#[test] +fn selection_assignment_is_atomic_across_invalid_items() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];"); + assert!(e.contains("Cannot select PathItem"), "{e}"); + assert!(s.active().unwrap().selection.objects.is_empty()); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems; vc.log(d.selection === null);\ + d.selection = [p[1], p[0], p[1]]; vc.log(d.selection.length); vc.log(app.selection[0].selected);\ + p[0].selected = false; vc.log(d.selection.length);\ + d.selection = p[0]; vc.log(d.selection.length);", + ); + assert_eq!(out, vec![json!(true), json!(2), json!(true), json!(1), json!(1)]); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + // An item of another document cannot be selected here. + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let e = failure(&mut s, "app.activeDocument.selection = app.documents[0].pageItems[0];"); + assert!(e.contains("Cannot select"), "{e}"); +} + +#[test] +fn an_inactive_document_changes_without_switching_tabs() { + let (mut s, a, _) = doc(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + log(&mut s, "var d = app.documents[0]; d.pageItems[0].name = 'far'; d.selection = d.pageItems[1];"); + assert_eq!(s.active_index(), Some(1)); + let first = &s.documents()[0]; + assert_eq!(first.doc.node(a).unwrap().name.as_deref(), Some("far")); + assert_eq!(first.selection.objects.len(), 1); +} + +#[test] +fn move_duplicate_and_zorder_obey_parent_order() { + let (mut s, a, b) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, first = p[0];\ + first.zOrder(ZOrderMethod.BRINGTOFRONT); vc.log(first.zOrderPosition);\ + var c = first.duplicate(); vc.log(c.zOrderPosition); vc.log(p.length); vc.log(app.activeDocument.selection.length);\ + c.zOrder(ZOrderMethod.SENDTOBACK); vc.log(c.zOrderPosition);", + ); + assert_eq!(out, vec![json!(2), json!(3), json!(3), json!(1), json!(1)]); + assert_eq!(s.active().unwrap().selection.objects, vec![b], "the selection stays as it was"); + let layer = &s.active().unwrap().doc.layers[0]; + let order: Vec = layer.children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order[1..], [b, a]); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].zOrder('front');").contains("ZOrderMethod")); +} + +/// The ids of the children of the first layer, bottom first. +fn layer_order(s: &Session) -> Vec { + s.active().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn move_and_duplicate_place_by_element_placement() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + // Before puts it directly above the relative object, after directly below. + let r = + log(&mut s, "var p = app.activeDocument.pageItems; var a = p[0], c = p[2]; vc.log(a.move(c, ElementPlacement.PLACEBEFORE) === undefined);"); + assert_eq!(r, vec![json!(false)]); + assert_eq!(layer_order(&s), [b, c, a]); + log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[0], ElementPlacement.PLACEAFTER);"); + assert_eq!(layer_order(&s), [a, b, c]); + // At the end of a container is under its contents, at the beginning on top. + log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[0].parent, ElementPlacement.PLACEATEND);"); + assert_eq!(layer_order(&s), [c, a, b]); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[0].parent, ElementPlacement.PLACEATBEGINNING);"); + assert_eq!(layer_order(&s), [a, b, c]); + assert_eq!(undo_steps(&s), steps + 4, "one step for each run that changed the order"); + // Moving to where it is runs nothing. + let steps = undo_steps(&s); + log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[1], ElementPlacement.PLACEBEFORE);"); + assert_eq!(undo_steps(&s), steps); + // Into a group, and a copy beside an object. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + log(&mut s, "var p = app.activeDocument.pageItems; p[3].move(p[0], ElementPlacement.INSIDE);"); + let inside: Vec = s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(inside, [a, b, c]); + let out = log( + &mut s, + "var g = app.activeDocument.pageItems[0], a = app.activeDocument.pageItems[1];\ + var copy = a.duplicate(g, ElementPlacement.PLACEATEND); vc.log(copy.parent.typename); vc.log(copy.zOrderPosition);", + ); + assert_eq!(out, vec![json!("GroupItem"), json!(1)]); + assert_eq!(s.active().unwrap().doc.node(g).unwrap().children().unwrap().len(), 4); + // Refused moves change nothing. + let before = format!("{:?}", s.active().unwrap().doc.layers); + for (source, part) in [ + ("var g = app.activeDocument.pageItems[0]; g.move(app.activeDocument.pageItems[1], ElementPlacement.INSIDE);", "into itself"), + ("var p = app.activeDocument.pageItems; p[1].move(p[2], ElementPlacement.INSIDE);", "cannot hold objects"), + ("var p = app.activeDocument.pageItems; p[1].move(p[2], 'inside');", "ElementPlacement"), + ("var p = app.activeDocument.pageItems; p[1].move();", "relative object"), + ("var p = app.activeDocument.pageItems; p[1].move(app.activeDocument);", "not available yet"), + ("var p = app.activeDocument.pageItems; p[1].duplicate(undefined, ElementPlacement.INSIDE);", "relative object"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // A locked group takes nothing. + s.execute("object.setProps", &json!({"ids": [g.0], "locked": true})).unwrap(); + rect(&mut s, 0.0, 0.0, 5.0, 5.0); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[p.length - 1].move(p[0], ElementPlacement.INSIDE);"); + assert!(e.contains("hidden or locked"), "{e}"); +} + +#[test] +fn a_copy_goes_beside_its_source() { + let (mut s, a, b) = doc(); + let out = log( + &mut s, + "var a = app.activeDocument.pageItems[0], c = a.duplicate(a, ElementPlacement.PLACEAFTER);\ + vc.log([c.zOrderPosition, a.zOrderPosition]);", + ); + assert_eq!(out, vec![json!([1, 2])]); + let order = layer_order(&s); + assert_eq!(order[1..], [a, b]); + // An object cannot go beside itself, and a copy cannot go into its source. + assert!(failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1], ElementPlacement.PLACEAFTER);").contains("into itself")); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let e = failure(&mut s, "var p = app.activeDocument.pageItems, g = p[1]; g.duplicate(g, ElementPlacement.INSIDE);"); + assert!(e.contains("into itself"), "{e}"); +} + +#[test] +fn a_copy_that_cannot_be_placed_is_deleted() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0); + let b = rect(&mut s, 30.0, 30.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("livePaint.make", &json!({})).unwrap(); + s.execute("text.create", &json!({"x": 200, "y": 200, "text": "Hi"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + // A Live Paint group takes no type, so the copy is refused after it was made. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, n = p.length, g = p[0], t = p[n - 1], m = '';\ + try { t.duplicate(g, ElementPlacement.INSIDE); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.length === n);", + ); + assert!(out[0].as_str().is_some_and(|m| m.contains("Live Paint takes paths")), "{out:?}"); + assert_eq!(out[1], json!(true)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + +#[test] +fn a_grid_by_column_takes_the_number_of_rows() { + let mut s = Session::new(); + for (layout, rows, cols) in [("GridByCol", 2, 3), ("RLGridByCol", 2, 3), ("GridByRow", 3, 2)] { + run(&mut s, &format!("app.documents.add(DocumentColorSpace.RGB, 100, 100, 6, DocumentArtboardLayout.{layout}, 10, 2);")).unwrap(); + let boards = &s.active().unwrap().doc.artboards; + let distinct = |mut v: Vec| { + v.sort_unstable(); + v.dedup(); + v.len() + }; + let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect()); + let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect()); + assert_eq!((tops, lefts), (rows, cols), "{layout}"); + } +} + +#[test] +fn stale_documents_throw_on_every_member() { + let (mut s, _, _) = doc(); + run(&mut s, "#targetengine keep\nvar d = app.activeDocument, p = d.pageItems, l = p[0].parent;").unwrap(); + for (member, message) in + [("d.typename", "Stale document"), ("d.parent", "Stale document"), ("p.typename", "Stale document"), ("l.typename", "Stale")] + { + let e = failure(&mut s, &format!("#targetengine keep\n{member};")); + assert!(e.contains(message), "{member}: {e}"); + } +} + +#[test] +fn hiding_or_locking_a_selected_item_deselects_it() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].hidden = true;"); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + log(&mut s, "app.activeDocument.pageItems[1].locked = true;"); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + +#[test] +fn an_edit_keeps_direct_selected_anchors() { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + let before = s.active().unwrap().selection.clone(); + assert!(!before.anchors.is_empty()); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].duplicate(); p[1].zOrder(ZOrderMethod.SENDTOBACK);"); + assert_eq!(s.active().unwrap().selection.anchors, before.anchors); + assert_eq!(s.active().unwrap().selection.objects, before.objects); + assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); +} + +#[test] +fn an_edit_keeps_the_key_object() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.key), (vec![a, b], Some(b))); +} + +#[test] +fn an_edit_keeps_selected_slices() { + let (mut s, a, _) = doc(); + s.execute("object.slice.make", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.slice.select", &json!({"slices": [a.0]})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.slices.clone(), sel.objects.len()), (vec![a], 0)); +} + +#[test] +fn a_startup_preset_alone_gives_its_first_size() { + let mut s = Session::new(); + for profile in ["Web", "Print", "Mobile"] { + let first = crate::cmd::newdoc::category(&s, profile).unwrap().remove(0); + let out = log(&mut s, &format!("var d = app.documents.addDocument('{profile}'); vc.log([d.width, d.height]);")); + let got = (out[0][0].as_f64(), out[0][1].as_f64()); + assert_eq!(got, (Some(first.width), Some(first.height)), "{profile}"); + } +} + +#[test] +fn page_item_members_not_built_yet_throw_on_read_and_assignment() { + let (mut s, _, _) = doc(); + for source in + ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] + { + assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); + } + assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); + // A deleted item or an earlier run's document is stale first. + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.blendingMode;"); + assert!(e.contains("Stale page item"), "{e}"); + run(&mut s, "#targetengine keep\nvar d = app.activeDocument;").unwrap(); + let e = failure(&mut s, "#targetengine keep\nd.layers;"); + assert!(e.contains("Stale document"), "{e}"); +} + +#[test] +fn assigning_the_same_objects_clears_the_key_and_guides() { + let (mut s, a, b) = doc(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert!(!s.active().unwrap().selection.guides.is_empty()); + log(&mut s, "var d = app.activeDocument; d.selection = [d.pageItems[0], d.pageItems[1]];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.key, sel.guides.len()), (vec![a, b], None, 0)); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + log(&mut s, "app.activeDocument.selection = null;"); + assert!(s.active().unwrap().selection.guides.is_empty()); +} + +#[test] +fn a_page_item_with_a_large_id_keeps_its_id() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + assert_eq!(a.0, big); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.name = 'big'; vc.log(i.name); i.remove();"); + assert_eq!(out, vec![json!("big")]); + assert!(s.active().unwrap().doc.node(a).is_none()); +} + +#[test] +fn only_class_constructors_construct() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var m = [];\ + try { new app.documents.add(); } catch (e) { m.push(e.name); }\ + try { new app.activeDocument.pageItems[0].remove(); } catch (e) { m.push(e.name); }\ + vc.log(m); vc.log(app.documents.length); vc.log(app.activeDocument.pageItems.length);", + ); + assert_eq!(out, vec![json!(["TypeError", "TypeError"]), json!(1), json!(2)]); +} + +#[test] +fn a_document_preset_is_an_instance_of_its_class() { + let mut s = Session::new(); + let out = log(&mut s, "var p = new DocumentPreset(); vc.log(p instanceof DocumentPreset); vc.log(p.typename); vc.log(p.width);"); + assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]); +} + +#[test] +fn the_same_document_or_item_is_the_same_object() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + vc.log([d === app.documents[0], p[0] === p[0], p[0] === d.selection[0], p[0] !== p[1], p === d.pageItems]);", + ); + assert_eq!(out, vec![json!([true, true, true, true, true])]); +} + +#[test] +fn collection_entries_are_found_by_in_and_array_methods() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, d = app.documents;\ + vc.log([0 in p, '1' in p, 2 in p, 0 in d, 1 in d]);\ + vc.log(Array.prototype.map.call(p, function (i) { return i.typename; }).join(','));", + ); + assert_eq!(out, vec![json!([true, true, false, true, false]), json!("PathItem,PathItem")]); +} + +#[test] +fn placement_in_another_document_is_refused() { + let (mut s, _, _) = doc(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + rect(&mut s, 0.0, 0.0, 5.0, 5.0); + let before: Vec = s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect(); + for source in [ + "app.documents[0].pageItems[0].move(app.documents[1].pageItems[0], ElementPlacement.PLACEBEFORE);", + "app.documents[0].pageItems[0].duplicate(app.documents[1].pageItems[0].parent, ElementPlacement.INSIDE);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("Cross-document placement is not available"), "{source}: {e}"); + } + let after: Vec = s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect(); + assert_eq!(after, before); +} + +#[test] +fn note_is_the_attributes_note() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; vc.log(i.note); i.note = 'check bleed'; vc.log(i.note);"); + assert_eq!(out, vec![json!(""), json!("check bleed")]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().extras().attrs.as_ref().unwrap().note, "check bleed"); + assert_eq!(undo_steps(&s), steps + 1); + log(&mut s, "app.activeDocument.pageItems[0].note = 'check bleed';"); + assert_eq!(undo_steps(&s), steps + 1, "the same note adds no step"); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = 5;").contains("note must be a string")); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long")); +} + +#[test] +fn document_preset_applies_only_its_given_fields() { + let mut s = Session::new(); + let out = log( + &mut s, + "var p = new DocumentPreset(); vc.log([p.typename, p.width, p.height, p.numArtboards, p.artboardSpacing, p.artboardLayout]);\ + vc.log(p.colorMode === undefined && p.units === undefined);\ + p.width = 300; p.height = 200; p.numArtboards = 2; p.colorMode = DocumentColorSpace.CMYK; p.title = 'Flyer';\ + p.units = RulerUnits.Millimeters; p.rasterResolution = DocumentRasterResolution.HighResolution;\ + var d = app.documents.addDocument('Print', p); vc.log([d.name, d.width, d.height, d.documentColorSpace, d.rulerUnits]);\ + var e = app.documents.addDocument(DocumentPresetType.BasicRGB); vc.log(e.documentColorSpace);", + ); + assert_eq!(out[0], json!(["DocumentPreset", 612, 792, 1, 20, "DocumentArtboardLayout.GridByRow"])); + assert_eq!(out[1], json!(true)); + assert_eq!(out[2], json!(["Flyer", 300, 200, "DocumentColorSpace.CMYK", "RulerUnits.Millimeters"])); + assert_eq!(out[3], json!("DocumentColorSpace.RGB")); + assert_eq!(s.documents().len(), 2); + assert_eq!(s.documents()[0].doc.artboards.len(), 2); + assert!((s.documents()[0].doc.raster_effects_ppi - 300.0).abs() < 1e-9); + for (source, part) in [ + ("app.documents.addDocument('Nope');", "no startup preset"), + ("var p = new DocumentPreset(); p.numArtboards = 101; app.documents.addDocument('Print', p);", "numArtBoards"), + ("var p = new DocumentPreset(); p.units = RulerUnits.Qs; app.documents.addDocument('Print', p);", "units"), + ( + "var p = new DocumentPreset(); p.transparencyGrid = DocumentTransparencyGrid.TransparencyGridRed; app.documents.addDocument('Print', p);", + "not available yet", + ), + ("app.documents.addDocument('Print', 5);", "DocumentPreset"), + ("app.documents.addDocument(7);", "startup preset"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(s.documents().len(), 2, "a refused preset makes no document"); +} + +#[test] +fn headless_add_document_dialog_fails_without_creating() { + let mut s = Session::new(); + let e = failure(&mut s, "app.documents.addDocument('Print', new DocumentPreset(), true);"); + assert!(e.contains("Dialog unavailable"), "{e}"); + assert!(s.documents().is_empty()); + let out = log(&mut s, "vc.log(app.documents.addDocument('Web', undefined, false).typename);"); + assert_eq!(out, vec![json!("Document")]); + assert_eq!(s.documents().len(), 1); +} + +#[test] +fn wrappers_go_stale_after_delete_and_undo() { + let (mut s, _, _) = doc(); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.name;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var c = app.activeDocument.pageItems[0].duplicate(); vc.run('edit.undo'); c.position;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length); p[0].name;"); + assert!(e.contains("undefined"), "{e}"); + // A named engine keeps its globals, but an object from an earlier run is stale. + run(&mut s, "#targetengine keep\nvar held = app.activeDocument.pageItems[0];").unwrap(); + let e = failure(&mut s, "#targetengine keep\nheld.name;"); + assert!(e.contains("Stale page item"), "{e}"); +} + +#[test] +fn remove_all_refuses_locked_art_before_deleting_anything() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains(&b.0.to_string()), "{e}"); + assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + // A locked object inside an unlocked group stops it too. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains(&g.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(b).is_some()); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + let out = log(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length);"); + assert_eq!(out, vec![json!(0)]); +} + +#[test] +fn get_is_file_open_cannot_probe_outside_script_scope() { + let (mut s, _, _) = doc(); + let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let p = path.to_string_lossy().replace('\\', "\\\\"); + let out = log(&mut s, &format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));")); + assert_eq!(out, vec![json!(true), json!(false)]); + for bad in ["../x.svg", "a/../b.svg", "\\\\\\\\host\\\\share\\\\x.svg", "//host/share/x.svg", "a\\u0000b", ""] { + assert!(failure(&mut s, &format!("app.getIsFileOpen('{bad}');")).contains("cannot check"), "{bad}"); + } + assert!(failure(&mut s, "app.getIsFileOpen(new Array(5000).join('a'));").contains("too long")); + let _ = std::fs::remove_file(path); +} + +#[test] +fn hostile_dom_values_do_not_reenter_or_exceed_limits() { + let (mut s, _, _) = doc(); + let before = s.active().unwrap().selection.objects.clone(); + // A plain object shaped like an object of the model is not one. + let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['PathItem', 0, 1, 1]; app.activeDocument.selection = f;"); + assert!(e.contains("not plain data"), "{e}"); + // A getter in a value is refused before it runs. + let e = failure( + &mut s, + "var hit = 0, v = {}; Object.defineProperty(v, 0, {get: function () { hit++; return 1; }, enumerable: true});\ + try { app.activeDocument.rulerOrigin = v; } catch (e) { vc.log(hit); throw e; }", + ); + assert!(e.contains("rulerOrigin"), "{e}"); + let e = failure(&mut s, "var a = []; for (var i = 0; i < 10001; i++) a.push(app.activeDocument.pageItems[0]); app.activeDocument.selection = a;"); + assert!(e.contains("at most 10000"), "{e}"); + assert_eq!(s.active().unwrap().selection.objects, before); +} + +#[test] +fn prototype_changes_cannot_forge_a_page_item() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var f = Object.create(PathItem.prototype); var m = '';\ + try { f.name = 'x'; } catch (e) { m = e.message; } vc.log(m);\ + try { PathItem.prototype.name = 'y'; } catch (e) { m = e.message; } vc.log(m); PageItem = null; Document.prototype.pageItems = null;\ + vc.log(Object.isFrozen(PathItem.prototype) || !Object.isExtensible(PathItem.prototype));\ + vc.log(app.activeDocument.pageItems.length);\ + try { new PathItem(); } catch (e) { m = e.name; } vc.log(m);", + ); + assert_eq!(out, vec![json!("this is not a page item"), json!("this is not a page item"), json!(true), json!(2), json!("TypeError")]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None); +} + +#[test] +fn unsupported_members_say_so() { + let (mut s, _, _) = doc(); + assert!(failure(&mut s, "app.activeDocument.layers;").contains("Document.layers is not available yet")); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index bf8154f9a7..02176c38c9 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -165,7 +165,8 @@ fn an_error_names_the_script_its_place_and_kind() { assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)"); let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); - assert!(run(&mut s, "app.activeDocument;").unwrap_err().to_string().contains("`vc`")); + assert!(run(&mut s, "new Window('dialog');").unwrap_err().to_string().contains("`vc`")); + assert!(run(&mut s, "activeDocument;").unwrap_err().to_string().contains("`app.activeDocument`")); assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _")); assert_eq!(s.script_report().unwrap()["line"], 1); } @@ -204,7 +205,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}"); } // The app's own reference error names the `vc` object; the same text a script threw does not. - run(&mut s, "app.activeDocument;").unwrap_err(); + run(&mut s, "new Window('dialog');").unwrap_err(); assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`")); assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in"); // An error in code `eval` compiled keeps where its message came from. diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..69c2ebf402 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -176,7 +176,7 @@ fn get_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult { } fn has_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult { - interp.has_property(o, &key_of(k)) + interp.has_property_indexed(o, &key_of(k)) } /// The estimated bytes a new element adds. diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..418a603e1c 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), + /// An object of a class a host defined ([`crate::host_classes`]). + Host(crate::host_classes::HostObj), } /// What an XML value is. @@ -312,7 +314,7 @@ impl Class { Class::XmlFilter(_) => "Object", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary | Class::ForIn(_) => "Object", + Class::Ordinary | Class::ForIn(_) | Class::Host(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4c18d0f76f..312221986c 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -113,6 +113,10 @@ pub(crate) enum ArgRead { Each(Rc<[Arg]>), /// None: the function is given the [`CallSite`] of the code that calls it, as three numbers. Site, + /// A member of a host class ([`crate::host_classes`]): `this` first, then each argument as + /// [`Data`], objects of host classes in them as [`crate::host_ref`] gives them; the objects of + /// host classes in the result are made from theirs. + Hosted, } /// A member of an object the host adds to the global environment. @@ -186,6 +190,9 @@ struct Reading { ancestors: Vec, path: Vec, function: Rc, + /// Objects of host classes are read as [`crate::host_ref`] gives them, and a plain object + /// that has [`crate::HOST_REF_KEY`] is refused. + hosted: bool, } impl Reading { @@ -255,6 +262,10 @@ impl Interp { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } let shape = match &self.object(id)?.class { + Class::Host(_) if r.hosted => { + return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); + } + Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), Class::Ordinary => { let o = self.object(id)?; @@ -302,6 +313,9 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); + if r.hosted && name == crate::HOST_REF_KEY { + return Err(self.data_error(r, ErrorType::Type, "is not plain data")); + } r.path.push(Step::Name(k)); let item = match prop { // A property holding `undefined` reads as one left out. @@ -337,6 +351,9 @@ impl Interp { Data::Array(items) => { self.write_container(items.into_iter().enumerate().map(|(i, d)| (Slot::Index(i), d)).collect(), true, depth, frozen)? } + Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, _)] if k == crate::HOST_REF_KEY) => { + self.write_host_ref(&Data::Object(items))? + } Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?, }) } @@ -376,9 +393,18 @@ impl Interp { /// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to /// the script. - pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult { + pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { let data = match how { ArgRead::Site => site_data(self.call_site()), + ArgRead::Hosted => { + let this = match this { + Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined), + _ => Data::Undefined, + }; + let mut data = vec![this]; + data.extend(self.read_args(name, args, how)?); + data + } _ => self.read_args(name, args, how)?, }; // Only the script's own code, in a run that can pause, can wait for a result. @@ -387,6 +413,7 @@ impl Interp { let result = f(data); self.can_wait.set(false); match result { + Ok(d) if matches!(how, ArgRead::Hosted) => self.write_hosted(d), Ok(d) => self.write_data(d, 0, matches!(how, ArgRead::Frozen)), Err(HostError::Wait) if can_wait => { self.waiting = true; @@ -467,7 +494,15 @@ impl Interp { /// The arguments of host function `name` as [`Data`], read as `how` says. fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult> { - let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() }; + let mut reading = Reading { + limits: self.data_limits, + bytes: 0, + entries: 0, + ancestors: Vec::new(), + path: Vec::new(), + function: name.clone(), + hosted: matches!(how, ArgRead::Hosted), + }; let args = match how { ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), _ => args, @@ -475,14 +510,14 @@ impl Interp { let mut data = Vec::with_capacity(args.len()); // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); - if !matches!(how, ArgRead::Data | ArgRead::Frozen) { + if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) { self.temp_roots.extend(args.iter().cloned()); } let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); let d = match how { - ArgRead::Data | ArgRead::Frozen | ArgRead::Site => self.read_data(a, &mut reading), + ArgRead::Data | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading), ArgRead::Text => self.read_text(a, &mut reading), ArgRead::Each(list) => match list.get(i) { Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), @@ -507,7 +542,7 @@ impl Interp { /// What host error `e` throws, or the limit it ends the run with. A function that waits /// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal /// error. - fn host_error(&mut self, e: HostError) -> JsResult { + pub(crate) fn host_error(&mut self, e: HostError) -> JsResult { match e { HostError::Wait => Ok(Abrupt::Internal("a host function waited for its result where the run cannot pause".into())), HostError::Abort(message) => { diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs new file mode 100644 index 0000000000..1d03f981ff --- /dev/null +++ b/crates/js/src/host_classes.rs @@ -0,0 +1,259 @@ +//! Classes a host defines ([`crate::Realm::define_host_classes`]): objects that stand for something +//! the host keeps, such as an open document or an object in one, with members the host's functions +//! answer. +//! +//! Each object holds the name of its class and a handle, a list of numbers the host chose, in an +//! internal slot that a script cannot read, write or copy onto another object. A host function sees +//! such an object as the [`Data`] that [`host_ref`] makes, and gives one back the same way; a plain +//! object a script made that carries [`HOST_REF_KEY`] is refused, so a script cannot make an object +//! of a host class from its own data. A class's prototype and constructor are frozen. While a +//! script holds the object for a class and handle, each read of that class and handle gives the +//! same object. +//! +//! Every member function gets the object it is called on (`this`) as its first argument, or +//! `undefined` when `this` is not an object of a host class, followed by the call's arguments; a +//! setter gets `this` and the value assigned. A class with an indexer answers `object[i]` for each +//! array index `i` with it, called with `this` and the index, and `i in object` is true when it +//! gives a value other than `undefined`; other names are looked up as usual. + +use std::rc::Rc; + +use crate::heap::{Class, Func, ObjId, Object, Prop, key}; +use crate::host::ArgRead; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::Value; +use crate::{Data, HostError, HostFunction}; + +/// The one key of the [`Data`] object that stands for an object of a host class ([`host_ref`]). +pub const HOST_REF_KEY: &str = "\u{0}hostRef"; + +/// A member of a host class's prototype. +#[derive(Clone)] +pub enum HostMember { + /// A read-only property: the function gives its value each time it is read. + Get(HostFunction), + /// A property the function `get` reads and `set` assigns. + Property { get: HostFunction, set: HostFunction }, + /// A method. + Method(HostFunction), +} + +/// A class [`crate::Realm::define_host_classes`] adds. +#[derive(Clone)] +pub struct HostClass { + pub name: String, + /// A class defined before this one, or in the same call before it, whose prototype this + /// class's prototype inherits from. + pub parent: Option, + pub members: Vec<(String, HostMember)>, + /// What `object[i]` gives for an array index `i`. + pub index: Option, + /// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`. + pub construct: Option, +} + +/// The internal slot of an object of a host class: its class, as an index into the realm's +/// classes, and its handle. +#[derive(Clone, Debug)] +pub(crate) struct HostObj { + pub(crate) class: u32, + pub(crate) handle: Rc<[f64]>, +} + +/// A class the realm has. +#[derive(Clone)] +pub(crate) struct Entry { + name: Rc, + proto: ObjId, + ctor: ObjId, + index: Option, +} + +impl Entry { + pub(crate) fn objects(&self) -> [ObjId; 2] { + [self.proto, self.ctor] + } +} + +/// A class, as an index into the realm's classes, and the bits of a handle. +type MadeKey = (u32, Box<[u64]>); + +/// The object made for each class and handle ([`Interp::host_objects`]). +pub(crate) type Made = std::collections::HashMap; + +/// Whether `id` is still the object made for `key`, and not a freed cell or another object that +/// was given its cell. +fn is_made(heap: &crate::heap::Heap, id: ObjId, key: &MadeKey) -> bool { + heap.object(id).is_some_and(|o| match &o.class { + Class::Host(h) => h.class == key.0 && h.handle.iter().map(|n| n.to_bits()).eq(key.1.iter().copied()), + _ => false, + }) +} + +/// Drops the entries of `made` whose objects the last collection freed. +pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap) { + made.retain(|key, id| is_made(heap, *id, key)); +} + +/// The [`Data`] that stands for the object of host class `class` with `handle`. +pub fn host_ref(class: &str, handle: &[f64]) -> Data { + let mut list = Vec::with_capacity(handle.len() + 1); + list.push(Data::String(class.to_string())); + list.extend(handle.iter().map(|n| Data::Number(*n))); + Data::Object(vec![(HOST_REF_KEY.to_string(), Data::Array(list))]) +} + +/// The class and handle of the object `d` stands for, when it is one [`host_ref`] made. +pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { + let Data::Object(items) = d else { return None }; + let [(k, Data::Array(list))] = items.as_slice() else { return None }; + if k != HOST_REF_KEY { + return None; + } + let (Data::String(class), rest) = list.split_first()? else { return None }; + let handle = rest.iter().map(|d| if let Data::Number(n) = d { Some(*n) } else { None }).collect::>>()?; + Some((class.as_str(), handle)) +} + +impl Interp { + /// The [`Data`] for the object of a host class `id`, or `None` when it is not one. + pub(crate) fn host_ref_of(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + let name = + self.host_classes.get(h.class as usize).map(|e| e.name.clone()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?; + Ok(Some(host_ref(&name, &h.handle))) + } + + /// The object of a host class that `d`, which a host function gave, stands for. + pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult { + let Some((name, handle)) = host_ref_parts(d) else { + return Err(self.throw(ErrorType::Type, "a host value names an object of a host class wrongly")); + }; + let Some((class, entry)) = self.host_classes.iter().enumerate().find(|(_, e)| &*e.name == name) else { + return Err(self.throw(ErrorType::Type, &format!("a host value names the unknown class {name}"))); + }; + let proto = entry.proto; + let class = u32::try_from(class).unwrap_or(u32::MAX); + let made = (class, handle.iter().map(|n| n.to_bits()).collect::>()); + if let Some(&id) = self.host_objects.get(&made) + && is_made(&self.heap, id, &made) + { + return Ok(Value::Object(id)); + } + self.reserve_heap(crate::heap::OBJECT_BYTES)?; + let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); + o.extensible = false; + let id = self.heap.alloc_object(o); + self.host_objects.insert(made, id); + Ok(Value::Object(id)) + } + + /// Whether `id` is the constructor of a host class (its other functions are not constructors). + pub(crate) fn is_host_constructor(&self, id: ObjId) -> bool { + self.host_classes.iter().any(|e| e.ctor == id) + } + + /// The indexer of the host class of `id`, when it is an object of a host class that has one. + pub(crate) fn host_indexer(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + Ok(self.host_classes.get(h.class as usize).and_then(|e| e.index.clone())) + } + + /// `object[index]` of an object of a host class, which its class's indexer `f` answers. + pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, index: u32) -> JsResult { + self.use_fuel()?; + let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) }; + match f(vec![this, Data::Number(f64::from(index))]) { + Ok(d) => self.write_hosted(d), + Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())), + Err(e) => Err(self.host_error(e)?), + } + } + + /// [[HasProperty]] of `k` on `id`: for an array index of an object of a host class with an + /// indexer, whether the indexer gives a value other than `undefined` for it. + pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &[u16]) -> JsResult { + if let Some(i) = crate::value::array_index(k) + && let Some(f) = self.host_indexer(id)? + { + return Ok(!matches!(self.host_index(&f, id, i)?, Value::Undefined)); + } + self.has_property(id, k) + } + + /// `d` as a JavaScript value, the objects of host classes in it made from their [`host_ref`]. + pub(crate) fn write_hosted(&mut self, d: Data) -> JsResult { + let was = std::mem::replace(&mut self.write_hosted, true); + let r = self.write_data(d, 0, false); + self.write_hosted = was; + r + } +} + +/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given. +pub(crate) fn install(i: &mut Interp, classes: Vec, instances: Vec<(String, Data)>) -> JsResult<()> { + for class in classes { + install_class(i, class)?; + } + for (name, d) in instances { + let v = i.write_hosted(d)?; + let global = i.global; + i.define(global, key(&name), Prop::Data { value: v, flags: 0 })?; + } + Ok(()) +} + +fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { + if i.host_classes.iter().any(|e| *e.name == *class.name) { + return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); + } + let parent = match &class.parent { + None => i.intrinsics.object_proto, + Some(p) => match i.host_classes.iter().find(|e| *e.name == **p) { + Some(e) => e.proto, + None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), + }, + }; + let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent))); + let mark = i.temp_roots.len(); + i.temp_roots.push(Value::Object(proto)); + let r = fill_class(i, proto, &class); + i.temp_roots.truncate(mark); + let ctor = r?; + i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index }); + let global = i.global; + i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) +} + +/// Puts the members of `class` on `proto` and makes its constructor. → the constructor. +fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult { + let path = &class.name; + for (name, member) in &class.members { + let full = format!("{path}.{name}"); + let prop = match member { + HostMember::Get(f) => Prop::Accessor { get: Some(hosted_function(i, f.clone(), &full)), set: None, flags: 0 }, + HostMember::Property { get, set } => { + let get = hosted_function(i, get.clone(), &full); + i.temp_roots.push(Value::Object(get)); + Prop::Accessor { get: Some(get), set: Some(hosted_function(i, set.clone(), &full)), flags: 0 } + } + HostMember::Method(f) => Prop::Data { value: Value::Object(hosted_function(i, f.clone(), &full)), flags: 0 }, + }; + i.define(proto, key(name), prop)?; + } + let construct = class.construct.clone().unwrap_or_else(|| { + let message = format!("{path} cannot be constructed by a script"); + Rc::new(move |_| Err(HostError::Type(message.clone()))) + }); + let ctor = hosted_function(i, construct, path); + i.define(ctor, key("prototype"), Prop::Data { value: Value::Object(proto), flags: 0 })?; + i.define(proto, key("constructor"), Prop::Data { value: Value::Object(ctor), flags: 0 })?; + i.object_mut(proto)?.extensible = false; + i.object_mut(ctor)?.extensible = false; + Ok(ctor) +} + +fn hosted_function(i: &mut Interp, f: HostFunction, name: &str) -> ObjId { + let proto = i.intrinsics.function_proto; + i.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read: ArgRead::Hosted }), Some(proto))) +} diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..874116d472 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -253,6 +253,14 @@ 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, + /// The classes a host added ([`crate::Realm::define_host_classes`]), in the order it added them. + pub(crate) host_classes: Vec, + /// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`]. + pub(crate) write_hosted: bool, + /// The object made for each class and handle ([`crate::host_classes`]), so that two reads of + /// the same one give the same object. It is not a root: an entry whose object was collected is + /// dropped after each collection. + pub(crate) host_objects: crate::host_classes::Made, /// 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 +526,9 @@ impl Interp { held_bytes: 0, install_error: None, files: None, + host_classes: Vec::new(), + write_hosted: false, + host_objects: crate::host_classes::Made::default(), date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), flattened: std::cell::Cell::new(0), @@ -774,8 +785,10 @@ 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.host_classes.iter().flat_map(crate::host_classes::Entry::objects)); roots.envs.push(self.global_env); self.heap.collect(&roots); + crate::host_classes::forget_collected(&mut self.host_objects, &self.heap); // The collection counts the live total again, so bytes already released are not in it. self.held.released.set(0); self.flattened.set(0); @@ -1408,6 +1421,12 @@ impl Interp { /// [[Get]] starting at `start`, with `receiver` as `this` for a getter. pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + // An array index of an object of a host class with an indexer is the indexer's answer. + if let Some(i) = array_index(k) + && let Some(f) = self.host_indexer(start)? + { + return self.host_index(&f, start, i); + } match self.find_property(start, k)? { None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Some(Prop::Data { value, .. }) => Ok(value), @@ -2262,7 +2281,7 @@ impl Interp { Func::Data { f, name, read } => { // The arguments are read before the function runs, and a result being built // keeps itself reachable. - return Ok(Prepared::Done(self.call_data(&f, &name, &args, &read)?)); + return Ok(Prepared::Done(self.call_data(&f, &name, &this, &args, &read)?)); } Func::Eval { f, end, strict_writes, name } => { return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?)); @@ -2371,6 +2390,22 @@ impl Interp { self.stack.truncate(start); self.push(v) } + // A host class's constructor ([`crate::host_classes`]) gives the object it makes. A plain + // object it gives inherits from the class's prototype. The class's other functions are + // not constructors. + Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted }) + if f.as_object().is_some_and(|o| self.is_host_constructor(o)) => + { + let v = self.call_data(&host, &name, &Value::Undefined, &args, &read)?; + if let (Some(callee), Value::Object(o)) = (f.as_object(), &v) + && matches!(self.object(*o)?.class, Class::Ordinary) + && let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))? + { + self.object_mut(*o)?.proto = Some(proto); + } + self.stack.truncate(start); + self.push(v) + } _ => Err(self.type_error("the value is not a constructor")), } } @@ -2496,7 +2531,7 @@ impl Interp { self.temp_roots.extend(keep.iter().cloned()); let was_waiting = self.waiting; let answer = match self.func_of(&host) { - Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read), _ => self.call(&host, &Value::Undefined, &args), }; self.temp_roots.truncate(mark); @@ -2933,7 +2968,7 @@ impl Interp { } let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) }; let k = self.to_key(a)?; - self.has_property(*o, &k).map(Value::Bool) + self.has_property_indexed(*o, &k).map(Value::Bool) } } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..1d7af9e4fb 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -58,6 +58,7 @@ mod error; mod file_classes; mod heap; mod host; +mod host_classes; mod interp; mod lexer; mod number; @@ -81,6 +82,7 @@ pub use ast::{ pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; +pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index d675e82ec7..52952eb73e 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -504,6 +504,17 @@ impl Realm { } } + /// Adds the host classes `classes` ([`crate::HostClass`]), each a global constructor whose + /// prototype holds its members, and the global objects `instances`, each made from the + /// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be + /// replaced. A heap too small for them ends with the error the realm's next run would give. + pub fn define_host_classes(&mut self, classes: Vec, instances: Vec<(String, crate::Data)>) -> Result<(), RunError> { + match crate::host_classes::install(&mut self.interp, classes, instances) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Sets `Folder.current` back to the host's `current`, for the next run of a realm that has /// `File` and `Folder` ([`Realm::define_file_classes`]); a realm without them keeps its /// `Folder.current`. The files an earlier run opened are no longer open. The last run's uncaught diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..94d8e728c0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2620,6 +2620,57 @@ app through the global object `vc`, and writes to the Script Console and runs ot throws a `RangeError`. - `vc.commands` lists the commands a script may run. - `vc.log(value)` adds a value to the report and a line to the Script Console. +- `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ + describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), + `app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. `app.documents` + (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` + and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, + which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of + columns for the other layouts), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new` + with the New Document profile `startupPreset` names (`Print`, `Web`, `Mobile`, `Video`, another profile of + `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset + `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` + (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` + starts with the defaults that page gives; `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` + throw an error that says they are not available yet, and `showOptionsDialog` true throws `Dialog unavailable` + with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, + `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, + destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) + has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each + entry `[i]` gives. Each page item + (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/) has `typename`, `parent`, `name`, `note` (the + Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected`, `opacity` (0 to + 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the + visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` + (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs + `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same + document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a + group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` + directly below it. An object of another document throws `Cross-document placement is not available`, and when + `node.move` refuses the place of a copy, `duplicate` deletes the copy and throws that error. The + enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, + `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and + `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. + VectorCraft's own rules: documents are listed in tab order, and page items in paint order from the bottom, with the + objects inside groups and compound paths after their group and without layers and ruler guides. Script coordinates + are points with Y up from the bottom-left corner of the first artboard, or, with + `CoordinateSystem.ARTBOARDCOORDINATESYSTEM`, Y down from the top-left corner of the active artboard. `typename` + is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem` + for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each + changed document. A value that changes nothing runs no command, and a change to another document leaves the active + tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine + kept from an earlier run, throws `Stale page item`; `index` and `getByName` throw `Not found`; and + `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, + a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with + nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, + letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when + the automation read roots allow its file, and that check can look the document's file up on disk. A path with + `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, + Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and + `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members + those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds + themselves, such as a path's fill, are not defined yet and read as `undefined`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..3b252b56a6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,6 +1024,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From f70d2ee7e6bdeb061cbfea3e9bb87d4ef0a99409 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 08:43:10 -0800 Subject: [PATCH 018/101] Scripts: duplicate, selection and wrapper fixes for the object model - duplicate() runs Edit > Duplicate, the place and the selection restore under one savepoint, so a refused place leaves the documents, the selection and the undo history as they were. It reads the copy's id from the command's own result, so ids above 2^53 return the copy. A path inside a compound path throws an error instead of copying the whole compound path. - An edit restores a mixed selection (direct-selected anchors and whole objects) in its original order with one select.anchorsMany. - Assigning the selection clears a Layers panel target. - A call on an inactive document switches back even when the selection restore fails. - documents.add with a grid by column passes the row count to file.new, which takes a new artboardLayout.rows key: 5 artboards in 4 rows give columns of 4 and 1. A preset keeps the rows until columns without rows, or another layout, is given, and New Document drops them when Columns or the layout changes. - A held page item stays the same object when its class changes in the same family (a placed image that is embedded becomes a RasterItem). - A waiting class member's answer is read as a class instance, and a class constructor called with new cannot wait. Docs: docs/mcp.md (DocumentPreset, duplicate, file.new rows), docs/gaps.md (G6). --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/newdoc.rs | 64 +++++++--- crates/engine/src/script/dom.rs | 136 ++++++++++++-------- crates/engine/src/script/mod.rs | 10 +- crates/engine/src/tests/newdoc.rs | 3 +- crates/engine/src/tests/script_dom.rs | 138 +++++++++++++++++++-- crates/js/src/host.rs | 6 +- crates/js/src/host_classes.rs | 44 ++++--- crates/js/src/host_tests.rs | 40 ++++++ crates/js/src/interp.rs | 18 ++- crates/js/src/realm.rs | 9 +- crates/ui-egui/src/dialogs/new_document.rs | 20 +++ docs/gaps.md | 5 +- docs/mcp.md | 17 ++- 14 files changed, 408 insertions(+), 104 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ccebbfac88..bf9ff59c14 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index e74a570a5b..03be423cf3 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "New Document Presets", [], None, - "{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one", + "{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, rows? (a grid by column made with rows), spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one", always, list ), @@ -146,6 +146,11 @@ fn de_ppi<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result bool { + *n == 0 +} + /// Everything New Document sets: a preset (built-in, saved or recent) or `file.new`'s params. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -166,6 +171,9 @@ pub struct DocSettings { pub layout: ArtboardLayout, /// Columns of a grid layout. pub columns: u32, + /// Rows of a grid by column, in place of `columns` when more than 0. + #[serde(skip_serializing_if = "is_zero")] + pub rows: u32, /// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value /// outside that range is read as the nearer end). #[serde(deserialize_with = "de_spacing")] @@ -203,6 +211,7 @@ impl Default for DocSettings { artboards: 1, layout: ArtboardLayout::GridByRow, columns: 0, + rows: 0, spacing: 20.0, right_to_left: false, bleed: [0.0; 4], @@ -222,9 +231,17 @@ pub const MAX_ARTBOARDS: u32 = 1000; pub const RASTER_PPI: [(f64, &str); 3] = [(72.0, "Screen (72 ppi)"), (150.0, "Medium (150 ppi)"), (300.0, "High (300 ppi)")]; impl DocSettings { + /// The rows a grid by column with `rows` uses, at most one for each artboard. + fn grid_rows(&self) -> Option { + (self.layout == ArtboardLayout::GridByColumn && self.rows > 0).then(|| (self.rows as usize).min(self.artboards.max(1) as usize)) + } + /// The columns a grid actually uses (0 or more than the artboards: one row). pub fn grid_columns(&self) -> usize { let n = self.artboards.max(1) as usize; + if let Some(rows) = self.grid_rows() { + return n.div_ceil(rows); + } match self.layout { ArtboardLayout::Row => n, ArtboardLayout::Column => 1, @@ -246,6 +263,11 @@ impl DocSettings { /// As `file.newPresets` lists it (and `file.new` takes it back). pub fn to_json(&self) -> Value { + let mut layout = + json!({"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left}); + if let (Some(rows), Some(o)) = (self.grid_rows(), layout.as_object_mut()) { + o.insert("rows".into(), json!(rows)); + } json!({ "name": self.name, "size": self.size_label(), @@ -254,7 +276,7 @@ impl DocSettings { "units": self.units.label(), "orientation": self.orientation(), "artboards": self.artboards, - "artboardLayout": {"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left}, + "artboardLayout": layout, "bleed": self.bleed, "backgroundContents": self.background.id(), "colorMode": color_mode_id(self.color_mode), @@ -337,25 +359,23 @@ impl DocSettings { Ok(self) } - /// `artboardLayout: {layout?, columns?, spacing?, rightToLeft?}` or just a layout id. + /// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id. fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> { let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column"); if let Some(id) = l.as_str() { self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?; + if self.layout != ArtboardLayout::GridByColumn { + self.rows = 0; + } return Ok(()); } let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?; + let count = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u32); for (k, v) in o { match k.as_str() { "layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?, - "columns" => { - self.columns = v - .as_f64() - .filter(|c| c.is_finite() && *c >= 1.0) - .ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))? - .round() - .min(MAX_ARTBOARDS as f64) as u32 - } + "columns" => self.columns = count(v).ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?, + "rows" => self.rows = count(v).ok_or_else(|| bad(cmd, "artboardLayout.rows must be 1 or more"))?, "spacing" => { self.spacing = v .as_f64() @@ -366,18 +386,30 @@ impl DocSettings { _ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))), } } + if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn { + return Err(bad(cmd, "artboardLayout.rows needs the gridByColumn layout")); + } + // Columns without rows, or another layout, replace a preset's rows. + if (o.contains_key("columns") && !o.contains_key("rows")) || self.layout != ArtboardLayout::GridByColumn { + self.rows = 0; + } + if self.grid_rows().is_some() { + self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX); + } Ok(()) } - /// The artboard rectangles, the first at the origin's side. + /// The artboard rectangles, the first at the origin's side. A grid by column with `rows` has + /// that many rows (at most one for each artboard). pub fn boards(&self) -> Vec { let n = self.artboards.max(1) as usize; let sizes = vec![(self.width, self.height); n]; let by_column = self.layout == ArtboardLayout::GridByColumn; - grid_origins(&sizes, Point::ZERO, self.grid_columns(), self.spacing, by_column, self.right_to_left) - .into_iter() - .map(|o| Rect::from_origin_size(o, (self.width, self.height))) - .collect() + let origins = match self.grid_rows() { + Some(rows) => grid_origins_rc(&sizes, Point::ZERO, (rows, n.div_ceil(rows)), self.spacing, true, self.right_to_left), + None => grid_origins(&sizes, Point::ZERO, self.grid_columns(), self.spacing, by_column, self.right_to_left), + }; + origins.into_iter().map(|o| Rect::from_origin_size(o, (self.width, self.height))).collect() } /// The new document (title and swatches set by `file.new`). diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 5763591ec7..dd17bb579e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -35,7 +35,7 @@ use serde_json::{Value, json}; use vectorcraft_geom::{Point, Rect}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; -use super::{Host, Link, command, current, data_size}; +use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; /// The error for a member read or called with no document open. @@ -84,12 +84,41 @@ pub(super) enum Coords { const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; -/// What the object model keeps for one run: its coordinate system and the last list of a -/// document's page items, kept while that document is unchanged. +/// What the object model keeps for one run: its coordinate system, the last list of a document's +/// page items, kept while that document is unchanged, and whether a call's own savepoint +/// ([`atomically`]) is open. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, + saving: Cell, +} + +impl State { + /// Whether a call's own savepoint is open: its commands take none of their own. + pub(super) fn saving(&self) -> bool { + self.saving.get() + } +} + +/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every +/// document, the selection and the undo histories are as they were before it, with no undo step +/// and no change to the document's saved state. +fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { + if h.dom.saving.get() { + return f(h); + } + let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate"); + h.dom.saving.set(true); + let r = f(h); + h.dom.saving.set(false); + let mut s = h.session.borrow_mut(); + if r.is_ok() { + save.keep(&mut s); + } else if !save.restore(&mut s) { + return Err(HostError::Abort(HISTORY_LOST.to_string())); + } + r } /// A document's uid, the document as it was, and the ids of its page items then. @@ -414,9 +443,9 @@ fn coords_of(d: &Data) -> std::result::Result { } /// Selects `before` again in the active document `doc` with the selection commands, so that the -/// journal holds the change: the whole objects, then the direct-selected anchors and segments, the -/// ruler guides and the key object, guide or anchor. Objects that are now deleted, hidden or -/// locked are left out. +/// journal holds the change: the objects in their order with their direct-selected anchors, then +/// the segments, the ruler guides and the key object, guide or anchor. Objects that are now +/// deleted, hidden or locked are left out. fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -> std::result::Result<(), HostError> { // Slices selected with the Slice Selection tool are the whole selection when there are any. let slices: Vec = before.slices.iter().filter(|i| doc.is_slice(**i)).map(|i| i.0).collect(); @@ -426,20 +455,25 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - } let keep = |id: &NodeId| editable(doc, *id); let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id); - let whole: Vec = before.objects.iter().filter(|i| keep(i) && !partial(i)).map(|i| i.0).collect(); - if whole.is_empty() { + let kept: Vec = before.objects.iter().copied().filter(keep).collect(); + if kept.is_empty() { command(h, "select.none", &json!({}))?; + } else if !kept.iter().any(partial) { + command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::>()}))?; } else { - command(h, "select.set", &json!({"ids": whole}))?; - } - let items: Vec = before - .anchors - .iter() - .filter(|(i, _)| keep(i)) - .map(|(i, a)| json!({"id": i.0, "anchors": a.iter().map(|(p, k)| [p, k]).collect::>()})) - .collect(); - if !items.is_empty() { - command(h, "select.anchorsMany", &json!({"items": items, "mode": "add"}))?; + // One `select.anchorsMany` selects every object in its order: a partly selected path with + // its anchors, a whole path with all of them and any other object with none. + let items: Vec = kept + .iter() + .map(|i| { + let anchors: Vec<[usize; 2]> = match before.anchors.get(i) { + Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(), + None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(), + }; + json!({"id": i.0, "anchors": anchors}) + }) + .collect(); + command(h, "select.anchorsMany", &json!({"items": items, "mode": "set"}))?; } for (i, segments) in before.segments.iter().filter(|(i, _)| keep(i)) { let segments: Vec<[usize; 2]> = segments.iter().map(|(p, k)| [*p, *k]).collect(); @@ -487,25 +521,26 @@ fn on_doc( command(h, "document.activate", &json!({"index": index}))?; } let r = f(h); + let mut restored = Ok(()); if keep_selection { let doc = { let s = h.session.borrow(); s.active().filter(|st| st.uid == uid && st.selection != before).map(|st| st.doc.clone()) }; if let Some(doc) = doc { - let back = restore_selection(h, &doc, &before); - if r.is_ok() { - back?; - } + restored = restore_selection(h, &doc, &before); } } - if switch && let Some(a) = active { - let back = command(h, "document.activate", &json!({"index": a})); - if r.is_ok() { - back?; - } - } - r + // The document that was active is active again before any error is given: `f`'s error first, + // then the selection's, then the switch back's. + let back = match active { + Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop), + _ => Ok(()), + }; + let v = r?; + restored?; + back?; + Ok(v) } /// Runs `id` with `params` on the item's document, its selection kept. @@ -707,10 +742,9 @@ impl NewDoc<'_> { if n.fract() != 0.0 || n < 1.0 || n > count { return Err(HostError::Range("artboardRowsOrCols must be a whole number from 1 to numArtBoards".into())); } - // A grid filled by column takes the number of rows; `file.new` takes columns. + // A grid filled by column takes the number of rows. let by_column = layout.get("layout").is_some_and(|l| l == "gridByColumn"); - let columns = if by_column { (count / n).ceil() } else { n }; - layout.insert("columns".into(), json!(columns)); + layout.insert((if by_column { "rows" } else { "columns" }).into(), json!(n)); } if !layout.is_empty() { p.insert("artboardLayout".into(), Value::Object(layout)); @@ -1020,11 +1054,12 @@ fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { } /// Makes `ids` the selection of `doc`, with no command when it already is: the same objects, each -/// selected as a whole, and no ruler guide, slice or key. +/// selected as a whole, and no ruler guide, slice, key or Layers panel target. fn set_selection(h: &Host, doc: Doc, ids: Vec) -> Answer { let same = with_doc(h, doc, |_, st| { let sel = &st.selection; sel.objects == ids + && sel.target.is_none() && sel.anchors.is_empty() && sel.segments.is_empty() && sel.guides.is_empty() @@ -1502,11 +1537,21 @@ fn item_move(h: &Host, a: &[Data]) -> Answer { Ok(arg(a, 0).clone()) } +/// The error of `duplicate` on a path inside a compound path. +pub const COMPOUND_MEMBER: &str = "Duplicating a path inside a compound path is not available yet"; + /// `duplicate(relativeObject?, insertionLocation?)`: a copy of the item, directly above it as /// Edit › Duplicate makes one, or into or beside `relativeObject` as `move` puts it. → the copy. -/// When `node.move` refuses the place, the copy is deleted and the error is thrown. +/// When `node.move` refuses the place, the copy and every change it made are put back, and the +/// error is thrown. fn item_duplicate(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; + let in_compound = with_doc(h, item.doc, |_, st| { + st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })) + }); + if in_compound { + return Err(HostError::Error(COMPOUND_MEMBER.into())); + } let to = match arg(a, 1) { Data::Undefined => { if !matches!(arg(a, 2), Data::Undefined) { @@ -1516,21 +1561,14 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { } target => Some(destination(h, item, target, arg(a, 2), true)?), }; - let r = edit_item(h, item, "edit.duplicate", &json!({"ids": [item.id.0]}))?; - let id = match &r { - Data::Object(o) => o.iter().find(|(k, _)| k == "ids").and_then(|(_, v)| match v { - Data::Array(ids) => ids.first().and_then(|d| if let Data::Number(n) = d { whole(*n) } else { None }), - _ => None, - }), - _ => None, - }; - let id = id.ok_or_else(|| HostError::Error("the copy was not made".into()))?; - if let Some(to) = to - && let Err(e) = place(h, item.doc, NodeId(id), &to) - { - edit_item(h, item, "edit.clear", &json!({"ids": [id]}))?; - return Err(e); - } + let id = atomically(h, |h| { + let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?; + let id = made["ids"].get(0).and_then(Value::as_u64).ok_or_else(|| HostError::Error("the copy was not made".into()))?; + if let Some(to) = to { + place(h, item.doc, NodeId(id), &to)?; + } + Ok(id) + })?; let s = h.session.borrow(); let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; Ok(item_ref(h, st, NodeId(id))) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 5ec5e2e92b..d228ff848f 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1237,7 +1237,8 @@ fn note_ids(s: &mut Session) { fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); let mutating = waits_for_tool_edit(id); - let save = mutating.then(|| Savepoint::take(s, id)); + // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. + let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); 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(); @@ -1303,6 +1304,11 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result std::result::Result { + command_value(host, id, params).map(|(data, _)| data) +} + +/// [`command`], with the command's result as it gave it as well as the script's copy of it. +fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> { let id = id.to_string(); let params = params.clone(); let session = host.session.clone(); @@ -1340,7 +1346,7 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result| { v.sort_unstable(); @@ -352,7 +390,43 @@ fn a_grid_by_column_takes_the_number_of_rows() { }; let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect()); let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect()); - assert_eq!((tops, lefts), (rows, cols), "{layout}"); + assert_eq!((tops, lefts), (rows, cols), "{layout} {count}"); + } +} + +#[test] +fn file_new_takes_the_rows_of_a_grid_by_column() { + let mut s = Session::new(); + let first_column = |s: &mut Session, layout: Value| { + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": layout})).unwrap(); + let boards = &s.active().unwrap().doc.artboards; + boards.iter().filter(|b| b.rect.x0.round() as i64 == boards[0].rect.x0.round() as i64).count() + }; + assert_eq!(first_column(&mut s, json!({"layout": "gridByColumn", "rows": 4})), 4); + // Rows take the place of columns given beside them. + assert_eq!(first_column(&mut s, json!({"layout": "gridByColumn", "rows": 4, "columns": 1})), 4); + // A preset keeps and lists the rows, with the columns they give. + use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; + let settings = DocSettings { artboards: 5, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() }; + let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap(); + let listed = settings.to_json(); + assert_eq!((&listed["artboardLayout"]["columns"], &listed["artboardLayout"]["rows"]), (&json!(2), &json!(4)), "{listed}"); + let stored: DocSettings = serde_json::from_value(serde_json::to_value(&settings).unwrap()).unwrap(); + assert_eq!(stored.rows, 4); + // More artboards keep the rows; columns alone, or another layout, replace them. + let more = stored.clone().with_params(&json!({"artboards": 9, "artboardLayout": listed["artboardLayout"]}), "file.new").unwrap(); + assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4); + let by_columns = stored.clone().with_params(&json!({"artboardLayout": {"columns": 1}}), "file.new").unwrap(); + assert_eq!((by_columns.rows, by_columns.boards().iter().filter(|b| b.x0 == by_columns.boards()[0].x0).count()), (0, 5)); + for layout in [json!({"layout": "gridByRow"}), json!("gridByRow")] { + let by_row = stored.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap(); + assert_eq!((by_row.rows, by_row.to_json()["artboardLayout"].get("rows")), (0, None), "{layout}"); + } + let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string(); + assert!(e.contains("rows must be 1 or more"), "{e}"); + for layout in ["gridByRow", "row", "column"] { + let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string(); + assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}"); } } @@ -390,6 +464,47 @@ fn an_edit_keeps_direct_selected_anchors() { assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); } +#[test] +fn an_edit_keeps_the_order_of_a_mixed_selection() { + let (mut s, a, b) = doc(); + rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + let before = s.active().unwrap().selection.clone(); + assert_eq!(before.objects, vec![a, b]); + log(&mut s, "app.activeDocument.pageItems[2].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.anchors.clone()), (before.objects, before.anchors)); +} + +#[test] +fn assigning_the_selection_clears_a_layers_panel_target() { + let (mut s, a, _) = doc(); + s.execute("layer.target", &json!({"id": a.0})).unwrap(); + assert_eq!(s.active().unwrap().selection.target, Some(a)); + log(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[0];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.target), (vec![a], None)); +} + +#[test] +fn a_held_image_stays_the_same_object_when_it_is_embedded() { + let dir = super::links::Folder::new("dom-embed"); + let photo = dir.file("photo.png"); + super::links::write(&photo, &super::links::png(20, 10, [255, 0, 0])); + let mut s = super::links::session(); + let id = super::links::place(&mut s, &photo); + let out = log( + &mut s, + &format!( + "var i = app.activeDocument.pageItems[0]; vc.log(i.typename); vc.run('links.embed', {{ids: [{}]}});\ + var j = app.activeDocument.pageItems[0]; vc.log([i === j, i.typename, i instanceof RasterItem, i instanceof PlacedItem]);", + id.0 + ), + ); + assert_eq!(out, vec![json!("PlacedItem"), json!([true, "RasterItem", true, false])]); +} + #[test] fn an_edit_keeps_the_key_object() { let (mut s, a, b) = doc(); @@ -630,8 +745,16 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); let p = path.to_string_lossy().replace('\\', "\\\\"); - let out = log(&mut s, &format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));")); + let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); + // Read roots that leave out the document's file: the same path does not count. + let elsewhere = std::env::temp_dir().join(format!("vc-dom-roots-{}", std::process::id())); + std::fs::create_dir_all(&elsewhere).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere], &[]).unwrap().unwrap(); + let out = crate::file_access::confine(Some(&roots), || log(&mut s, &query)); + assert_eq!(out, vec![json!(false), json!(false)]); + let _ = std::fs::remove_dir_all(&elsewhere); for bad in ["../x.svg", "a/../b.svg", "\\\\\\\\host\\\\share\\\\x.svg", "//host/share/x.svg", "a\\u0000b", ""] { assert!(failure(&mut s, &format!("app.getIsFileOpen('{bad}');")).contains("cannot check"), "{bad}"); } @@ -647,12 +770,13 @@ fn hostile_dom_values_do_not_reenter_or_exceed_limits() { let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['PathItem', 0, 1, 1]; app.activeDocument.selection = f;"); assert!(e.contains("not plain data"), "{e}"); // A getter in a value is refused before it runs. - let e = failure( + let out = log( &mut s, "var hit = 0, v = {}; Object.defineProperty(v, 0, {get: function () { hit++; return 1; }, enumerable: true});\ - try { app.activeDocument.rulerOrigin = v; } catch (e) { vc.log(hit); throw e; }", + try { app.activeDocument.rulerOrigin = v; } catch (e) { vc.log(e.message); } vc.log(hit);", ); - assert!(e.contains("rulerOrigin"), "{e}"); + assert!(out[0].as_str().is_some_and(|m| m.contains("rulerOrigin")), "{out:?}"); + assert_eq!(out[1], json!(0)); let e = failure(&mut s, "var a = []; for (var i = 0; i < 10001; i++) a.push(app.activeDocument.pageItems[0]); app.activeDocument.selection = a;"); assert!(e.contains("at most 10000"), "{e}"); assert_eq!(s.active().unwrap().selection.objects, before); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 312221986c..f34c9cff8e 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -407,8 +407,9 @@ impl Interp { } _ => self.read_args(name, args, how)?, }; - // Only the script's own code, in a run that can pause, can wait for a result. - let can_wait = self.in_slice && self.reentry == 0; + // Only the script's own code, in a run that can pause, can wait for a result, and a host + // class's constructor called with `new` cannot. + let can_wait = self.in_slice && self.reentry == 0 && !self.constructing; self.can_wait.set(can_wait); let result = f(data); self.can_wait.set(false); @@ -417,6 +418,7 @@ impl Interp { Ok(d) => self.write_data(d, 0, matches!(how, ArgRead::Frozen)), Err(HostError::Wait) if can_wait => { self.waiting = true; + self.waiting_hosted = matches!(how, ArgRead::Hosted); self.pause.set(true); Ok(Value::Undefined) } diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 1d03f981ff..e88bc3f454 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -8,7 +8,9 @@ //! object a script made that carries [`HOST_REF_KEY`] is refused, so a script cannot make an object //! of a host class from its own data. A class's prototype and constructor are frozen. While a //! script holds the object for a class and handle, each read of that class and handle gives the -//! same object. +//! same object. Classes that descend from the same class without a parent share their objects: a +//! read of another of them with the same handle gives the object the script holds, now of the +//! class that read names. //! //! Every member function gets the object it is called on (`this`) as its first argument, or //! `undefined` when `this` is not an object of a host class, followed by the call's arguments; a @@ -67,6 +69,9 @@ pub(crate) struct Entry { proto: ObjId, ctor: ObjId, index: Option, + /// The class without a parent this class descends from (itself for such a class), as an index + /// into the realm's classes. + family: u32, } impl Entry { @@ -75,24 +80,26 @@ impl Entry { } } -/// A class, as an index into the realm's classes, and the bits of a handle. +/// A family of classes ([`Entry::family`]) and the bits of a handle. type MadeKey = (u32, Box<[u64]>); -/// The object made for each class and handle ([`Interp::host_objects`]). +/// The object made for each family of classes and handle ([`Interp::host_objects`]). pub(crate) type Made = std::collections::HashMap; /// Whether `id` is still the object made for `key`, and not a freed cell or another object that /// was given its cell. -fn is_made(heap: &crate::heap::Heap, id: ObjId, key: &MadeKey) -> bool { +fn is_made(heap: &crate::heap::Heap, classes: &[Entry], id: ObjId, key: &MadeKey) -> bool { heap.object(id).is_some_and(|o| match &o.class { - Class::Host(h) => h.class == key.0 && h.handle.iter().map(|n| n.to_bits()).eq(key.1.iter().copied()), + Class::Host(h) => { + classes.get(h.class as usize).is_some_and(|e| e.family == key.0) && h.handle.iter().map(|n| n.to_bits()).eq(key.1.iter().copied()) + } _ => false, }) } /// Drops the entries of `made` whose objects the last collection freed. -pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap) { - made.retain(|key, id| is_made(heap, *id, key)); +pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap, classes: &[Entry]) { + made.retain(|key, id| is_made(heap, classes, *id, key)); } /// The [`Data`] that stands for the object of host class `class` with `handle`. @@ -132,12 +139,20 @@ impl Interp { let Some((class, entry)) = self.host_classes.iter().enumerate().find(|(_, e)| &*e.name == name) else { return Err(self.throw(ErrorType::Type, &format!("a host value names the unknown class {name}"))); }; - let proto = entry.proto; + let (proto, family) = (entry.proto, entry.family); let class = u32::try_from(class).unwrap_or(u32::MAX); - let made = (class, handle.iter().map(|n| n.to_bits()).collect::>()); + let made = (family, handle.iter().map(|n| n.to_bits()).collect::>()); if let Some(&id) = self.host_objects.get(&made) - && is_made(&self.heap, id, &made) + && is_made(&self.heap, &self.host_classes, id, &made) { + // An object of another class of the family becomes one of `class`. + let o = self.object_mut(id)?; + if let Class::Host(h) = &mut o.class + && h.class != class + { + h.class = class; + o.proto = Some(proto); + } return Ok(Value::Object(id)); } self.reserve_heap(crate::heap::OBJECT_BYTES)?; @@ -207,10 +222,11 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { if i.host_classes.iter().any(|e| *e.name == *class.name) { return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); } - let parent = match &class.parent { - None => i.intrinsics.object_proto, + let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX); + let (parent, family) = match &class.parent { + None => (i.intrinsics.object_proto, own), Some(p) => match i.host_classes.iter().find(|e| *e.name == **p) { - Some(e) => e.proto, + Some(e) => (e.proto, e.family), None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), }, }; @@ -220,7 +236,7 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index }); + i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 21cd2c0bc5..1da0d53002 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -636,6 +636,46 @@ fn a_host_function_that_waits_where_it_cannot_ends_the_run() { assert_eq!(e.kind, RunErrorKind::Internal); } +/// The host class `Thing` with the method `fetch`, which waits for its answer where it can, the +/// getter `id`, the first number of the object's handle, and the constructor `make`; and the +/// global `thing`, the `Thing` with the handle `[1]`. +fn with_thing(r: &mut Realm, make: Option) { + let can_wait = r.wait_flag(); + let fetch: HostFunction = Rc::new(move |_| if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) }); + let id: HostFunction = Rc::new(|a| Ok(a.first().and_then(host_ref_parts).and_then(|(_, h)| h.first().copied()).map_or(Data::Null, Data::Number))); + let members = vec![("fetch".to_string(), HostMember::Method(fetch)), ("id".to_string(), HostMember::Get(id))]; + let class = HostClass { name: "Thing".into(), parent: None, members, index: None, construct: make }; + r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); +} + +#[test] +fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { + let mut r = realm(1_000_000); + with_thing(&mut r, None); + r.start("var t = thing.fetch(), u = thing.fetch(); [t instanceof Thing, t.id, t === u, t === thing].join()").unwrap(); + for _ in 0..2 { + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.answer(host_ref("Thing", &[2.0])).unwrap(); + } + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into())); +} + +#[test] +fn a_host_class_constructor_called_with_new_cannot_wait() { + let mut r = realm(1_000_000); + let could: Rc>> = Rc::default(); + let (seen, can_wait) = (could.clone(), r.wait_flag()); + let make: HostFunction = Rc::new(move |_| { + seen.set(Some(can_wait.get())); + if can_wait.get() { Err(HostError::Wait) } else { Ok(Data::Object(Vec::new())) } + }); + with_thing(&mut r, Some(make)); + r.start("var c = new Thing(); c instanceof Thing").unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::Bool(true)); + assert_eq!(could.get(), Some(false)); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 874116d472..63e6251dd7 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -257,7 +257,7 @@ pub(crate) struct Interp { pub(crate) host_classes: Vec, /// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`]. pub(crate) write_hosted: bool, - /// The object made for each class and handle ([`crate::host_classes`]), so that two reads of + /// The object made for each family of classes and handle ([`crate::host_classes`]), so that two reads of /// the same one give the same object. It is not a root: an entry whose object was collected is /// dropped after each collection. pub(crate) host_objects: crate::host_classes::Made, @@ -281,6 +281,11 @@ pub(crate) struct Interp { pub(crate) can_wait: Rc>, /// A host function's call waits for its result: the value on top of the stack stands in for it. pub(crate) waiting: bool, + /// The call that waits is a member of a host class ([`crate::host::ArgRead::Hosted`]): its + /// answer is read as such a member's result is ([`Interp::write_hosted`]). + pub(crate) waiting_hosted: bool, + /// A host class's constructor runs with `new`: it may not wait for its result. + pub(crate) constructing: bool, /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before /// the next instruction runs. pub(crate) resuming: Option, @@ -538,6 +543,8 @@ impl Interp { in_slice: false, can_wait: Rc::default(), waiting: false, + waiting_hosted: false, + constructing: false, resuming: None, host_abort: None, data_limits: crate::DataLimits::default(), @@ -788,7 +795,7 @@ impl Interp { roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects)); roots.envs.push(self.global_env); self.heap.collect(&roots); - crate::host_classes::forget_collected(&mut self.host_objects, &self.heap); + crate::host_classes::forget_collected(&mut self.host_objects, &self.heap, &self.host_classes); // The collection counts the live total again, so bytes already released are not in it. self.held.released.set(0); self.flattened.set(0); @@ -2392,11 +2399,14 @@ impl Interp { } // A host class's constructor ([`crate::host_classes`]) gives the object it makes. A plain // object it gives inherits from the class's prototype. The class's other functions are - // not constructors. + // not constructors. A constructor called with `new` cannot wait for its result. Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted }) if f.as_object().is_some_and(|o| self.is_host_constructor(o)) => { - let v = self.call_data(&host, &name, &Value::Undefined, &args, &read)?; + let was = std::mem::replace(&mut self.constructing, true); + let v = self.call_data(&host, &name, &Value::Undefined, &args, &read); + self.constructing = was; + let v = v?; if let (Some(callee), Value::Object(o)) = (f.as_object(), &v) && matches!(self.object(*o)?.class, Class::Ordinary) && let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))? diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 52952eb73e..f1ca6b570d 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -255,6 +255,8 @@ impl Realm { interp.last_error = Value::Null; interp.host_abort = None; interp.waiting = false; + interp.waiting_hosted = false; + interp.constructing = false; interp.resuming = None; interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; @@ -291,6 +293,8 @@ impl Realm { interp.temp_roots.clear(); interp.join_stack.clear(); interp.waiting = false; + interp.waiting_hosted = false; + interp.constructing = false; interp.resuming = None; interp.passing = Value::Undefined; match result { @@ -406,8 +410,11 @@ impl Realm { }); } interp.waiting = false; + // A member of a host class gets its answer as it gets an immediate result. + let hosted = std::mem::take(&mut interp.waiting_hosted); // The value on top of the stack stood in for the result. - let r = interp.write_data(d, 0, false).and_then(|v| { + let written = if hosted { interp.write_hosted(d) } else { interp.write_data(d, 0, false) }; + let r = written.and_then(|v| { interp.stack.pop(); interp.push(v) }); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 4f48d4ad2f..f64f2f6be2 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -245,8 +245,13 @@ fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { ) } +/// Sets one artboard layout field. A new layout or column count replaces the rows of a preset +/// made with `file.new`'s `rows`. fn set_layout(d: &mut Dialog, key: &str, v: Value) { let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); + if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) { + o.remove("rows"); + } l[key] = v; d.fields.insert("artboardLayout".into(), l); } @@ -890,6 +895,21 @@ mod tests { app.ui.dialog.as_ref().unwrap().fields.get(k).cloned().unwrap_or_default() } + /// A preset's rows stay until Columns or the layout changes. + #[test] + fn a_new_column_count_replaces_a_presets_rows() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": 4})); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "spacing", json!(5.0)); + assert_eq!(field(&app, "artboardLayout")["rows"], json!(4)); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "columns", json!(3)); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByColumn", "columns": 3, "spacing": 5.0})); + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4})); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByRow")); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow"})); + } + /// Recent shows each entry as it was made: a portrait and a landscape A3 are two cards of /// their own orientations, and only the chosen one is selected (#2860). #[test] diff --git a/docs/gaps.md b/docs/gaps.md index 549d74f46b..cd23b3096c 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -807,8 +807,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the document object model for scripts and the `#engine` script directive (#1183 is - open). File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` +- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the + other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new + documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 94d8e728c0..5f873fe10a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2631,9 +2631,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` - starts with the defaults that page gives; `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` - throw an error that says they are not available yet, and `showOptionsDialog` true throws `Dialog unavailable` - with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, + starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and + `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when + the preset it is given holds one of them with a value other than `null`, and makes no document. + `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each @@ -2648,7 +2649,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` directly below it. An object of another document throws `Cross-document placement is not available`, and when - `node.move` refuses the place of a copy, `duplicate` deletes the copy and throws that error. The + `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and + the undo history as they were before the call. `duplicate` on a path inside a compound path throws + `Duplicating a path inside a compound path is not available yet`. A script that holds a placed image keeps the + same object when the image is embedded: the next read gives that object, now a `RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. @@ -8847,7 +8851,10 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, -spacing, rightToLeft}`, `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's +rows, spacing, rightToLeft}` (`rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is +an error with another layout; a preset keeps the rows until `columns` without `rows`, or another layout, is given, +and New Document drops them when Columns or the layout changes), +`bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)). `file.newPresets {category?}` lists the categories and presets (Recent: the last sizes used; Saved: the user's presets, From 6cce980e2bb5e1781b72452983716ed659775575 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:46:14 -0800 Subject: [PATCH 019/101] Scripts: keep targets and chosen parts when edits restore the selection - An edit a script makes puts back a Layers panel target, an object chosen inside a dynamic symbol instance and an object chosen in an Objects on Path group, each with its own selection command. - Assigning a document's selection selects a symbol instance or an Objects on Path group as a whole when one of its objects was chosen. - file.newPresets lists a grid by column's rows as set, also when there are fewer artboards than rows, and New Document's Columns shows the columns those rows give the current number of artboards. - docs/roadmap.md's M13 row names the script object model that is available. --- crates/engine/src/cmd/newdoc.rs | 5 +- crates/engine/src/script/dom.rs | 35 +++++++++-- crates/engine/src/tests/script_dom.rs | 71 ++++++++++++++++++++++ crates/ui-egui/src/dialogs/new_document.rs | 35 ++++++++--- docs/mcp.md | 5 +- docs/roadmap.md | 2 +- 6 files changed, 135 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 03be423cf3..a242b1fd20 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -265,8 +265,9 @@ impl DocSettings { pub fn to_json(&self) -> Value { let mut layout = json!({"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left}); - if let (Some(rows), Some(o)) = (self.grid_rows(), layout.as_object_mut()) { - o.insert("rows".into(), json!(rows)); + // The rows as set, also when there are fewer artboards than rows. + if let Some(o) = layout.as_object_mut().filter(|_| self.grid_rows().is_some()) { + o.insert("rows".into(), json!(self.rows)); } json!({ "name": self.name, diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index dd17bb579e..0883e94099 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -443,9 +443,10 @@ fn coords_of(d: &Data) -> std::result::Result { } /// Selects `before` again in the active document `doc` with the selection commands, so that the -/// journal holds the change: the objects in their order with their direct-selected anchors, then -/// the segments, the ruler guides and the key object, guide or anchor. Objects that are now -/// deleted, hidden or locked are left out. +/// journal holds the change: a Layers panel target, a dynamic symbol instance's object or an Objects +/// on Path group's object with its own command, else the objects in their order with their +/// direct-selected anchors, then the segments, the ruler guides and the key object, guide or anchor. +/// Objects that are now deleted, hidden or locked are left out. fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -> std::result::Result<(), HostError> { // Slices selected with the Slice Selection tool are the whole selection when there are any. let slices: Vec = before.slices.iter().filter(|i| doc.is_slice(**i)).map(|i| i.0).collect(); @@ -454,6 +455,24 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - return Ok(()); } let keep = |id: &NodeId| editable(doc, *id); + // Each of these commands sets the whole selection. One that refuses (its object is no longer + // inside the isolated group, or a symbol's object is now hidden) changes nothing, and the + // objects are selected as below. + if let Some(t) = before.target.filter(keep) + && command(h, "layer.target", &json!({"id": t.0})).is_ok() + { + return Ok(()); + } + if let Some(p) = before.symbol_part.as_ref().filter(|p| keep(&p.instance)) + && command(h, "symbol.instance.selectPart", &json!({"id": p.instance.0, "path": p.path})).is_ok() + { + return Ok(()); + } + if let Some(m) = before.on_path_member.filter(keep) + && command(h, "object.objectsOnPath.selectMember", &json!({"member": m.0})).is_ok() + { + return Ok(()); + } let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id); let kept: Vec = before.objects.iter().copied().filter(keep).collect(); if kept.is_empty() { @@ -503,8 +522,9 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - /// Runs `f` with the document `uid` active, and makes the document that was active before active /// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s /// commands changed it (commands given ids select them first), direct-selected anchors, segments, -/// ruler guides, slices and the key included, less the objects that are now deleted, hidden or -/// locked. +/// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic +/// symbol instance or an Objects on Path group included, less the objects that are now deleted, +/// hidden or locked. fn on_doc( h: &Host, uid: u64, @@ -1054,12 +1074,15 @@ fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { } /// Makes `ids` the selection of `doc`, with no command when it already is: the same objects, each -/// selected as a whole, and no ruler guide, slice, key or Layers panel target. +/// selected as a whole (no dynamic symbol instance's object or Objects on Path group's object +/// chosen in it), and no ruler guide, slice, key or Layers panel target. fn set_selection(h: &Host, doc: Doc, ids: Vec) -> Answer { let same = with_doc(h, doc, |_, st| { let sel = &st.selection; sel.objects == ids && sel.target.is_none() + && sel.symbol_part.is_none() + && sel.on_path_member.is_none() && sel.anchors.is_empty() && sel.segments.is_empty() && sel.guides.is_empty() diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 15a8e2e950..63cebea042 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -430,6 +430,18 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { } } +#[test] +fn a_listed_preset_keeps_more_rows_than_artboards() { + use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; + let settings = DocSettings { artboards: 2, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() }; + let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap(); + let listed = settings.to_json(); + assert_eq!((&listed["artboardLayout"]["columns"], &listed["artboardLayout"]["rows"]), (&json!(1), &json!(4)), "{listed}"); + // Five artboards from the listing fill four rows, not two. + let more = settings.with_params(&json!({"artboards": 5, "artboardLayout": listed["artboardLayout"]}), "file.new").unwrap(); + assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4); +} + #[test] fn stale_documents_throw_on_every_member() { let (mut s, _, _) = doc(); @@ -487,6 +499,65 @@ fn assigning_the_selection_clears_a_layers_panel_target() { assert_eq!((sel.objects.clone(), sel.target), (vec![a], None)); } +#[test] +fn an_edit_keeps_a_layers_panel_target() { + let (mut s, a, b) = doc(); + s.execute("layer.target", &json!({"id": a.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.target), (vec![a], Some(a))); + // A targeted layer stays targeted, with its art selected. + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.target, sel.objects.len(), sel.objects.contains(&b)), (Some(layer), 4, true)); +} + +/// A document with a rectangle at the bottom of the stack, then a dynamic symbol instance of two +/// rectangles and an Objects on Path group of one rectangle: (session, instance, group, the +/// group's rectangle). +fn chosen_parts() -> (Session, NodeId, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + rect(&mut s, 300.0, 200.0, 20.0, 20.0); + let (x, y) = (rect(&mut s, 10.0, 10.0, 20.0, 20.0), rect(&mut s, 50.0, 10.0, 20.0, 20.0)); + let id = |v: Value| NodeId(v["id"].as_u64().unwrap()); + let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [x.0, y.0], "type": "dynamic"})).unwrap()); + let member = rect(&mut s, 10.0, 100.0, 20.0, 20.0); + let line = id(s.execute("shape.line", &json!({"x1": 50, "y1": 250, "x2": 350, "y2": 250})).unwrap()); + s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + let group = id(s.execute("object.objectsOnPath.attach", &json!({"path": line.0})).unwrap()); + (s, inst, group, member) +} + +#[test] +fn an_edit_keeps_an_object_chosen_inside_a_symbol_or_on_a_path() { + let (mut s, inst, group, member) = chosen_parts(); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + let before = s.active().unwrap().selection.clone(); + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.symbol_part.clone()), (before.objects, before.symbol_part)); + s.execute("object.objectsOnPath.selectMember", &json!({"member": member.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.on_path_member), (vec![group], Some(member))); +} + +#[test] +fn assigning_the_selection_selects_a_symbol_or_on_path_group_as_a_whole() { + let (mut s, inst, group, member) = chosen_parts(); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + log(&mut s, "var d = app.activeDocument; d.selection = d.selection[0];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.symbol_part.clone()), (vec![inst], None)); + s.execute("object.objectsOnPath.selectMember", &json!({"member": member.0})).unwrap(); + log(&mut s, "var d = app.activeDocument; d.selection = d.selection[0];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.on_path_member), (vec![group], None)); +} + #[test] fn a_held_image_stays_the_same_object_when_it_is_embedded() { let dir = super::links::Folder::new("dom-embed"); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index f64f2f6be2..6b9abbcb2f 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -233,16 +233,21 @@ fn unit(d: &Dialog) -> Unit { Unit::named(&d.str("units")).unwrap_or_default() } -/// The artboard layout fields. +/// The artboard layout fields. A grid by column with rows shows the columns those rows give the +/// current number of artboards, as `file.new` lays them out. fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { let l = d.fields.get("artboardLayout"); let get = |k: &str| l.and_then(|l| l.get(k)); - ( - get("layout").and_then(Value::as_str).and_then(ArtboardLayout::parse).unwrap_or_default(), - get("columns").and_then(Value::as_u64).unwrap_or(1), - get("spacing").and_then(Value::as_f64).unwrap_or(20.0), - get("rightToLeft").and_then(Value::as_bool).unwrap_or(false), - ) + let lay = get("layout").and_then(Value::as_str).and_then(ArtboardLayout::parse).unwrap_or_default(); + let rows = get("rows").and_then(Value::as_u64).filter(|r| *r > 0 && lay == ArtboardLayout::GridByColumn); + let columns = match rows { + Some(rows) => { + let n = d.f64("artboards", 1.0).round().clamp(1.0, MAX_ARTBOARDS as f64) as u64; + n.div_ceil(rows.min(n)) + } + None => get("columns").and_then(Value::as_u64).unwrap_or(1), + }; + (lay, columns, get("spacing").and_then(Value::as_f64).unwrap_or(20.0), get("rightToLeft").and_then(Value::as_bool).unwrap_or(false)) } /// Sets one artboard layout field. A new layout or column count replaces the rows of a preset @@ -910,6 +915,22 @@ mod tests { assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow"})); } + /// Columns shows what a preset's rows give the current number of artboards. + #[test] + fn columns_follow_a_presets_rows_as_artboards_change() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": 4})); + let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; + for (artboards, shown) in [(5, 2), (9, 3), (2, 1)] { + set(&mut app, "artboards", json!(artboards)); + assert_eq!(columns(&app), shown, "{artboards} artboards"); + } + // Without rows, Columns shows the stored count. + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 2, "rows": 4})); + assert_eq!(columns(&app), 2); + } + /// Recent shows each entry as it was made: a portrait and a landscape A3 are two cards of /// their own orientations, and only the chosen one is selected (#2860). #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5f873fe10a..50e8af3d40 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8852,8 +8852,9 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, rows, spacing, rightToLeft}` (`rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is -an error with another layout; a preset keeps the rows until `columns` without `rows`, or another layout, is given, -and New Document drops them when Columns or the layout changes), +an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are +fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns +the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes), `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)). diff --git a/docs/roadmap.md b/docs/roadmap.md index 27c4f78e25..3ddf3459a4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | From 626d84352049b897d8e9e77e5e14078b1bfd2d0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:34:09 -0800 Subject: [PATCH 020/101] Scripts: list the object model in the host name check, refuse zOrder inside a compound path The host name test now has rows for app, the document model classes and the enumerations the script host adds. zOrder on a path inside a compound path throws an error and leaves the document unchanged, as duplicate does. --- crates/engine/src/script/dom.rs | 19 ++++-- crates/engine/src/tests/script_dom.rs | 36 +++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 61 ++++++++++++++++++- docs/mcp.md | 3 +- 4 files changed, 111 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 0883e94099..b986dfcf2d 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1563,16 +1563,21 @@ fn item_move(h: &Host, a: &[Data]) -> Answer { /// The error of `duplicate` on a path inside a compound path. pub const COMPOUND_MEMBER: &str = "Duplicating a path inside a compound path is not available yet"; +/// The error of `zOrder` on a path inside a compound path. +pub const COMPOUND_MEMBER_ORDER: &str = "Reordering a path inside a compound path is not available yet"; + +/// Whether `item` is a path inside a compound path. +fn in_compound(h: &Host, item: Item) -> bool { + with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }))) +} + /// `duplicate(relativeObject?, insertionLocation?)`: a copy of the item, directly above it as /// Edit › Duplicate makes one, or into or beside `relativeObject` as `move` puts it. → the copy. /// When `node.move` refuses the place, the copy and every change it made are put back, and the /// error is thrown. fn item_duplicate(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - let in_compound = with_doc(h, item.doc, |_, st| { - st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })) - }); - if in_compound { + if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER.into())); } let to = match arg(a, 1) { @@ -1597,7 +1602,8 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { Ok(item_ref(h, st, NodeId(id))) } -/// `zOrder(method)`: one of the four Object › Arrange commands for the item. +/// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a +/// compound path is refused. fn item_z_order(h: &Host, a: &[Data]) -> Answer { let id = match arg(a, 1) { Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront", @@ -1607,6 +1613,9 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { _ => return Err(HostError::Type("zOrder needs a ZOrderMethod value".into())), }; let item = this_item(h, a)?; + if in_compound(h, item) { + return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into())); + } let (before, after) = with_doc(h, item.doc, |_, st| { let at = st.doc.position(item.id); let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 63cebea042..67bd373e2d 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -358,6 +358,42 @@ fn a_path_inside_a_compound_path_is_not_duplicated() { assert_eq!(out, vec![json!(["CompoundPathItem", 6])]); } +#[test] +fn a_path_inside_a_compound_path_is_not_reordered() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + rect(&mut s, 200.0, 200.0, 20.0, 20.0); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, m = [], out = [];\ + for (var i = 0; i < p.length; i++) if (p[i].parent.typename == 'CompoundPathItem') m.push(p[i]);\ + var ways = [ZOrderMethod.BRINGTOFRONT, ZOrderMethod.BRINGFORWARD, ZOrderMethod.SENDBACKWARD, ZOrderMethod.SENDTOBACK];\ + for (var j = 0; j < m.length; j++) for (var k = 0; k < ways.length; k++) {\ + try { m[j].zOrder(ways[k]); out.push('ran'); } catch (e) { out.push(e.message); }\ + }\ + vc.log(m.length); vc.log(out);", + ); + assert_eq!(out[0], json!(2)); + let messages = out[1].as_array().cloned().unwrap_or_default(); + assert_eq!(messages.len(), 8, "{out:?}"); + for m in &messages { + assert!(m.as_str().is_some_and(|m| m.contains("Reordering a path inside a compound path is not available yet")), "{out:?}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + // The compound path itself still moves. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, c;\ + for (var i = 0; i < p.length; i++) if (p[i].typename == 'CompoundPathItem') c = p[i];\ + var at = c.zOrderPosition; c.zOrder(ZOrderMethod.BRINGTOFRONT); vc.log([at, c.zOrderPosition]);", + ); + assert_eq!(out, vec![json!([1, 2])]); +} + #[test] fn a_copy_of_an_object_with_a_large_id_is_the_copy() { 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..ef7c97e951 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -41,7 +41,8 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog and a message to the person do not change anything -/// outside it. +/// outside it. The document model (`app`, its classes and the enumerations) acts on the open +/// documents; `Document.saveAs` and `close` throw "not available yet". const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -70,8 +71,63 @@ const INSIDE: &[(&str, &str)] = &[ "absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \ getRelativeURI modified name parent path relativeURI resolve selectDlg toString", ), + ( + "", + "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \ + DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ + PageItems RulerUnits ZOrderMethod", + ), + ("Application.", "prototype"), + ( + "Application.prototype.", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ + selection typename", + ), + ("Documents.", "prototype"), + ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), + ("Document.", "prototype"), + ( + "Document.prototype.", + "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ + groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ + rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ + views views= width", + ), + ("Layer.", "prototype"), + ("Layer.prototype.", "constructor name typename"), + ("PageItems.", "prototype"), + ("PageItems.prototype.", "constructor getByName index length parent removeAll typename"), + ("PageItem.", "prototype"), + ( + "PageItem.prototype.", + "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ + controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ + left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ + position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= top top= transform \ + transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ + width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", + ), + ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), + ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), + ("DocumentColorSpace.", "CMYK RGB"), + ("DocumentPresetType.", "BasicCMYK BasicRGB Mobile Print Video Web"), + ("DocumentPreviewMode.", "DefaultPreview OverprintPreview PixelPreview"), + ("DocumentRasterResolution.", "HighResolution MediumResolution ScreenResolution"), + ( + "DocumentTransparencyGrid.", + "TransparencyGridBlue TransparencyGridDark TransparencyGridGreen TransparencyGridLight TransparencyGridMedium \ + TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed", + ), + ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), + ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), + ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; +/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` +/// and the page item types. +const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; + /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. const NOT_CHECKED: &str = "vc"; @@ -118,7 +174,8 @@ fn language_names() -> BTreeSet { fn table_names() -> BTreeSet { let inside = INSIDE.iter().flat_map(|(prefix, names)| names.split_whitespace().map(move |n| format!("{prefix}{n}"))); - OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain([NOT_CHECKED.to_string()]).collect() + let bare = BARE_CLASSES.split_whitespace().flat_map(|c| [c.to_string(), format!("{c}.prototype"), format!("{c}.prototype.constructor")]); + OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain(bare).chain([NOT_CHECKED.to_string()]).collect() } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 50e8af3d40..c305916f6f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2651,7 +2651,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot directly below it. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `duplicate` on a path inside a compound path throws - `Duplicating a path inside a compound path is not available yet`. A script that holds a placed image keeps the + `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws + `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a `RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and From 4b97cc84926ee4dd9c807dcc1e2181017452d16c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:18:44 -0800 Subject: [PATCH 021/101] Scripts: a failed selection restore ends the run unless the command refused When an edit puts the selection back, the Layers panel target, symbol part, Objects on Path member, ruler guide and key object commands fall back or skip only when the command refuses with an ordinary error. An internal failure or a request to stop now ends the run instead of being treated as a refusal. --- crates/engine/src/script/dom.rs | 35 ++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b986dfcf2d..9d4acfa798 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -459,17 +459,17 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - // inside the isolated group, or a symbol's object is now hidden) changes nothing, and the // objects are selected as below. if let Some(t) = before.target.filter(keep) - && command(h, "layer.target", &json!({"id": t.0})).is_ok() + && done_unless_refused(command(h, "layer.target", &json!({"id": t.0})))? { return Ok(()); } if let Some(p) = before.symbol_part.as_ref().filter(|p| keep(&p.instance)) - && command(h, "symbol.instance.selectPart", &json!({"id": p.instance.0, "path": p.path})).is_ok() + && done_unless_refused(command(h, "symbol.instance.selectPart", &json!({"id": p.instance.0, "path": p.path})))? { return Ok(()); } if let Some(m) = before.on_path_member.filter(keep) - && command(h, "object.objectsOnPath.selectMember", &json!({"member": m.0})).is_ok() + && done_unless_refused(command(h, "object.objectsOnPath.selectMember", &json!({"member": m.0})))? { return Ok(()); } @@ -504,7 +504,7 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - // Guides that are locked now, and a key that no longer qualifies (the objects beside it are // gone), stay unselected: those commands refuse them and change nothing. if !picked.is_empty() { - let _ = command(h, "guide.select", &json!({"indexes": picked, "toggle": true})); + done_unless_refused(command(h, "guide.select", &json!({"indexes": picked, "toggle": true})))?; } let key = if let Some((id, (p, k))) = before.key_anchor.filter(|(id, _)| keep(id)) { Some(json!({"id": id.0, "anchor": [p, k]})) @@ -514,11 +514,22 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - before.key_guide.as_ref().and_then(index).map(|g| json!({"guide": g})) }; if let Some(key) = key { - let _ = command(h, "select.key", &key); + done_unless_refused(command(h, "select.key", &key))?; } Ok(()) } +/// The result `r` of a selection command that [`restore_selection`] runs: `true` when it ran and +/// `false` when it refused (an `Error`, which changes nothing). Any other error, such as an +/// internal failure or a request to stop, is returned, so the run ends with it. +fn done_unless_refused(r: std::result::Result) -> std::result::Result { + match r { + Ok(_) => Ok(true), + Err(HostError::Error(_)) => Ok(false), + Err(e) => Err(e), + } +} + /// Runs `f` with the document `uid` active, and makes the document that was active before active /// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s /// commands changed it (commands given ids select them first), direct-selected anchors, segments, @@ -1813,3 +1824,17 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn restoring_the_selection_falls_back_only_on_a_refusal() { + assert_eq!(done_unless_refused(Ok(Data::Undefined)), Ok(true)); + assert_eq!(done_unless_refused(Err(HostError::Error("refused".into()))), Ok(false)); + // An internal failure or a stop ends the run instead of being taken for a refusal. + assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into()))); + assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); + } +} From 4bc1f7a187439606160a91b03be7add43a1cd4a3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:40:55 -0800 Subject: [PATCH 022/101] Scripts: Documents.add takes the artboard spacing file.new takes artboardSpacing is refused above 100,000 points, the limit file.new applies, so a value file.new would refuse throws a RangeError that names artboardSpacing. --- crates/engine/src/cmd/newdoc.rs | 2 +- crates/engine/src/script/dom.rs | 4 ++-- crates/engine/src/tests/script_dom.rs | 3 +++ 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index a242b1fd20..983ef4041d 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -561,7 +561,7 @@ pub(crate) fn side_error(cmd: &str, units: Unit) -> crate::EngineError { bad(cmd, format!("width and height must be more than 0 and at most {limit}")) } /// Largest artboard spacing, points. -const MAX_SPACING: f64 = 1.0e5; +pub(crate) const MAX_SPACING: f64 = 1.0e5; pub fn color_mode_id(m: ColorMode) -> &'static str { match m { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9d4acfa798..55073e70ec 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -763,8 +763,8 @@ impl NewDoc<'_> { } if let Some(d) = self.spacing { let v = number(d, "artboardSpacing")?; - if !(0.0..=MAX_SIZE).contains(&v) { - return Err(HostError::Range("artboardSpacing must be from 0 to 3999856 points".into())); + if !(0.0..=crate::cmd::newdoc::MAX_SPACING).contains(&v) { + return Err(HostError::Range("artboardSpacing must be from 0 to 100000 points".into())); } layout.insert("spacing".into(), json!(v)); } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 67bd373e2d..0324e81339 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -62,6 +62,9 @@ fn app_documents_track_active_tab_and_new_document() { assert!(failure(&mut s, "app.documents.add(DocumentColorSpace.RGB, -5);").contains("width")); assert!(failure(&mut s, "app.documents.add('RGB');").contains("colorSpace")); assert!(failure(&mut s, "app.documents.add(undefined, 10, 10, 101);").contains("numArtBoards")); + // The spacing is refused at file.new's limit, with the script's own name for it. + let spacing = "app.documents.add(undefined, 10, 10, 2, DocumentArtboardLayout.Row, 100001);"; + assert!(failure(&mut s, spacing).contains("artboardSpacing must be from 0 to 100000 points")); assert!(failure(&mut s, "app.documents.index('none');").contains("Not found")); assert_eq!(s.documents().len(), 3); } From a8d1b297664811f37ec5ab206824dea1ed77aeb2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:46:08 -0800 Subject: [PATCH 023/101] Tests: the script corpus failure test reads an undefined name Scripts now have an app object, so app.activeDocument no longer throws a ReferenceError. The test reads a name the host does not define instead. --- crates/engine/tests/script_corpus.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/script_corpus.rs b/crates/engine/tests/script_corpus.rs index 870bfbabc2..c2ca9a38f6 100644 --- a/crates/engine/tests/script_corpus.rs +++ b/crates/engine/tests/script_corpus.rs @@ -89,9 +89,9 @@ fn a_script_that_ends_well_passes() { fn a_failure_gives_its_kind_and_place() { let r = result(&mut session(), &source("var a = 1;\nvar = ;")); assert_eq!((r["ok"].clone(), r["kind"].clone(), r["line"].clone()), (json!(false), json!("syntax"), json!(2))); - let r = result(&mut session(), &source("var d = app.activeDocument;")); + let r = result(&mut session(), &source("var d = undefinedHost.activeDocument;")); assert_eq!(r["kind"], "thrown"); - assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: app"), "{r}"); + assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: undefinedHost"), "{r}"); let r = result(&mut session(), &source("while (true) {}")); assert_eq!(r["kind"], "limit"); assert!(r["fuelUsed"].as_u64().unwrap() <= FUEL); From 76aee609f1458c53e0c32c8ae3f53d849469d24b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 12:21:32 -0800 Subject: [PATCH 024/101] Tests: page item width and height setters give the page-aligned size on rotated objects A rotated rectangle given a width and then a height through the scripting object model reads back the values set, its geometric bounds have that size, and other objects stay as they were. The resize doc comment names the page's axes. --- crates/engine/src/script/dom.rs | 4 +++- crates/engine/src/tests/script_dom.rs | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 55073e70ec..fb72785a23 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1392,7 +1392,9 @@ fn item_set_top(h: &Host, a: &[Data]) -> Answer { move_to(h, a, None, Some(y)) } -/// Scales the item about its top-left corner to `size` points wide (`width`) or tall. +/// Scales the item about its top-left corner along the page's axes to `size` points wide (`width`) +/// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated +/// objects included. fn resize(h: &Host, a: &[Data], width: bool) -> Answer { let what = if width { "width" } else { "height" }; let size = number(arg(a, 1), what)?; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 0324e81339..3c5a2f4df0 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -118,6 +118,27 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +#[test] +fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let other = format!("{:?}", s.active().unwrap().doc.node(b)); + let out = log( + &mut s, + "var i = app.activeDocument.selection[0], h = i.height;\ + i.width = 80; vc.log([i.width, i.height - h]);\ + i.height = 90; vc.log([i.width, i.height]);\ + var g = i.geometricBounds; vc.log([g[2] - g[0], g[1] - g[3]]);", + ); + let pairs: Vec<[f64; 2]> = out.iter().map(|v| [v[0].as_f64().unwrap(), v[1].as_f64().unwrap()]).collect(); + for (got, want) in pairs.iter().zip([[80.0, 0.0], [80.0, 90.0], [80.0, 90.0]]) { + assert!((got[0] - want[0]).abs() < 1e-6 && (got[1] - want[1]).abs() < 1e-6, "{out:?}"); + } + assert_eq!(pairs.len(), 3, "{out:?}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was"); +} + #[test] fn convert_coordinate_pair_is_inverse_and_y_up() { let mut s = Session::new(); From f33e0cb16d13ed6f2c934e1a63074b7fabf2c94c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 12:37:34 -0800 Subject: [PATCH 025/101] Scripts: PageItem.remove refuses hidden or locked art as removeAll does remove() on an object that is hidden or locked, sits in a hidden or locked layer or group, or is a group holding such an object now throws and deletes nothing, the same rule pageItems.removeAll() applies. docs/mcp.md states both rules and that width and height scale along the page's axes. --- crates/engine/src/script/dom.rs | 6 ++++++ crates/engine/src/tests/script_dom.rs | 25 +++++++++++++++++++++++++ docs/mcp.md | 6 +++++- 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index fb72785a23..241720f786 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1437,8 +1437,14 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { at.map(|i| num(float(i as u64 + 1))).ok_or_else(|| HostError::Error(STALE_ITEM.into())) } +/// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or +/// group, or a group holding one is refused, as [`items_remove_all`] refuses it. fn item_remove(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; + let whole = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable)); + if !whole { + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {}", item.id.0))); + } edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?; Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 3c5a2f4df0..795161ac1c 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -870,6 +870,31 @@ fn remove_all_refuses_locked_art_before_deleting_anything() { assert_eq!(out, vec![json!(0)]); } +#[test] +fn remove_refuses_hidden_or_locked_art_as_remove_all_does() { + let (mut s, a, b) = doc(); + for (on, off) in [ + (json!({"ids": [b.0], "locked": true}), json!({"ids": [b.0], "locked": false})), + (json!({"ids": [b.0], "visible": false}), json!({"ids": [b.0], "visible": true})), + ] { + s.execute("object.setProps", &on).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems[1].remove();"); + assert!(e.contains(&format!("cannot delete hidden or locked objects: {}", b.0)), "{on}: {e}"); + assert!(s.active().unwrap().doc.node(b).is_some(), "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + // A group that holds a locked object is refused too. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems[0].remove();"); + assert!(e.contains(&g.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(b).is_some()); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].remove();"); + assert!(s.active().unwrap().doc.node(b).is_none()); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index c305916f6f..9bc2be8efc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2665,7 +2665,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each changed document. A value that changes nothing runs no command, and a change to another document leaves the active tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine - kept from an earlier run, throws `Stale page item`; `index` and `getByName` throw `Not found`; and + kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a + hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw + `cannot delete hidden or locked objects` and delete nothing. Setting `width` or `height` scales the object along + the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw + `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, From ba0441c458a6496b9152924ce895475cfc5e0ae5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:33:43 -0800 Subject: [PATCH 026/101] Scripts: addDocument takes only a DocumentPreset and throws when its profile cannot be read - new DocumentPreset() now makes an object of the DocumentPreset class whose settings the run keeps, so addDocument refuses a plain object, one with a typename of DocumentPreset included, with a TypeError naming presetSettings. - When file.new reports a profileError, addDocument throws an error that names the profile and the reason, and the document made with the defaults is put back. - A script's file.new reads the New Document profile file in the app's own profiles folder; the automation roots in force still apply. Before, the script's file gate refused the folder, so a scripted addDocument never used an edited profile. Docs: docs/mcp.md. --- crates/engine/src/cmd/newdoc.rs | 17 ++- crates/engine/src/file_access.rs | 9 +- crates/engine/src/script/dom.rs | 113 +++++++++++++++--- crates/engine/src/tests/script_dom.rs | 60 ++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 15 ++- docs/mcp.md | 10 +- 6 files changed, 197 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 983ef4041d..fb26b13c68 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -984,13 +984,18 @@ impl Session { let file = path.to_string_lossy().to_string(); // Checked before the file is looked for, so a request that may not read the folder learns // nothing of its files, nor where the folder is. + // A script's gate does not apply to reads of the app's own folder; the automation roots in + // force still do. let denied = |_| PROFILE_DENIED.to_string(); - crate::file_access::check_read(&file).map_err(denied)?; - if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { - return Ok(None); - } - crate::file_access::check_read(&file).map_err(denied)?; - let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?; + let read = crate::file_access::app_folder_read(|| { + crate::file_access::check_read(&file).map_err(denied)?; + if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { + return Ok(None); + } + crate::file_access::check_read(&file).map_err(denied)?; + crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some) + })?; + let Some(bytes) = read else { return Ok(None) }; // The color profiles the file carries are installed where missing, as opening it installs // them, so the new document's assigned profiles draw and are saved with it. let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?; diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..7c246c6a64 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -206,9 +206,16 @@ pub fn unconfined(f: impl FnOnce() -> T) -> T { with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f)) } +/// Run `f`, a read of a file in one of the app's own folders, with reads exempt from the gate of +/// the script command this thread runs. Unlike [`unconfined`], the roots in force still apply. +pub(crate) fn app_folder_read(f: impl FnOnce() -> T) -> T { + with_gate_reads_exempt(true, f) +} + thread_local! { /// Are reads on this thread exempt from the gate of the script command it runs? Only inside an - /// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]). + /// [`unconfined`] or an [`app_folder_read`] entered after the gate was put in force + /// ([`with_script_gate`]). static GATE_READS_EXEMPT: std::cell::Cell = const { std::cell::Cell::new(false) }; } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 241720f786..f8caab9adb 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -85,13 +85,14 @@ const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's -/// page items, kept while that document is unchanged, and whether a call's own savepoint -/// ([`atomically`]) is open. +/// page items, kept while that document is unchanged, whether a call's own savepoint +/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + presets: RefCell>>, } impl State { @@ -873,10 +874,13 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Range("the startup preset's name is too long".into())); } let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?; + // Only an object `new DocumentPreset()` made: a plain object such as `{width: 500}` is refused. let settings = match given(arg(a, 2)) { None | Some(Data::Null) => Vec::new(), - Some(Data::Object(o)) => o.clone(), - Some(_) => return Err(HostError::Type("presetSettings must be a DocumentPreset".into())), + Some(d) => { + let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?; + h.dom.presets.borrow()[i].clone() + } }; let field = |k: &str| settings.iter().find(|(n, _)| n == k).map(|(_, v)| v).and_then(given); for k in ["documentBleedLink", "documentBleedOffsetRect", "transparencyGrid"] { @@ -913,23 +917,101 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { if let Some(m) = mode { p.entry("colorMode").or_insert_with(|| json!(m)); } - new_document(h, p) + // A profile whose file could not be read throws, and the document `file.new` made with the + // defaults is put back, with the Recent sizes as they were. + atomically(h, |h| { + let (_, value) = command_value(h, "file.new", &Value::Object(p))?; + if let Some(e) = value.get("profileError") { + let profile = e["profile"].as_str().unwrap_or_default(); + let reason = e["reason"].as_str().unwrap_or_default(); + return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}"))); + } + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) + }) } /// `new DocumentPreset()`: a record of new-document settings with the defaults the help page /// gives; the other settings are -/// left out. -fn new_preset(_: &[Data]) -> Answer { +/// left out. The settings stay with the run, which hands the script an object of the +/// `DocumentPreset` class. +fn new_preset(h: &Host) -> Answer { + let mut presets = h.dom.presets.borrow_mut(); + if presets.len() >= MAX_PRESETS { + return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); + } let item = |k: &str, v: Data| (k.to_string(), v); - Ok(Data::Object(vec![ - item("typename", text("DocumentPreset")), + presets.push(vec![ item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), item("artboardRowsOrCols", num(1.0)), item("artboardSpacing", num(20.0)), item("height", num(792.0)), item("numArtboards", num(1.0)), item("width", num(612.0)), - ])) + ]); + Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) +} + +/// The most `DocumentPreset` objects one run can make. +const MAX_PRESETS: usize = 10_000; + +/// The settings a `DocumentPreset` has, each a property a script reads and assigns. +const PRESET_FIELDS: &[&str] = &[ + "artboardLayout", + "artboardRowsOrCols", + "artboardSpacing", + "colorMode", + "documentBleedLink", + "documentBleedOffsetRect", + "height", + "numArtboards", + "previewMode", + "rasterResolution", + "title", + "transparencyGrid", + "units", + "width", +]; + +/// The index in the run's presets of the `DocumentPreset` `d` is, when it is one this run made. +fn preset_of(h: &Host, d: &Data) -> Option { + let handle = handle_of(d, "DocumentPreset")?; + let [run, i] = handle.as_slice() else { return None }; + if whole(*run) != Some(h.run) { + return None; + } + let i = usize::try_from(whole(*i)?).ok()?; + (i < h.dom.presets.borrow().len()).then_some(i) +} + +/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`, and +/// a value is checked when `addDocument` uses it. +fn preset_field(link: &Link, key: &'static str) -> HostMember { + let not_preset = || HostError::Type("this is not a DocumentPreset".into()); + let l = link.clone(); + let get: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + let presets = h.dom.presets.borrow(); + Ok(presets[i].iter().find(|(k, _)| k == key).map_or(Data::Undefined, |(_, v)| v.clone())) + }); + let l = link.clone(); + let set: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + let value = arg(&a, 1).clone(); + h.charge_call(16 + data_size(&value))?; + let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + let mut presets = h.dom.presets.borrow_mut(); + let fields = &mut presets[i]; + match fields.iter_mut().find(|(k, _)| k == key) { + Some((_, v)) => *v = value, + None => fields.push((key.to_string(), value)), + } + Ok(Data::Undefined) + }); + HostMember::Property { get, set } } // ---- Document ---- @@ -1723,11 +1805,14 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), application.push(later(l, "Application", "beep")); let preset = { let l = link.clone(); - let f: HostFunction = Rc::new(move |a: Vec| { - current(&l)?.charge_call(64)?; - new_preset(&a) + let f: HostFunction = Rc::new(move |_: Vec| { + let h = current(&l)?; + h.charge_call(64)?; + new_preset(&h) }); - HostClass { name: "DocumentPreset".into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } + let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"))]; + members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k)))); + HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) } }; let mut classes = vec![ class("Application", None, application, None), diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 795161ac1c..a0e63a5d06 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -835,6 +835,66 @@ fn headless_add_document_dialog_fails_without_creating() { assert_eq!(s.documents().len(), 1); } +#[test] +fn add_document_takes_only_a_document_preset() { + let mut s = Session::new(); + for source in [ + "app.documents.addDocument('Print', {width: 500});", + "app.documents.addDocument('Print', {});", + "app.documents.addDocument('Print', {typename: 'DocumentPreset', width: 500});", + "var p = new DocumentPreset(); var q = {}; for (var k in p) q[k] = p[k]; app.documents.addDocument('Print', q);", + "app.documents.addDocument('Print', [612, 792]);", + "app.documents.addDocument('Print', 'DocumentPreset');", + ] { + let e = failure(&mut s, source); + assert!(e.contains("TypeError") && e.contains("presetSettings must be a DocumentPreset"), "{source}: {e}"); + } + assert!(s.documents().is_empty(), "a refused preset makes no document"); + let out = log(&mut s, "var p = new DocumentPreset(); p.width = 500; vc.log(app.documents.addDocument('Print', p).width);"); + assert_eq!(out, vec![json!(500)]); +} + +#[test] +fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { + let dir = std::env::temp_dir().join(format!("vc-script-add-document-profile-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + // A profile with no file gives the defaults. + let out = log(&mut s, "vc.log(app.documents.addDocument('Web').typename);"); + assert_eq!(out, vec![json!("Document")]); + assert_eq!(s.doc().unwrap().links_from, None); + // A script reads the profile's file in the app's own folder. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); + log(&mut s, "app.documents.addDocument('Print');"); + assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + // file.new itself makes the document with the defaults and reports the profile it could not read. + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["profile"], "Print", "{r}"); + s.execute("file.close", &json!({})).unwrap(); + let recent = s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(); + let e = failure(&mut s, "app.documents.addDocument('Print');"); + assert!(e.contains("Error: the New Document profile Print could not be read"), "{e}"); + assert!(s.documents().is_empty(), "the document made with the defaults is put back"); + // A script that catches the error finds nothing changed. + let out = log( + &mut s, + "var p = new DocumentPreset(); p.width = 333;\ + try { app.documents.addDocument('Print', p); } catch (e) { vc.log(e.name); } vc.log(app.documents.length);", + ); + assert_eq!(out, vec![json!("Error"), json!(0)]); + assert_eq!(s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(), recent, "the Recent sizes are as they were"); + // A startup preset with no profile reads no file. + let out = log(&mut s, "vc.log(app.documents.addDocument('Basic RGB').documentColorSpace);"); + assert_eq!(out, vec![json!("DocumentColorSpace.RGB")]); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn wrappers_go_stale_after_delete_and_undo() { let (mut s, _, _) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..d9b6b87103 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -73,7 +73,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \ + "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ PageItems RulerUnits ZOrderMethod", ), @@ -83,6 +83,14 @@ const INSIDE: &[(&str, &str)] = &[ "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ selection typename", ), + ("DocumentPreset.", "prototype"), + ( + "DocumentPreset.prototype.", + "artboardLayout artboardLayout= artboardRowsOrCols artboardRowsOrCols= artboardSpacing artboardSpacing= colorMode \ + colorMode= constructor documentBleedLink documentBleedLink= documentBleedOffsetRect documentBleedOffsetRect= height \ + height= numArtboards numArtboards= previewMode previewMode= rasterResolution rasterResolution= title title= \ + transparencyGrid transparencyGrid= typename units units= width width=", + ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), ("Document.", "prototype"), @@ -123,9 +131,8 @@ const INSIDE: &[(&str, &str)] = &[ ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; -/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` -/// and the page item types. -const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ +/// The classes the host adds with nothing but a prototype and its constructor: the page item types. +const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's diff --git a/docs/mcp.md b/docs/mcp.md index 9bc2be8efc..182e0fe1c8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2633,7 +2633,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when - the preset it is given holds one of them with a value other than `null`, and makes no document. + the preset it is given holds one of them with a value other than `null`, and makes no document. A + `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a + `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the + automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the + profile and the reason, and makes no document. `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) @@ -9045,7 +9049,9 @@ The profile is read on every `file.new`, so a replayed journal or a recorded act runs, as `document.open` reads its file when it runs. A file larger than 64 MiB (VectorCraft's own limit) is not read. When the file cannot be read, is too large or is not a native document, or the request's read roots leave out the folder (whether or not the file exists), the document starts with the defaults and -`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar. The +`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar, and +a script's `app.documents.addDocument` throws it. A script's file access limits do not apply to reading the profile's +file. The reason given when the read roots leave out the folder does not name the folder's path. Color profiles the profile's file carries are installed when they are missing, as `document.open` installs them, and each one that can't be used adds a line to `file.new`'s `warnings`. The new document's links find their files through relative paths from the From 5cb64802585f18dcbaeb3c4bea6136d87172b297 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:53:28 -0800 Subject: [PATCH 027/101] Scripts: assigning PageItem.selected keeps how the other objects are selected Setting selected to true or false runs select.add or select.toggle for that one object, so the other objects keep their direct-selected anchors and segments and the key object. Before, it replaced the selection with whole objects. --- crates/engine/src/script/dom.rs | 16 +++++++--------- crates/engine/src/tests/script_dom.rs | 18 ++++++++++++++++++ docs/mcp.md | 4 +++- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index f8caab9adb..e70dfbb86a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1378,17 +1378,15 @@ fn item_selected(h: &Host, a: &[Data]) -> Answer { fn item_set_selected(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let on = boolean(arg(a, 1), "selected")?; - let mut ids = with_doc(h, item.doc, |_, st| st.selection.objects.clone()); - if ids.contains(&item.id) == on { + if with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)) == on { return Ok(Data::Undefined); } - if on { - let mut given = selection_ids(h, item.doc, arg(a, 0))?; - ids.append(&mut given); - } else { - ids.retain(|i| *i != item.id); - } - set_selection(h, item.doc, ids) + // Adding or removing the one object keeps how the others are selected (their direct-selected + // anchors and segments, and the key object). + let ids = if on { selection_ids(h, item.doc, arg(a, 0))? } else { vec![item.id] }; + let id = if on { "select.add" } else { "select.toggle" }; + on_doc(h, item.doc.uid, false, |h| command(h, id, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + Ok(Data::Undefined) } /// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index a0e63a5d06..9d933378ea 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -835,6 +835,24 @@ fn headless_add_document_dialog_fails_without_creating() { assert_eq!(s.documents().len(), 1); } +#[test] +fn setting_selected_keeps_how_the_other_objects_are_selected() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + let anchors = s.active().unwrap().selection.anchors.get(&a).cloned(); + assert!(anchors.is_some()); + log( + &mut s, + "var p = app.activeDocument.pageItems;\ + for (var i = 0; i < p.length; i++) { if (p[i].left == 200) p[i].selected = true; if (p[i].left == 100) p[i].selected = false; }", + ); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.objects, vec![a, c]); + assert_eq!(sel.anchors.get(&a).cloned(), anchors, "the direct-selected anchors stay"); +} + #[test] fn add_document_takes_only_a_document_preset() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index 182e0fe1c8..a826f5b3b8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2644,7 +2644,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each entry `[i]` gives. Each page item (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/) has `typename`, `parent`, `name`, `note` (the - Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected`, `opacity` (0 to + Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds + or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they + were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` From e15e3e083d652d9dd1b9145663d9b7838a07215e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:35:17 -0800 Subject: [PATCH 028/101] New Document: Columns reads float rows and columns as file.new does The dialog read artboardLayout's rows and columns as whole numbers only, so a value stored as a float (4.0 from ui.dialog.set) fell back to the stored columns while file.new made the grid from it. The dialog now reads both as file.new does: a number of 1 or more, rounded and kept to the artboard limit. --- crates/ui-egui/src/dialogs/new_document.rs | 28 +++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 6b9abbcb2f..d7c20c0137 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -234,18 +234,20 @@ fn unit(d: &Dialog) -> Unit { } /// The artboard layout fields. A grid by column with rows shows the columns those rows give the -/// current number of artboards, as `file.new` lays them out. +/// current number of artboards, as `file.new` lays them out. Rows and columns are read as +/// `file.new` reads them: a number of 1 or more, rounded and kept to [`MAX_ARTBOARDS`]. fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { let l = d.fields.get("artboardLayout"); let get = |k: &str| l.and_then(|l| l.get(k)); + let count = |k: &str| get(k).and_then(Value::as_f64).filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u64); let lay = get("layout").and_then(Value::as_str).and_then(ArtboardLayout::parse).unwrap_or_default(); - let rows = get("rows").and_then(Value::as_u64).filter(|r| *r > 0 && lay == ArtboardLayout::GridByColumn); + let rows = count("rows").filter(|_| lay == ArtboardLayout::GridByColumn); let columns = match rows { Some(rows) => { let n = d.f64("artboards", 1.0).round().clamp(1.0, MAX_ARTBOARDS as f64) as u64; n.div_ceil(rows.min(n)) } - None => get("columns").and_then(Value::as_u64).unwrap_or(1), + None => count("columns").unwrap_or(1), }; (lay, columns, get("spacing").and_then(Value::as_f64).unwrap_or(20.0), get("rightToLeft").and_then(Value::as_bool).unwrap_or(false)) } @@ -931,6 +933,26 @@ mod tests { assert_eq!(columns(&app), 2); } + /// Rows and columns stored as floats, as `ui.dialog.set` stores them, show what `file.new` + /// makes of them: rounded, at least 1 and at most the artboard limit. + #[test] + fn columns_read_float_rows_and_columns_as_file_new_does() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; + set(&mut app, "artboards", json!(5)); + for (rows, shown) in [(json!(4.0), 2), (json!(3.5), 2), (json!(2.4), 3)] { + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 1, "rows": rows})); + assert_eq!(columns(&app), shown, "rows {rows}"); + } + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 3.0})); + assert_eq!(columns(&app), 3); + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 1e9})); + assert_eq!(columns(&app), super::MAX_ARTBOARDS as u64); + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 0.4})); + assert_eq!(columns(&app), 1); + } + /// Recent shows each entry as it was made: a portrait and a landscape A3 are two cards of /// their own orientations, and only the chosen one is selected (#2860). #[test] From abe8b303ded7186796ad1ac8647f142a02ef1375 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:14:01 -0800 Subject: [PATCH 029/101] Scripts: remove and removeAll keep art on a locked artboard PageItem.remove() and PageItems.removeAll() checked only whether the object and its layers and groups were shown and unlocked, then passed the ids to edit.clear, which deletes named objects without checking artboard locks. Both now throw "cannot delete objects on a locked artboard" with the object ids and delete nothing, as art on a locked artboard is not editable elsewhere in the document. --- crates/engine/src/script/dom.rs | 26 +++++++++++++++++++++----- crates/engine/src/tests/script_dom.rs | 24 ++++++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e70dfbb86a..bce4edad74 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1249,19 +1249,26 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { } /// `pageItems.removeAll()`: deletes every object of the document in one command. A hidden or -/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted, +/// and so does an object on a locked artboard. fn items_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); - (ids, refused) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } @@ -1518,17 +1525,26 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { } /// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or -/// group, or a group holding one is refused, as [`items_remove_all`] refuses it. +/// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`] +/// refuses it. fn item_remove(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - let whole = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable)); + let (whole, on_locked) = with_doc(h, item.doc, |_, st| { + (editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable), st.doc.on_locked_artboard(item.id)) + }); if !whole { return Err(HostError::Error(format!("cannot delete hidden or locked objects: {}", item.id.0))); } + if on_locked { + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); + } edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?; Ok(Data::Undefined) } +/// The error of `remove()` and `removeAll()` for an object on a locked artboard. +const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; + /// The error of `move` and `duplicate` given an object of another document. pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 9d933378ea..26632b7055 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -973,6 +973,30 @@ fn remove_refuses_hidden_or_locked_art_as_remove_all_does() { assert!(s.active().unwrap().doc.node(b).is_none()); } +/// Art on a locked artboard stays: `remove()` and `removeAll()` throw and delete nothing. +#[test] +fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pageItems[1].remove();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", b.0)), "{e}"); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(a).is_some() && s.active().unwrap().doc.node(b).is_some()); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + let out = log(&mut s, "var p = app.activeDocument.pageItems; p[1].remove(); p.removeAll(); vc.log(p.length);"); + assert_eq!(out, vec![json!(0)]); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index a826f5b3b8..51cd09fdbb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2673,7 +2673,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw - `cannot delete hidden or locked objects` and delete nothing. Setting `width` or `height` scales the object along + `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` + when any object is on one, throw `cannot delete objects on a locked artboard` and delete nothing. Setting `width` or `height` scales the object along the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, From 71aaa752a03dd40e4cbc7faef551022c6dd2f9a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:52:56 -0800 Subject: [PATCH 030/101] New Document: a new layout keeps the columns a preset's rows showed A preset made with file.new's rows under gridByColumn shows the column count those rows give the current number of artboards. Changing the Layout field removed the rows and kept the preset's stored columns, so Create laid out a different number of columns than the dialog showed. The layout change now writes the shown count into columns, for rows stored as integers or floats. Under gridByRow the dialog shows the stored columns and file.new rejects rows, so a layout change from it keeps the stored columns, as it does for rows file.new would reject. --- crates/ui-egui/src/dialogs/new_document.rs | 41 +++++++++++++++++++--- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index d7c20c0137..cf10f0035e 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -253,11 +253,16 @@ fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { } /// Sets one artboard layout field. A new layout or column count replaces the rows of a preset -/// made with `file.new`'s `rows`. +/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. fn set_layout(d: &mut Dialog, key: &str, v: Value) { + let (lay, shown, ..) = layout(d); let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); - if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) { - o.remove("rows"); + if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) + && o.remove("rows").and_then(|r| r.as_f64()).is_some_and(|r| r.is_finite() && r >= 1.0) + && key == "layout" + && lay == ArtboardLayout::GridByColumn + { + o.insert("columns".into(), json!(shown)); } l[key] = v; d.fields.insert("artboardLayout".into(), l); @@ -914,7 +919,35 @@ mod tests { assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByColumn", "columns": 3, "spacing": 5.0})); set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4})); super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByRow")); - assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow"})); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow", "columns": 1})); + } + + /// A new layout keeps the columns a preset's rows showed, so Create lays out what the dialog + /// showed. Under a grid by row the dialog shows the stored columns, and they stay. + #[test] + fn a_new_layout_keeps_the_columns_a_presets_rows_showed() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; + set(&mut app, "artboards", json!(9)); + for to in ["gridByRow", "gridByColumn", "row", "column"] { + for rows in [json!(4), json!(4.0), json!(3.6)] { + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": rows})); + assert_eq!(columns(&app), 3, "9 artboards in rows {rows}"); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!(to)); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": to, "columns": 3}), "{to}, rows {rows}"); + } + } + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 2, "rows": 4})); + assert_eq!(columns(&app), 2); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByColumn")); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByColumn", "columns": 2})); + assert_eq!(columns(&app), 2); + // Rows file.new would reject leave the stored columns the dialog showed. + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": 0})); + assert_eq!(columns(&app), 2); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByRow")); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow", "columns": 2})); } /// Columns shows what a preset's rows give the current number of artboards. From 67633efb4d4a2c537600e1b237cc87c3c4d18259 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:36:54 -0800 Subject: [PATCH 031/101] Scripts: a linked profile file is refused and preset values count as passed data A New Document profile file that is a link or a folder is no longer read: the read is exempt from a script's file gate, which never checked where a link leads. file.new reports it as a profileError with the reason "not a plain file". Reading a DocumentPreset setting now counts the value it returns toward the data a run may pass, as assigning it does, and addDocument counts the preset's settings before copying them. The removeAll() test on a locked artboard now also holds an object on an unlocked artboard and checks it is still there after the call throws. --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/newdoc.rs | 12 ++++++++---- crates/engine/src/script/dom.rs | 10 ++++++++-- crates/engine/src/script/mod.rs | 13 ++++++++++++- crates/engine/src/tests/newdoc.rs | 16 ++++++++++++++++ crates/engine/src/tests/script_dom.rs | 26 +++++++++++++++++++++++++- docs/mcp.md | 4 ++-- 7 files changed, 72 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index bf9ff59c14..c8b9785fe9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index fb26b13c68..073de104cc 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -977,8 +977,9 @@ impl Session { /// Profile `name`'s document, its file's path and a warning for each color profile the file /// carries that can't be used: `None` when it has no file (the shipped profile, the defaults), - /// the reason when the request being served may not read it, or its file can't be read, is - /// larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft reads. + /// the reason when the request being served may not read it, or its file is a link or a folder, + /// can't be read, is larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft + /// reads. fn read_profile(&self, name: &str) -> std::result::Result, String> { let Some(path) = self.profile_path(name) else { return Ok(None) }; let file = path.to_string_lossy().to_string(); @@ -989,8 +990,11 @@ impl Session { let denied = |_| PROFILE_DENIED.to_string(); let read = crate::file_access::app_folder_read(|| { crate::file_access::check_read(&file).map_err(denied)?; - if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { - return Ok(None); + match std::fs::symlink_metadata(&path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + // A link is refused: the script's gate does not check where it leads. + Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()), + _ => {} } crate::file_access::check_read(&file).map_err(denied)?; crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index bce4edad74..675ab3fb5a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -879,6 +879,9 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { None | Some(Data::Null) => Vec::new(), Some(d) => { let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?; + // The settings are charged as data passed to the call before they are copied. + let bytes = h.dom.presets.borrow()[i].iter().map(|(k, v)| k.len() as u64 + 2 + data_size(v)).sum::(); + h.charge_call(bytes)?; h.dom.presets.borrow()[i].clone() } }; @@ -992,8 +995,11 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { let l = link.clone(); let get: HostFunction = Rc::new(move |a: Vec| { let h = current(&l)?; - h.charge_call(16)?; - let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + // The value handed back is charged as the setter charges it, before it is copied. + let i = preset_of(&h, arg(&a, 0)); + let bytes = i.map_or(0, |i| h.dom.presets.borrow()[i].iter().find(|(k, _)| k == key).map_or(0, |(_, v)| data_size(v))); + h.charge_call(16 + bytes)?; + let i = i.ok_or_else(not_preset)?; let presets = h.dom.presets.borrow(); Ok(presets[i].iter().find(|(k, _)| k == key).map_or(Data::Undefined, |(_, v)| v.clone())) }); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..affacab584 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1046,7 +1046,7 @@ impl Host { } let bridge = self.bridge.get().saturating_add(bytes); self.bridge.set(bridge); - if bridge > MAX_BRIDGE_BYTES { + if bridge > bridge_bytes() { return Err(self.over(OVER_BRIDGE)); } let n = self.calls_this_slice.get() + 1; @@ -2509,6 +2509,15 @@ fn growth_objects() -> u64 { GROWTH_OBJECTS } +/// The data a run may pass to and from commands. +fn bridge_bytes() -> u64 { + #[cfg(test)] + if let Some(n) = TEST_BRIDGE_BYTES.with(Cell::get) { + return n; + } + MAX_BRIDGE_BYTES +} + /// The limits of a command's result on its way to the script. fn result_limits() -> DataLimits { #[cfg(test)] @@ -2526,6 +2535,8 @@ thread_local! { pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; + /// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`]. + pub(crate) static TEST_BRIDGE_BYTES: Cell> = const { Cell::new(None) }; /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. pub(crate) static TEST_ENGINE_HEAP: Cell> = const { Cell::new(None) }; /// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`]. diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index edf27aaf2a..11330bac10 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -906,6 +906,22 @@ fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { let _ = std::fs::remove_dir_all(&dir); } +#[cfg(unix)] +#[test] +fn a_profile_that_is_a_link_is_not_followed() { + let (mut s, dir) = with_profiles("link"); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + // A profile the folder held, moved out and linked back in. + let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-outside-{}.vectorcraft", std::process::id())); + std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap(); + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}"); + assert!(r.get("profile").is_none(), "{r}"); + let _ = std::fs::remove_file(&outside); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn profile_names_are_checked_and_editing_needs_the_folder() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 26632b7055..bb283e7dab 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -913,6 +913,23 @@ fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn document_preset_values_count_toward_the_data_a_run_passes() { + // A 64 KiB title, set once, then read or handed to addDocument 32 times: 2 MiB, over a 1 MiB limit. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20))); + let mut s = Session::new(); + let set = "var p = new DocumentPreset(); p.title = new Array(65537).join('t');"; + let read = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) p.title;")); + let added = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) try {{ app.documents.addDocument('Print', p, 5); }} catch (e) {{}}")); + let within = run(&mut s, &format!("{set} for (var i = 0; i < 8; i++) p.title;")); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + for e in [read, added] { + assert!(e.contains("passed more data"), "{e}"); + } + within.unwrap(); + assert!(s.documents().is_empty()); +} + #[test] fn wrappers_go_stale_after_delete_and_undo() { let (mut s, _, _) = doc(); @@ -985,12 +1002,19 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { .unwrap(); }; lock(&mut s, true); + // An object on a second, unlocked artboard is not deleted either. + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 300})).unwrap(); + let c = rect(&mut s, 1100.0, 100.0, 50.0, 50.0); let steps = undo_steps(&s); let e = failure(&mut s, "app.activeDocument.pageItems[1].remove();"); assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", b.0)), "{e}"); let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()), "{e}"); - assert!(s.active().unwrap().doc.node(a).is_some() && s.active().unwrap().doc.node(b).is_some()); + let out = + log(&mut s, "try { app.activeDocument.pageItems.removeAll(); } catch (e) { vc.log(e.name); } vc.log(app.activeDocument.pageItems.length);"); + assert_eq!(out, vec![json!("Error"), json!(3)]); + let doc = &s.active().unwrap().doc; + assert!(doc.node(a).is_some() && doc.node(b).is_some() && doc.node(c).is_some()); assert_eq!(undo_steps(&s), steps); lock(&mut s, false); let out = log(&mut s, "var p = app.activeDocument.pageItems; p[1].remove(); p.removeAll(); vc.log(p.length);"); diff --git a/docs/mcp.md b/docs/mcp.md index 51cd09fdbb..095975a485 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9050,8 +9050,8 @@ with the defaults. The profile is read on every `file.new`, so a replayed journal or a recorded action uses the profile as it is when it runs, as `document.open` reads its file when it runs. A file larger than 64 MiB (VectorCraft's own limit) is not read. -When the file cannot be read, is too large or is not a native document, or the request's read roots leave out the -folder (whether or not the file exists), the document starts with the defaults and +When the file is a link or a folder, cannot be read, is too large or is not a native document, or the request's read +roots leave out the folder (whether or not the file exists), the document starts with the defaults and `file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar, and a script's `app.documents.addDocument` throws it. A script's file access limits do not apply to reading the profile's file. The From 7c376a58da2808a3d6b42d85f8e8bfb90eacde09 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:54:44 -0800 Subject: [PATCH 032/101] Save for Web: Black & White keeps to the color count with transparent pixels With two colors and some pixels transparent, Black & White still built both black and white entries next to the transparent one, so the palette held three entries. When only one entry is left, Black & White now takes black or white, whichever leaves the opaque pixels nearer the palette with the locked colors included, and skips an end that is already locked. --- crates/render/src/encode/quantize.rs | 16 ++++++++++++++++ crates/render/src/encode/tests_palette.rs | 8 +++++++- crates/render/src/encode/tests_web.rs | 9 +++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index 885196f11b..ae2a5c2fdc 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -178,6 +178,22 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, } let free = k - lock.len(); let (mut palette, exact) = match o.reduction { + // With one entry left (two colors and a transparent entry, or the others locked): black or + // white, whichever leaves the opaque pixels nearer the palette, the locked colors included. + Reduction::BlackWhite if free < 2 => { + let mut hist = [0u64; 256]; + for c in opaque() { + hist[c[0] as usize] += 1; + } + let w = o.reduction.weights(); + let cost = |end: [u8; 3]| -> f32 { + let entries: Vec<[f32; 3]> = lock.iter().chain([&end]).map(|c| c.map(f32::from)).collect(); + let near = |g: f32| entries.iter().map(|&e| dist([g; 3], e, w)).fold(f32::INFINITY, f32::min); + hist.iter().enumerate().filter(|(_, n)| **n > 0).map(|(g, &n)| n as f32 * near(g as f32)).sum() + }; + let ends = [[0; 3], [255; 3]].into_iter().filter(|c| !lock.contains(c)); + (ends.min_by(|a, b| cost(*a).total_cmp(&cost(*b))).into_iter().collect(), false) + } Reduction::BlackWhite => (vec![[0; 3], [255; 3]], false), Reduction::Gray => ((0..free).map(|i| [(i * 255 / (free - 1).max(1)) as u8; 3]).collect(), false), Reduction::Web => (web(opaque(), free), false), diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index fbb59dc42c..837c62f359 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -71,7 +71,7 @@ fn colours_cap_the_palette() { let px = ramps(64, 48); for colors in [2, 16, 64, 256] { for dither in Dither::ALL { - for reduction in [Reduction::Perceptual, Reduction::Selective, Reduction::Adaptive, Reduction::Web, Reduction::Gray] { + for reduction in Reduction::ALL { let ix = quantize(&px, 64, 48, &PaletteOptions { colors, dither, reduction, ..Default::default() }); assert!(ix.palette.len() <= colors as usize, "{colors} {dither:?} {reduction:?}: {}", ix.palette.len()); assert!(ix.indices.iter().all(|&i| (i as usize) < ix.palette.len())); @@ -325,6 +325,12 @@ fn transparency_dither_leaves_clear_and_opaque_pixels_and_needs_transparency() { let o = PaletteOptions { colors: 2, ..alpha_dither(Dither::Pattern, 100) }; let ix = quantize(&see_through(w, h, |_, _| 128), w, h, &o); assert_eq!((ix.palette.len(), ix.transparent), (2, Some(0))); + // So does Black & White, with black and white pixels both left opaque. + let bw = PaletteOptions { reduction: Reduction::BlackWhite, matte: None, ..o }; + let px: Vec = (0..64u32).flat_map(|i| if i % 8 < 4 { [0, 0, 0, 128] } else { [255, 255, 255, 128] }).collect(); + let ix = quantize(&px, 8, 8, &bw); + assert_eq!(ix.transparent, Some(0)); + assert!(ix.palette.len() <= 2, "{:?}", ix.palette); // No pixels, and a width past the pixels there are. assert!(clear_mask(&[], 0, &alpha_dither(Dither::Diffusion, 100)).is_empty()); assert_eq!(clear_mask(&see_through(3, 1, |_, _| 200), 1000, &alpha_dither(Dither::Diffusion, 100)).len(), 3); diff --git a/crates/render/src/encode/tests_web.rs b/crates/render/src/encode/tests_web.rs index 79e36b3f5f..3eb10c364b 100644 --- a/crates/render/src/encode/tests_web.rs +++ b/crates/render/src/encode/tests_web.rs @@ -22,6 +22,15 @@ fn locked_colours_survive_a_reduction() { let ix = quantize_locked(&px, 64, 16, &o, &[rare]); assert!(ix.palette.contains(&rare) && ix.palette.len() <= 4, "{:?}", ix.palette); assert_eq!(colours(&ix)[0], rare); + // Black & White with black locked and one entry left: white takes it, though most pixels are black. + let px = image(8, 8, |x, _| if x == 7 { [255; 3] } else { [0; 3] }); + let o = PaletteOptions { colors: 2, dither: Dither::None, reduction: Reduction::BlackWhite, ..Default::default() }; + let ix = quantize_locked(&px, 8, 8, &o, &[[0; 3]]); + assert_eq!(ix.palette, [[0; 3], [255; 3]]); + // With a light gray locked, black takes the entry left, though most pixels are white. + let px = image(10, 1, |x, _| if x < 4 { [0; 3] } else { [255; 3] }); + let ix = quantize_locked(&px, 10, 1, &o, &[[200; 3]]); + assert_eq!(ix.palette, [[200; 3], [0; 3]]); } #[test] From 875bde4841aeafc9eb03701f67f09e3ae3092fbd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:12:07 -0800 Subject: [PATCH 033/101] Plug-ins: a filter or plug-in command can report a notice in the status bar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A filter's output may hold `notice`, one string reporting what the run did. It needs no permission and no host import. Once the output is applied, plugin.run and plug-in commands return it as `notice`, and the desktop app and the web build show it in the status bar as `Plug-in “name”: notice`. The status bar translates the words around it and never the notice. The host trims the notice, escapes control, bidirectional and separator characters, and cuts it at 200 characters, escapes included. A notice that is not a string or has no visible character refuses the output, and nothing changes. A run that declines, fails, is refused or is canceled shows none, and a live effect's notice is ignored. Docs: docs/plugins.md, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/plugin.rs | 17 ++++++--- crates/engine/src/tests/plugins.rs | 51 +++++++++++++++++++++++++ crates/plugins/src/objects.rs | 25 ++++++++++-- crates/plugins/src/objects/tests.rs | 30 +++++++++++++++ crates/ui-egui/src/app/commands.rs | 3 ++ crates/ui-egui/src/chrome/status_bar.rs | 13 +++++-- crates/ui-egui/src/chrome/tests.rs | 35 +++++++++++++++++ crates/ui-egui/src/dialogs/form.rs | 7 +++- 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 + crates/ui-egui/src/plugin_runs.rs | 18 +++++++++ crates/ui-egui/src/state.rs | 6 +++ docs/mcp.md | 14 +++++-- docs/plugins.md | 12 ++++++ docs/target-app-parity.md | 1 + 38 files changed, 265 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..8fbec2ad2d 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -342,6 +342,7 @@ impl FilterRun { // A command's undo step is named after the command. let label = self.label(); let (inputs, parent) = (self.inputs, self.parent); + let notice = out.notice; let ids = s.edit(&label, |d, sel| { let before = (!may_write).then(|| d.layers.clone()); let ids = objects::apply_output(d, &inputs, out.objects, parent, &admit_effects).map_err(err)?; @@ -358,6 +359,10 @@ impl FilterRun { if let Some(cmd) = &self.command { out["command"] = json!(cmd.id); } + // Only an output that was applied reports its notice. + if let Some(notice) = notice { + out["notice"] = json!(notice); + } Ok(out) } } @@ -372,8 +377,8 @@ fn not_granted(name: &str, permission: Permission) -> EngineError { /// parameters and `_context` (what it keeps with the document included), and applies its output as /// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with /// what it keeps with the document from now on: the output handed in for this very run when there -/// is one ([`FilterRun::hand_in`]), else the plug-in's, run now. → `{plugin, ids}`: what it made or -/// changed, which is then selected. +/// is one ([`FilterRun::hand_in`]), else the plug-in's, run now. → `{plugin, ids, notice?}`: what it +/// made or changed, which is then selected, and the output's `notice` once it was applied. fn run(s: &mut Session, p: &Value) -> Result { // An output handed in is for this run only (the app hands it in just before), whatever it does. let handed = s.plugin_output.take(); @@ -483,7 +488,7 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec { fields.push_str(own); } let params = format!( - "{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step → {{plugin, command, ids}}", + "{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step → {{plugin, command, ids, notice?}}", m.id, c.id ); let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); @@ -516,9 +521,9 @@ fn unrouted(_: &mut Session, _: &Value) -> Result { /// Runs plug-in command `id` (`plugin..`): a filter run of the plug-in on /// `ids` (else the selection) with the command's own parameters, checked before it runs, and /// `_context.command`, under the plug-in's permissions and budget, applied as one undo step named -/// after the command → `{plugin, command, ids}`. A run that fails (a trap, an exhausted budget, an -/// output it may not make) leaves the document as it was, and the error names the plug-in and the -/// command. +/// after the command → `{plugin, command, ids, notice?}`. A run that fails (a trap, an exhausted +/// budget, an output it may not make) leaves the document as it was, and the error names the +/// plug-in and the command. pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result { // An output handed in is for `plugin.run` alone. s.plugin_output = None; diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..802a5f9c32 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -203,6 +203,57 @@ fn failing_plugins_leave_the_document_and_history_alone() { } } +/// A filter's output may report a `notice`, which `plugin.run` returns once the output is applied, +/// escaped and capped by the host. It needs no permission: a filter granted none reports one too. +/// A `notice` that is not a string refuses the output, and the document and history stay as they +/// were. +#[test] +fn a_filter_s_notice_is_returned_once_its_output_is_applied() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000").0; + let quiet = "test.engine.notice.none"; + install(&mut s, &asking(quiet, "[]", &json!({"objects": [], "notice": "Nothing to tidy"}))); + let r = run(&mut s, "plugin.run", json!({"id": quiet})); + assert_eq!((&r["plugin"], &r["notice"]), (&json!(quiet), &json!("Nothing to tidy"))); + let reading = |s: &mut Session, id: &str, output: &Value| { + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, output)); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})) + }; + let noisy = "test.engine.notice.escaped"; + let long = format!("Done\u{202E}\n{}", "x".repeat(500)); + reading(&mut s, noisy, &json!({"objects": [{"id": id}], "notice": long})); + let shown = run(&mut s, "plugin.run", json!({"id": noisy, "ids": [id]}))["notice"].as_str().unwrap_or_default().to_string(); + assert!(shown.starts_with("Done\\u{202E}\\u{000A}xx") && shown.ends_with('…'), "{shown}"); + assert_eq!(shown.chars().count(), vectorcraft_plugins::objects::MAX_NOTICE_CHARS); + let plain = "test.engine.notice.plain"; + reading(&mut s, plain, &json!({"objects": [{"id": id}]})); + assert!(run(&mut s, "plugin.run", json!({"id": plain, "ids": [id]})).get("notice").is_none()); + let bad = "test.engine.notice.bad"; + install(&mut s, &asking(bad, "[]", &json!({"objects": [], "notice": 3}))); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let e = s.execute("plugin.run", &json!({"id": bad})).unwrap_err().to_string(); + assert!(e.contains("`notice` must be a string with visible text"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); +} + +/// A plug-in command's result carries its run's `notice` beside the command's id, and so does the +/// step of a batch that runs it. +#[test] +fn a_plugin_command_returns_its_run_s_notice() { + let mut s = session(); + let id = "test.engine.notice.command"; + let commands = r#"[{"id":"count","label":"Count"}]"#; + install_wat(&mut s, &tpl::returning(&with_commands(id, "filter", commands), r#"{"objects":[],"notice":"Counted 0 objects"}"#)); + let count = crate::cmd::plugin::command_id(id, "count"); + let r = run(&mut s, &count, json!({})); + assert_eq!((&r["command"], &r["notice"]), (&json!("count"), &json!("Counted 0 objects"))); + let batch = run(&mut s, "command.batch", json!({"commands": [{"command": count, "params": {}}]})); + assert!(batch.to_string().contains("Counted 0 objects"), "{batch}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + #[test] fn live_effect_plugins_reshape_editable_art_and_expand() { let mut s = session(); diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 19a90500ce..0fdefc15e7 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -38,6 +38,8 @@ pub const MITER_LIMIT: std::ops::RangeInclusive = 1.0..=500.0; pub const MAX_EFFECT_ID: usize = 128; /// Largest data a plug-in may keep with a document (`documentData`), in bytes of JSON. pub const MAX_DOCUMENT_DATA: usize = 1 << 20; +/// Most characters of a filter's `notice` as the host shows it, its escapes counted. +pub const MAX_NOTICE_CHARS: usize = 200; /// Most text a filter is given of one type object, in bytes of UTF-8 over all its runs: longer /// type comes with `truncated` and no runs or paragraphs. pub const MAX_INPUT_TEXT: usize = 256 * 1024; @@ -794,10 +796,12 @@ pub struct Output { /// (what the plug-in keeps stays as it is), `Some(None)` for `null` (it forgets it), else what /// it keeps from now on, at most [`MAX_DOCUMENT_DATA`] bytes of JSON. pub document_data: Option>, + /// `notice`, the run's report for the status bar, as [`decode_notice`] reads it. + pub notice: Option, } -/// Parses a filter's output: `{"objects": [...], "documentData"?: …}`, or `{"error": "message"}` -/// when the plug-in declined (the message reaches the user). +/// Parses a filter's output: `{"objects": [...], "documentData"?: …, "notice"?: "…"}`, or +/// `{"error": "message"}` when the plug-in declined (the message reaches the user). pub fn decode_output(bytes: &[u8]) -> Result { decode_output_with(bytes, &[], &HashMap::new()) } @@ -822,7 +826,22 @@ pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans) Some(Some(data)) } }; - Ok(Output { objects, document_data }) + let notice = decode_notice(&v)?; + Ok(Output { objects, document_data, notice }) +} + +/// The `notice` of output `v`: `None` when it has none (or `null`), else its text without the +/// white space around it, as [`crate::permissions::display_text`] shows plug-in text (control, +/// bidirectional formatting and separator characters escaped) and at most [`MAX_NOTICE_CHARS`] +/// characters. A `notice` that is not a string, or has no character besides white space, control +/// and zero-width ones, is an error. +pub fn decode_notice(v: &Value) -> Result> { + let shows = |c: char| !c.is_whitespace() && !c.is_control() && !matches!(c, '\u{00AD}' | '\u{200B}'..='\u{200D}' | '\u{2060}' | '\u{FEFF}'); + match v.get("notice") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) if s.chars().any(shows) => Ok(Some(crate::permissions::display_text(s.trim(), MAX_NOTICE_CHARS))), + Some(_) => Err(Error::Output("`notice` must be a string with visible text".into())), + } } /// Parses a plug-in's objects: `{"objects": [...]}`, or `{"error": "message"}` when the plug-in diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 58159c3370..c271127236 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -1172,3 +1172,33 @@ fn document_data_is_kept_forgotten_or_refused() { // A decline is still a decline. assert!(matches!(decode_output(br#"{"error": "No pens.", "documentData": 1}"#), Err(Error::Failed(_)))); } + +/// A filter's `notice`: absent or `null` is none; a string is trimmed, its control, bidirectional +/// and separator characters escaped, and cut at [`MAX_NOTICE_CHARS`] with an ellipsis; anything +/// else, and text with nothing visible, refuses the whole output. +#[test] +fn notice_is_escaped_capped_and_checked() { + let out = |notice: Option| { + let mut v = json!({"objects": []}); + if let Some(n) = notice { + v["notice"] = n; + } + decode_output(v.to_string().as_bytes()).map(|o| o.notice) + }; + assert_eq!(out(None).unwrap(), None); + assert_eq!(out(Some(Value::Null)).unwrap(), None); + assert_eq!(out(Some(json!(" Selected 12 objects \n"))).unwrap().as_deref(), Some("Selected 12 objects")); + let shown = out(Some(json!("Saved\u{202E}txt.exe\nError: disk full\u{7}"))).unwrap().unwrap_or_default(); + assert_eq!(shown, "Saved\\u{202E}txt.exe\\u{000A}Error: disk full\\u{0007}"); + let long = out(Some(json!("y".repeat(10_000)))).unwrap().unwrap_or_default(); + assert_eq!(long.chars().count(), MAX_NOTICE_CHARS); + assert!(long.ends_with('…')); + // Escapes count toward the limit, so a notice of right-to-left overrides stays within it too. + let escaped = out(Some(json!("\u{202E}".repeat(10_000)))).unwrap().unwrap_or_default(); + assert!(escaped.chars().count() <= MAX_NOTICE_CHARS && !escaped.contains('\u{202E}'), "{escaped}"); + for bad in [json!(""), json!(" \t\n "), json!("\u{200B}\u{FEFF}"), json!(12), json!(["a"]), json!({"text": "a"}), json!(true)] { + assert!(matches!(out(Some(bad.clone())), Err(Error::Output(ref e)) if e.contains("`notice`")), "{bad}"); + } + // A decline is still a decline. + assert!(matches!(decode_output(br#"{"error": "No pens.", "notice": "Done"}"#), Err(Error::Failed(_)))); +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 042e8b37a5..4537f578c3 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -85,6 +85,9 @@ impl VectorcraftApp { if id == "prefs.import" && result.is_ok() { crate::prefs_dialog::imported(self, touch_workspace); } + if let Ok(r) = &result { + crate::plugin_runs::show_notice(self, id, r); + } placing::settle_swatch_paste(self); result } diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 126cc956f3..e906d576f0 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -411,15 +411,22 @@ pub(super) fn status_readouts(app: &VectorcraftApp, ui: &mut Ui, t: &Tokens) { } /// The status message in the interface language. While it is the error of the last script run -/// and that error's message is text the script supplied, that text is shown as it is and only the -/// words around it are translated. +/// and that error's message is text the script supplied, or a plug-in run's notice +/// ([`crate::state::UiState::status_kept`]), that text is shown as it is and only the words around +/// it are translated. pub(crate) fn status_message(app: &VectorcraftApp) -> String { let status = app.ui.status.as_str(); + let is = |before: &str, kept: &str, after: &str| status.strip_prefix(before).and_then(|rest| rest.strip_suffix(after)) == Some(kept); if let Some((before, kept, after)) = app.session.script_authored_failure() - && status.strip_prefix(before.as_str()).and_then(|rest| rest.strip_suffix(after.as_str())) == Some(kept) + && is(&before, kept, &after) { return crate::i18n::msg_keeping(&before, kept, &after); } + if let Some((before, kept, after)) = &app.ui.status_kept + && is(before, kept, after) + { + return crate::i18n::msg_keeping(before, kept, after); + } crate::i18n::msg(status) } diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..fc902f4dd7 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -996,6 +996,41 @@ fn german_script_status_preserves_authored_error_and_translates_native_error() { assert_eq!(app.session.script_authored_failure(), None); } +/// A plug-in run's notice shows in the status bar after the plug-in's name once its output is +/// applied: the words around it are translated and the notice itself never is, even when it reads +/// like one of the app's own messages. A run whose output is refused shows no notice, and the next +/// status message replaces the notice. +#[test] +fn plugin_notice_shows_after_the_plug_in_s_name_and_is_never_translated() { + use vectorcraft_plugins::wat as tpl; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let install = |app: &mut crate::VectorcraftApp, id: &str, output: &str| { + let module = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), output)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module), "replace": true})).unwrap(); + }; + let id = "test.ui.notice"; + install(&mut app, id, r#"{"objects":[],"notice":"invalid array length"}"#); + let r = app.run("plugin.run", json!({"id": id})).unwrap(); + assert_eq!(r["notice"], json!("invalid array length")); + assert_eq!(app.ui.status, format!("Plug-in “Test {id}”: invalid array length")); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + assert_eq!(super::status_bar::status_message(&app), format!("Plug-in „Test {id}“: invalid array length")); + // The same words as an ordinary message are translated. + app.status("invalid array length"); + assert_eq!(super::status_bar::status_message(&app), "ungültige Array-Länge"); + crate::i18n::set_current(crate::i18n::Lang::EN); + // An output refused for its notice shows no notice. + let bad = "test.ui.notice.bad"; + install(&mut app, bad, r#"{"objects":[],"notice":"\u0007"}"#); + app.status(""); + assert!(app.run("plugin.run", json!({"id": bad})).is_err()); + assert!(!app.ui.status.starts_with("Plug-in “"), "{}", app.ui.status); + for id in [id, bad] { + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} + /// The message of an open that starts with a line about its linked files lists the open's notes on /// hover and for screen readers, in a wide and in a narrow window. A later message leaves the list /// out. diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index f19cd18cda..43296260d2 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -1088,8 +1088,8 @@ pub(super) fn preview_now(app: &mut crate::VectorcraftApp, d: &mut Dialog, label } /// OK of a dialog using [`preview`]: keep the previewed `cmd` as one undo step (or run it when no -/// preview runs) and close; the command's warning shows in the status bar either way. On an error -/// the dialog stays open. +/// preview runs) and close; the command's warning, or a plug-in run's notice, shows in the status +/// bar either way. On an error the dialog stays open. pub(crate) fn commit_preview(app: &mut crate::VectorcraftApp, cmd: &str, params: Value) -> Result { let r = if app.session.in_interaction() { match app.session.preview(cmd, ¶ms) { @@ -1100,6 +1100,9 @@ pub(crate) fn commit_preview(app: &mut crate::VectorcraftApp, cmd: &str, params: { app.status(w.to_string()); } + if r.is_ok() { + crate::plugin_runs::show_notice(app, cmd, &v); + } r } Err(e) => Err(e.to_string()), diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..14e94525f4 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7141,6 +7141,8 @@ liquify-list-end {0}, {1} {0} i {1} @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them S’ha restaurat {n} document recuperat: desa’l per conservar-lo|S’han restaurat {n} documents recuperats: desa’ls per conservar-los @msg result would exceed the canvas (coordinates out of range) el resultat excediria el llenç (coordenades fora de rang) @msg Running “{name}”… S’està executant «{name}»… +@msg Plug-in “{name}”: {notice} Complement «{name}»: {notice} +@msg `notice` must be a string with visible text `notice` ha de ser una cadena amb text visible @msg Save for Web: the image is empty Desa per a la web: la imatge és buida @msg Save writes {_1}, not {_2}: use document.export for other formats Desa escriu {_1}, no {_2}: fes servir document.export per a altres formats @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Desa escriu {_1}, no {_2}: fes servir file.saveAsTemplate per escriure’l diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..a0e98d061a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7297,6 +7297,8 @@ axis Y Axis osa Y Cancel Plug-in Run Zrušit běh zásuvného modulu @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} doběhl, ale dokument nebo zásuvný modul se mezitím změnil: spusťte ho znovu @msg Running “{name}”… Spouští se „{name}“… +@msg Plug-in “{name}”: {notice} Zásuvný modul „{name}“: {notice} +@msg `notice` must be a string with visible text `notice` musí být řetězec s viditelným textem @msg a live effect runs while the document is drawn, so it can't be `heavy` živý efekt běží během vykreslování dokumentu, takže nemůže být `heavy` @msg an exporter always gets an export's budget: leave `budget` out exportní zásuvný modul dostává vždy rozpočet exportu: klíč `budget` vynechte @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ žádá o velký výpočetní rozpočet (každé spuštění až {minutes} minut a {times}krát víc instrukcí než obvykle): musí ho schválit člověk v desktopové aplikaci, nebo předejte `allowHeavy: true` v relaci spuštěné s --allow-plugin-grants diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..fc1b9c9c02 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -528,6 +528,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` gælder for lineære, radiale, koniske og diamantformede gradienter @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} blev færdig, men dokumentet eller plug-in'et ændrede sig i mellemtiden: kør det igen @msg Running “{name}”… Kører »{name}«… +@msg Plug-in “{name}”: {notice} Plug-in »{name}«: {notice} +@msg `notice` must be a string with visible text `notice` skal være en streng med synlig tekst @msg a live effect runs while the document is drawn, so it can't be `heavy` en live-effekt kører, mens dokumentet tegnes, så den kan ikke være `heavy` @msg an exporter always gets an export's budget: leave `budget` out en eksportør får altid et eksportbudget: udelad `budget` @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants »{_1}« beder om et tungt budget (hver kørsel op til {minutes} minutter og {times} gange de sædvanlige instruktioner): en person skal godkende det i skrivebordsappen, eller send `allowHeavy: true` i en session startet med --allow-plugin-grants diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..0f27ad3bd6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6880,6 +6880,8 @@ axis Y Axis Y-Achse Cancel Plug-in Run Plug-in-Ausführung abbrechen @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} ist fertig, aber das Dokument oder das Plug-in hat sich inzwischen geändert: Führen Sie es erneut aus @msg Running “{name}”… „{name}“ wird ausgeführt… +@msg Plug-in “{name}”: {notice} Plug-in „{name}“: {notice} +@msg `notice` must be a string with visible text `notice` muss eine Zeichenkette mit sichtbarem Text sein @msg a live effect runs while the document is drawn, so it can't be `heavy` ein Live-Effekt läuft, während das Dokument gezeichnet wird, daher kann er nicht `heavy` sein @msg an exporter always gets an export's budget: leave `budget` out ein Export-Plug-in erhält immer das Budget eines Exports: Lassen Sie `budget` weg @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ verlangt ein großes Rechenbudget (jede Ausführung bis zu {minutes} Minuten und {times}-mal so viele Anweisungen wie üblich): Eine Person muss es in der Desktop-App genehmigen, oder übergeben Sie `allowHeavy: true` in einer mit --allow-plugin-grants gestarteten Sitzung diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..b61deb1f47 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7286,6 +7286,8 @@ axis Y Axis Άξονας Y Cancel Plug-in Run Ακύρωση εκτέλεσης προσθέτου @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again Το {_1} ολοκληρώθηκε, αλλά το έγγραφο ή το πρόσθετο άλλαξε στο μεταξύ: εκτελέστε το ξανά @msg Running “{name}”… Εκτέλεση του «{name}»… +@msg Plug-in “{name}”: {notice} Πρόσθετο «{name}»: {notice} +@msg `notice` must be a string with visible text το `notice` πρέπει να είναι συμβολοσειρά με ορατό κείμενο @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 diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..2806acd349 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7272,6 +7272,8 @@ axis Y Axis Eje Y Cancel Plug-in Run Cancelar ejecución del plugin @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} terminó, pero el documento o el plugin cambió entretanto: vuelva a ejecutarlo @msg Running “{name}”… Ejecutando “{name}”… +@msg Plug-in “{name}”: {notice} Plugin “{name}”: {notice} +@msg `notice` must be a string with visible text `notice` debe ser una cadena con texto visible @msg a live effect runs while the document is drawn, so it can't be `heavy` un efecto interactivo se ejecuta mientras se dibuja el documento, así que no puede ser `heavy` @msg an exporter always gets an export's budget: leave `budget` out un plugin de exportación siempre recibe el presupuesto de una exportación: omite `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}” pide un presupuesto de cálculo grande (cada ejecución hasta {minutes} minutos y {times} veces las instrucciones habituales): una persona debe aprobarlo en la aplicación de escritorio, o pasa `allowHeavy: true` en una sesión iniciada con --allow-plugin-grants diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..9f1a8e34bb 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7363,6 +7363,8 @@ axis Y Axis Y-akseli Cancel Plug-in Run Peruuta laajennuksen ajo @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} valmistui, mutta asiakirja tai laajennus muuttui sillä välin: suorita se uudelleen @msg Running “{name}”… Suoritetaan ”{name}”… +@msg Plug-in “{name}”: {notice} Laajennus ”{name}”: {notice} +@msg `notice` must be a string with visible text `notice` on oltava merkkijono, jossa on näkyvää tekstiä @msg a live effect runs while the document is drawn, so it can't be `heavy` live-tehoste suoritetaan asiakirjaa piirrettäessä, joten se ei voi olla `heavy` @msg an exporter always gets an export's budget: leave `budget` out vientilaajennus saa aina viennin budjetin: jätä `budget` pois @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants ”{_1}” pyytää suurta laskentabudjettia (jokainen ajo enintään {minutes} minuuttia ja {times} kertaa tavallinen määrä käskyjä): ihmisen on hyväksyttävä se työpöytäsovelluksessa, tai anna `allowHeavy: true` istunnossa, joka on käynnistetty valitsimella --allow-plugin-grants diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..d5ebc7f6cd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7300,6 +7300,8 @@ axis Y Axis Axe Y @msg `name` must be 1-64 printable characters `name` doit compter 1-64 caractères imprimables @msg `version`, `description` or `author` is too long `version`, `description` ou `author` est trop long @msg `warnings` must be a list of strings `warnings` doit être une liste de chaînes +@msg Plug-in “{name}”: {notice} Plug-in “{name}” ({notice}) +@msg `notice` must be a string with visible text `notice` doit être une chaîne avec du texte visible @msg `{k}` must be one of {_1} `{k}` doit valoir l’une de ces valeurs : {_1} @msg `{k}` must be {what} `{k}` doit être {what} @msg an exporter declares 1 to {MAX_EXTENSIONS} `extensions` un module externe d’exportation déclare de 1 à {MAX_EXTENSIONS} `extensions` diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..cd015d705e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8888,6 +8888,8 @@ liquify-list-end {0}, {1} {0} और {1} @msg rows and columns must be 1..500 rows और columns को 1..500 होना चाहिए @msg rows of objects whose appearances differ can't be reordered together उन ऑब्जेक्ट्स की पंक्तियाँ जिनकी उपस्थिति भिन्न होती हैं, उन्हें एक साथ फिर से व्यवस्थित नहीं किया जा सकता है @msg Running “{name}”… "{name}"... +@msg Plug-in “{name}”: {notice} प्लग-इन "{name}": {notice} +@msg `notice` must be a string with visible text `notice` दिखने वाले टेक्स्ट वाली स्ट्रिंग होनी चाहिए @msg Save for Web: the image is empty वेब के लिए सेव करें: इमेज खाली है @msg save the document first: copy puts the file in its folder पहले डॉक्यूमेंट को सेव करना: प्रतिलिपि फ़ाइल को अपने फ़ोल्डर में डालती है @msg save the document first: Package collects a saved document पहले डॉक्यूमेंट को सेव करना: पैकेज एक सेव किए गए डॉक्यूमेंट एकत्र करता है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..61f02f0851 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7282,6 +7282,8 @@ axis Y Axis Y tengely Cancel Plug-in Run Bővítmény futásának megszakítása @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} lefutott, de közben megváltozott a dokumentum vagy a bővítmény: futtasd újra @msg Running “{name}”… Futtatás: „{name}”… +@msg Plug-in “{name}”: {notice} „{name}” bővítmény: {notice} +@msg `notice` must be a string with visible text a `notice` látható szöveget tartalmazó karakterlánc legyen @msg a live effect runs while the document is drawn, so it can't be `heavy` az élő effektus a dokumentum rajzolása közben fut, ezért nem lehet `heavy` @msg an exporter always gets an export's budget: leave `budget` out az exportáló bővítmény mindig az exportálás keretét kapja: hagyd ki a `budget` kulcsot @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants a(z) „{_1}” nagy számítási keretet kér (futásonként legfeljebb {minutes} perc és a szokásos utasításszám {times}-szorosa): egy személynek jóvá kell hagynia az asztali alkalmazásban, vagy add meg az `allowHeavy: true` értéket egy --allow-plugin-grants kapcsolóval indított munkamenetben diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..5eabf8a13c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -411,6 +411,8 @@ @msg `spread` applies to linear, radial, conic and diamond gradients `spread` berlaku untuk gradien linear, radial, conic, dan diamond @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} selesai, tetapi dokumen atau plug-in berubah sementara itu: jalankan lagi @msg Running “{name}”… Menjalankan “{name}”… +@msg Plug-in “{name}”: {notice} Plug-in “{name}” melaporkan: {notice} +@msg `notice` must be a string with visible text `notice` harus berupa string dengan teks yang terlihat @msg a live effect runs while the document is drawn, so it can't be `heavy` efek langsung berjalan saat dokumen digambar, sehingga tidak dapat `heavy` @msg an exporter always gets an export's budget: leave `budget` out pengekspor selalu mendapat anggaran ekspor: hilangkan `budget` @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” meminta anggaran berat (setiap proses hingga {minutes} menit dan {times} kali instruksi biasa): seseorang harus menyetujuinya di aplikasi desktop, atau berikan `allowHeavy: true` dalam sesi yang dimulai dengan --allow-plugin-grants diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..a0e4fecb4f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6919,6 +6919,8 @@ axis Y Axis Asse Y Cancel Plug-in Run Annulla esecuzione plug-in @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} è terminato, ma nel frattempo il documento o il plug-in è cambiato: va eseguito di nuovo @msg Running “{name}”… Esecuzione di “{name}”… +@msg Plug-in “{name}”: {notice} Dal plug-in “{name}”: {notice} +@msg `notice` must be a string with visible text `notice` deve essere una stringa con testo visibile @msg a live effect runs while the document is drawn, so it can't be `heavy` un effetto dinamico viene eseguito mentre il documento viene disegnato, quindi non può essere `heavy` @msg an exporter always gets an export's budget: leave `budget` out un plug-in di esportazione riceve sempre il budget di un’esportazione: ometti `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}” chiede un budget di calcolo elevato (ogni esecuzione fino a {minutes} minuti e {times} volte le istruzioni consuete): una persona deve approvarlo nell’app desktop, oppure passa `allowHeavy: true` in una sessione avviata con --allow-plugin-grants diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..788733b3f1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6994,6 +6994,8 @@ axis Y Axis Y 軸 Cancel Plug-in Run プラグインの実行をキャンセル @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} は完了しましたが、その間にドキュメントまたはプラグインが変更されました。もう一度実行してください @msg Running “{name}”… 「{name}」を実行中… +@msg Plug-in “{name}”: {notice} プラグイン「{name}」: {notice} +@msg `notice` must be a string with visible text `notice` は表示される文字を含む文字列にしてください @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}」は大きな計算予算を求めています (1 回の実行につき最大 {minutes} 分、通常の {times} 倍の命令)。デスクトップ アプリで人が承認するか、--allow-plugin-grants を付けて開始したセッションで `allowHeavy: true` を指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..dab67fdd92 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9399,6 +9399,8 @@ axis Y Axis Y ღერძი Cancel Plug-in Run პლაგინის გაშვების გაუქმება @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} დასრულდა, მაგრამ ამასობაში დოკუმენტი ან პლაგინი შეიცვალა: გაუშვით ხელახლა @msg Running “{name}”… მიმდინარეობს „{name}“-ის გაშვება… +@msg Plug-in “{name}”: {notice} პლაგინი „{name}“: {notice} +@msg `notice` must be a string with visible text `notice` უნდა იყოს ხილული ტექსტის მქონე სტრიქონი @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-ით გაშვებულ სესიაში diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..f30279162f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6891,6 +6891,8 @@ axis Y Axis Y축 Cancel Plug-in Run 플러그인 실행 취소 @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1}이(가) 끝났지만 그동안 문서나 플러그인이 변경되었습니다. 다시 실행하세요 @msg Running “{name}”… “{name}” 실행 중… +@msg Plug-in “{name}”: {notice} 플러그인 “{name}”: {notice} +@msg `notice` must be a string with visible text `notice`는 보이는 텍스트가 있는 문자열이어야 합니다 @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}배 명령어). 데스크톱 앱에서 사람이 승인하거나 --allow-plugin-grants로 시작한 세션에서 `allowHeavy: true`를 전달하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..766b2f8553 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -375,6 +375,8 @@ liquify-list-end {0}, {1} {0} en {1} @msg `spread` applies to linear, radial, conic and diamond gradients `spread` geldt voor lineaire, radiale, conische en ruitvormige verlopen @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} is voltooid, maar het document of de plug-in is intussen gewijzigd: voer het opnieuw uit @msg Running “{name}”… „{name}” wordt uitgevoerd… +@msg Plug-in “{name}”: {notice} Plug-in „{name}”: {notice} +@msg `notice` must be a string with visible text `notice` moet een tekenreeks met zichtbare tekst zijn @msg a live effect runs while the document is drawn, so it can't be `heavy` een live-effect wordt uitgevoerd terwijl het document wordt getekend, dus kan het niet `heavy` zijn @msg an exporter always gets an export's budget: leave `budget` out een exportplug-in krijgt altijd het budget van een export: laat `budget` weg @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}” vraagt om een groot rekenbudget (elke uitvoering tot {minutes} minuten en {times} keer het gebruikelijke aantal instructies): een persoon moet dit goedkeuren in de desktop-app, of geef `allowHeavy: true` door in een sessie die is gestart met --allow-plugin-grants diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..98329f7a76 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7152,6 +7152,8 @@ axis Y Axis Oś Y Cancel Plug-in Run Anuluj działanie wtyczki @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} zakończył działanie, ale w międzyczasie zmienił się dokument lub wtyczka: uruchom ją ponownie @msg Running “{name}”… Uruchamianie „{name}”… +@msg Plug-in “{name}”: {notice} Wtyczka „{name}”: {notice} +@msg `notice` must be a string with visible text `notice` musi być ciągiem znaków z widocznym tekstem @msg a live effect runs while the document is drawn, so it can't be `heavy` efekt na żywo działa podczas rysowania dokumentu, więc nie może być `heavy` @msg an exporter always gets an export's budget: leave `budget` out wtyczka eksportu zawsze dostaje budżet eksportu: pomiń `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}” prosi o duży budżet obliczeń (każde uruchomienie do {minutes} minut i {times} razy więcej instrukcji niż zwykle): musi ją zatwierdzić osoba w aplikacji desktopowej albo przekaż `allowHeavy: true` w sesji uruchomionej z --allow-plugin-grants diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..edfd302666 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7196,6 +7196,8 @@ axis Y Axis Eixo Y Cancel Plug-in Run Cancelar Execução do Plug-in @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} terminou, mas o documento ou o plug-in mudou nesse meio-tempo: execute-o novamente @msg Running “{name}”… Executando “{name}”… +@msg Plug-in “{name}”: {notice} Do plug-in “{name}”: {notice} +@msg `notice` must be a string with visible text `notice` deve ser uma string com texto visível @msg a live effect runs while the document is drawn, so it can't be `heavy` um efeito dinâmico é executado enquanto o documento é desenhado, então não pode ser `heavy` @msg an exporter always gets an export's budget: leave `budget` out um plug-in de exportação sempre recebe o orçamento de uma exportação: omita `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}” pede um orçamento de processamento grande (cada execução até {minutes} minutos e {times} vezes as instruções habituais): uma pessoa precisa aprová-lo no aplicativo de desktop, ou passe `allowHeavy: true` em uma sessão iniciada com --allow-plugin-grants diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..fb6326f53b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6918,6 +6918,8 @@ axis Y Axis Ось Y Cancel Plug-in Run Отменить запуск модуля @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} завершился, но документ или модуль за это время изменился: запустите его снова @msg Running “{name}”… Выполняется «{name}»… +@msg Plug-in “{name}”: {notice} Модуль «{name}»: {notice} +@msg `notice` must be a string with visible text `notice` должен быть строкой с видимым текстом @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 diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..6794b14981 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7344,6 +7344,8 @@ axis Y Axis Y-axel Cancel Plug-in Run Avbryt körning av plugin @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} är klar, men dokumentet eller pluginet ändrades under tiden: kör det igen @msg Running “{name}”… Kör ”{name}”… +@msg Plug-in “{name}”: {notice} Plugin ”{name}”: {notice} +@msg `notice` must be a string with visible text `notice` måste vara en sträng med synlig text @msg a live effect runs while the document is drawn, so it can't be `heavy` en live-effekt körs medan dokumentet ritas, så den kan inte vara `heavy` @msg an exporter always gets an export's budget: leave `budget` out ett exportinsticksprogram får alltid en exports budget: utelämna `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}” begär en stor beräkningsbudget (varje körning upp till {minutes} minuter och {times} gånger de vanliga instruktionerna): en person måste godkänna det i skrivbordsappen, eller skicka `allowHeavy: true` i en session som startats med --allow-plugin-grants diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..d146fc8a3e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7369,6 +7369,8 @@ axis Y Axis Y ekseni Cancel Plug-in Run Eklenti Çalıştırmasını İptal Et @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} bitti, ancak bu sırada belge veya eklenti değişti: yeniden çalıştırın @msg Running “{name}”… “{name}” çalıştırılıyor… +@msg Plug-in “{name}”: {notice} “{name}” eklentisi: {notice} +@msg `notice` must be a string with visible text `notice` görünür metin içeren bir dize olmalıdır @msg a live effect runs while the document is drawn, so it can't be `heavy` canlı efekt belge çizilirken çalışır, bu yüzden `heavy` olamaz @msg an exporter always gets an export's budget: leave `budget` out dışa aktarma eklentisi her zaman bir dışa aktarmanın bütçesini alır: `budget` anahtarını çıkarın @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” büyük bir hesaplama bütçesi istiyor (her çalıştırma en fazla {minutes} dakika ve olağan komutların {times} katı): masaüstü uygulamasında bir kişinin onaylaması gerekir veya --allow-plugin-grants ile başlatılan bir oturumda `allowHeavy: true` geçirin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..d6a0ea26e4 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6901,6 +6901,8 @@ axis Y Axis Вісь Y Cancel Plug-in Run Скасувати запуск модуля @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} завершився, але документ або модуль тим часом змінився: запустіть його знову @msg Running “{name}”… Виконується «{name}»… +@msg Plug-in “{name}”: {notice} Модуль «{name}»: {notice} +@msg `notice` must be a string with visible text `notice` має бути рядком із видимим текстом @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 diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..bca4098192 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6947,6 +6947,8 @@ axis Y Axis Trục Y Cancel Plug-in Run Hủy lần chạy plug-in @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} đã chạy xong, nhưng tài liệu hoặc plug-in đã thay đổi trong lúc đó: hãy chạy lại @msg Running “{name}”… Đang chạy “{name}”… +@msg Plug-in “{name}”: {notice} Plug-in “{name}” báo: {notice} +@msg `notice` must be a string with visible text `notice` phải là một chuỗi có văn bản hiển thị @msg a live effect runs while the document is drawn, so it can't be `heavy` hiệu ứng trực tiếp chạy trong lúc tài liệu được vẽ nên không thể là `heavy` @msg an exporter always gets an export's budget: leave `budget` out plug-in xuất luôn nhận ngân sách của một lần xuất: hãy bỏ `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}” yêu cầu ngân sách tính toán lớn (mỗi lần chạy tới {minutes} phút và gấp {times} lần số lệnh thông thường): cần một người phê duyệt trong ứng dụng máy tính, hoặc truyền `allowHeavy: true` trong phiên khởi động bằng --allow-plugin-grants diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..3914f7423b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7129,6 +7129,8 @@ axis Y Axis Y 轴 Cancel Plug-in Run 取消运行插件 @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} 已完成,但文档或插件在此期间已更改:请重新运行 @msg Running “{name}”… 正在运行“{name}”… +@msg Plug-in “{name}”: {notice} 增效工具“{name}”:{notice} +@msg `notice` must be a string with visible text `notice` 必须是包含可见文本的字符串 @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} 倍):需要有人在桌面应用中批准,或在以 --allow-plugin-grants 启动的会话中传入 `allowHeavy: true` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..11d1a5df17 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6950,6 +6950,8 @@ axis Y Axis Y 軸 Cancel Plug-in Run 取消執行增效模組 @msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} 已完成,但文件或增效模組在此期間已變更:請重新執行 @msg Running “{name}”… 正在執行「{name}」… +@msg Plug-in “{name}”: {notice} 增效模組「{name}」:{notice} +@msg `notice` must be a string with visible text `notice` 必須是包含可見文字的字串 @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} 倍):需要有人在桌面應用程式中核准,或在以 --allow-plugin-grants 啟動的工作階段中傳入 `allowHeavy: true` diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index b80f15a9db..e5623d33fd 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -24,6 +24,7 @@ use serde_json::{Value, json}; use vectorcraft_engine::EngineError; use vectorcraft_engine::cmd::fileio::progress::{self, Progress}; use vectorcraft_engine::cmd::plugin::FilterRun; +use vectorcraft_plugins::{permissions, registry}; use crate::VectorcraftApp; use crate::export_progress::{self, Pressed}; @@ -154,6 +155,23 @@ fn finish(app: &mut VectorcraftApp, r: Running, done: Option) { } } +/// Shows in the status bar the notice of the plug-in run that command `cmd` (`plugin.run` or a +/// plug-in command) applied, with result `r`: `Plug-in “name”: notice`, the plug-in's name escaped +/// and capped as prompts show it. The notice is shown as the run returned it (escaped and capped by +/// the host) and never translated. A result without a notice leaves the status bar as it is. +pub fn show_notice(app: &mut VectorcraftApp, cmd: &str, r: &Value) { + if cmd != "plugin.run" && !vectorcraft_engine::cmd::plugin::is_command_id(cmd) { + return; + } + let (Some(notice), Some(id)) = (r.get("notice").and_then(Value::as_str), r.get("plugin").and_then(Value::as_str)) else { return }; + let name = registry::get(id).map_or_else(|| id.to_string(), |p| p.manifest().name.trim().trim_end_matches('…').to_string()); + let name = permissions::display_text(&name, permissions::MAX_SHOWN_NAME); + let status = format!("Plug-in “{name}”: {notice}"); + let before = status.strip_suffix(notice).unwrap_or_default().to_string(); + app.status(status); + app.ui.status_kept = Some((before, notice.to_string(), String::new())); +} + /// The progress window's Cancel (also Esc): every filter running in the background stops (at once when it checks /// `vc_cancelled`, else at the next slice of its budget) and changes nothing → `{cancelled: n}`. pub fn cancel_all(app: &mut VectorcraftApp) -> Value { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f8bce4e088..a59075730b 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -670,6 +670,11 @@ pub struct UiState { /// Not saved. #[serde(skip)] pub status_notes: Option<(String, Vec)>, + /// The status text a plug-in wrote, with the app's words before and after it: while the status + /// is these three together, the status bar translates the app's words and shows the plug-in's + /// as they are ([`crate::plugin_runs::show_notice`]). Not saved. + #[serde(skip)] + pub status_kept: Option<(String, String, String)>, pub palette_open: bool, pub palette_query: String, /// Set when the palette's shortcut, its command or the search icon opens or closes the palette, @@ -1369,6 +1374,7 @@ impl Default for UiState { replace_font_warning: None, last_find: None, status_notes: None, + status_kept: None, palette_open: false, palette_query: String::new(), palette_toggled: false, diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..c0943f697d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3564,6 +3564,11 @@ given and show none. These limits are VectorCraft's own values. {"name":"run_command","arguments":{"command":"app.toast","params":{"message":"Exported 4 artboards","level":"success"}}} ``` +A filter or plug-in command that only reports what it did needs neither `app.toast` nor any permission: its output's +`notice` ([plug-ins](plugins.md#output)) comes back in the run's result, and the desktop app and the web build show it +in the status bar as `Plug-in “name”: notice` once the output is applied. A run that fails, is refused or is canceled +shows no notice. + ## Navigator panel options The Navigator panel menu's Panel Options… opens the `navigatorPanelOptions` dialog (fields `color`, `solidDashes`), @@ -13245,7 +13250,10 @@ while it changes it, so installs, removals, grants and plug-in settings from two be locked, `plugin.install` and `plugin.remove` fail and change nothing: `plugin.install {path | dataBase64}` installs one, `plugin.list` / `plugin.info {id}` describe them (parameters, schema, defaults). An object filter runs on the selected paths and compound paths with `plugin.run {id, params}` (one -undo step; it may change, delete or add objects, and the result is selected). A filter whose manifest lists `inputs` +undo step; it may change, delete or add objects, and the result is selected) → `{plugin, ids, notice?}`. `notice` is +the text the filter's output reports in its `notice` key, escaped and cut at 200 characters +([plug-ins](plugins.md#output)); it is returned only when the output was applied, and the desktop app shows it in the +status bar after the plug-in's name. A filter whose manifest lists `inputs` (`type`, `image`, `symbolInstance`; `inputs` in its `plugin.list` entry) also lists `doc.read` in its `permissions`, so installing it needs a person's approval. It is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs over one run (an object that doesn't fit what the objects @@ -13363,8 +13371,8 @@ value or the folder the preference already holds, and the web build does not che A filter or live effect may declare commands of its own ([plugins.md](plugins.md#commands)): each is the command `plugin..` while the plug-in is installed, listed by `command_list` and in its `plugin.list` entry (`commands: [{id, command, label, params, paramsSchema}]`). Run it with `{ids?, params?}` (its parameters may also -be top-level keys): the parameters are checked before the plug-in runs, a run is one undo step named after the -command, and a run that traps or runs out of its instruction budget returns an error that starts with the plug-in's +be top-level keys) → `{plugin, command, ids, notice?}`, with `notice` as `plugin.run` returns it: the parameters are +checked before the plug-in runs, a run is one undo step named after the command, and a run that traps or runs out of its instruction budget returns an error that starts with the plug-in's name and the command's label and leaves the document and the undo history as they were. For `plugin.run` and plug-in commands, `ids` left out or null means the selection, and an `ids` that is not a list of object ids is an error. diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..709baf3c80 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -792,6 +792,18 @@ under the plug-in's id, and hosts from before `documentData` keep it when they s document, so it can read what every plug-in keeps there, not only its own. A live effect isn't given it: its geometry is worked out from the object alone. +To report what a run did, a filter or a plug-in command adds `notice`: one string, such as +`{"objects": [...], "notice": "Selected 12 objects"}`. It needs no permission and no host import. Once the output is +applied, the desktop app and the web build show it in the status bar as `Plug-in “name”: notice`, the plug-in's name +first, and `plugin.run` and the plug-in command return it as `notice` in their result. The host trims the white space around it, writes control, bidirectional and line +separator characters as `\u{202E}` escapes and cuts it at 200 characters, escapes included, ending it with `…`. Each run +reports at most one notice, and a later status message replaces it. A `notice` that is not a string or has no visible +character refuses the whole output, and nothing changes. A run that declines, fails, is refused, is canceled or +finishes after the document changed shows none; an output that changes nothing still shows its notice. The status +bar translates the words around the notice, never the notice itself. A live effect's +`notice` is ignored, since it runs whenever its object is drawn. These limits are VectorCraft's own values. Hosts +from before `notice` ignore it. + For a **live effect**, the geometry of every returned object's `path` (their subpaths, in order) replaces the object's; the rest is ignored (the object keeps its own appearance). An empty list removes the geometry. A live effect that declares `paintOutput` returns painted pieces instead ([below](#painted-live-effects)). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..cb60fec233 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1047,6 +1047,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`. + - Plug-in run notices: a filter or plug-in command's output may report a `notice`, which needs no permission; once the output is applied, `plugin.run` and the command return it and the status bar shows it as `Plug-in “name”: notice`, escaped, cut at 200 characters and never translated, and a run that fails or is refused shows none. VectorCraft's own API and limits. Tests: `objects::tests::notice_is_escaped_capped_and_checked` in `vectorcraft-plugins`, `a_filter_s_notice_is_returned_once_its_output_is_applied` and `a_plugin_command_returns_its_run_s_notice` in `vectorcraft-engine`, `plugin_notice_shows_after_the_plug_in_s_name_and_is_never_translated` in `vectorcraft-ui-egui`. - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. - Saves, Export for Screens and Package under `--automation-read-root`: a save without a path leaves the document's own file out of its reply, and a save without a path known leaves out the suggested folder, when they are outside the read roots; Export for Screens into an export preset's folder outside them lists its files relative to that folder and names that folder by its name in an error, and the export settings and saved presets leave out a folder outside them when read or exported; Package's report and warnings, and Document Info's linked images, name a file outside them by its file name. A path the client gives stays in the reply. `crates/engine/src/tests/save.rs`, `crates/engine/src/cmd/fileio/tests_screens.rs`, `crates/engine/src/tests/package.rs`, `crates/ui-egui/src/tests/automation.rs`. - Errors under `--automation-read-root`: a refused save without a path and `file.revert` (also as an `action.batch` step), `script.listInstalled` and `links.relink {copy}` name the document's own file, the Scripts folder or the document's folder by its file name when it is outside the read roots, and keep the roots and the reason; `links.relink`'s copies name such a file by its file name too. A path the client gives stays whole. `crates/engine/src/tests/save.rs` (`pathless_save_rejection_hides_document_folder`), `crates/engine/src/cmd/fileio/action_batch.rs`, `crates/engine/src/tests/links.rs`, `crates/engine/src/tests/script_folder.rs`. From 891dc8006da10e02518eb8204ca81eff198abacd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:39:06 -0800 Subject: [PATCH 034/101] Plug-ins: invisible notices are refused, and batch steps show their notice A filter's `notice` made only of default-ignorable characters that the host keeps as they are (U+034F combining grapheme joiner, the Hangul fillers, variation selectors, invisible operators, tags and the like) was accepted and showed an empty status message. Such a notice now refuses the output, as one of only zero-width characters already did. The visible character must also fall within the part the status bar shows: a notice whose visible text comes after the 200-character cut is refused instead of showing only the ellipsis. Text with a visible character keeps these characters, and its bidirectional ones are still escaped. A painted live effect that returned `notice` was refused and drew its input unchanged, while the docs said the key is ignored. The painted decoder now ignores a top-level `notice` and still refuses any other unknown top-level key; the message and its catalog rows say so. A plug-in step of an action or a `command.batch` now shows its notice in the status bar too; when several steps report one, the last shows. The run's result carries `pluginName`, the name of the plug-in that ran, next to `notice`, so the status bar names the right plug-in even when a later step of the batch removes or replaces it. The `plugin.run` and plug-in command params text lists the new keys. Docs: docs/plugins.md, docs/mcp.md. --- crates/engine/src/cmd/plugin.rs | 14 ++++---- crates/engine/src/tests/plugins.rs | 6 ++-- crates/plugins/src/objects.rs | 56 ++++++++++++++++++++++++++--- crates/plugins/src/objects/tests.rs | 21 ++++++++++- crates/plugins/src/painted.rs | 8 ++--- crates/plugins/src/painted/tests.rs | 15 ++++++++ crates/ui-egui/src/chrome/tests.rs | 18 ++++++++-- 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 +- crates/ui-egui/src/plugin_runs.rs | 34 ++++++++++++++---- docs/mcp.md | 11 +++--- docs/plugins.md | 15 +++++--- 35 files changed, 187 insertions(+), 61 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 8fbec2ad2d..e8bc28da3d 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -359,9 +359,10 @@ impl FilterRun { if let Some(cmd) = &self.command { out["command"] = json!(cmd.id); } - // Only an output that was applied reports its notice. + // Only an output that was applied reports its notice, with the name of the plug-in that ran. if let Some(notice) = notice { out["notice"] = json!(notice); + out["pluginName"] = json!(m.name); } Ok(out) } @@ -377,8 +378,9 @@ fn not_granted(name: &str, permission: Permission) -> EngineError { /// parameters and `_context` (what it keeps with the document included), and applies its output as /// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with /// what it keeps with the document from now on: the output handed in for this very run when there -/// is one ([`FilterRun::hand_in`]), else the plug-in's, run now. → `{plugin, ids, notice?}`: what it -/// made or changed, which is then selected, and the output's `notice` once it was applied. +/// is one ([`FilterRun::hand_in`]), else the plug-in's, run now. → `{plugin, ids, notice?, +/// pluginName?}`: what it made or changed, which is then selected, and the output's `notice` once it +/// was applied, with the plug-in's name. fn run(s: &mut Session, p: &Value) -> Result { // An output handed in is for this run only (the app hands it in just before), whatever it does. let handed = s.plugin_output.take(); @@ -488,7 +490,7 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec { fields.push_str(own); } let params = format!( - "{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step → {{plugin, command, ids, notice?}}", + "{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step → {{plugin, command, ids, notice?, pluginName?}} (pluginName, the plug-in's name, comes with notice)", m.id, c.id ); let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); @@ -521,7 +523,7 @@ fn unrouted(_: &mut Session, _: &Value) -> Result { /// Runs plug-in command `id` (`plugin..`): a filter run of the plug-in on /// `ids` (else the selection) with the command's own parameters, checked before it runs, and /// `_context.command`, under the plug-in's permissions and budget, applied as one undo step named -/// after the command → `{plugin, command, ids, notice?}`. A run that fails (a trap, an exhausted +/// after the command → `{plugin, command, ids, notice?, pluginName?}`. A run that fails (a trap, an exhausted /// budget, an output it may not make) leaves the document as it was, and the error names the /// plug-in and the command. pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result { @@ -1293,7 +1295,7 @@ pub fn specs() -> Vec { "Run Plug-in", [], None, - "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}", + "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)", has_doc, run ), diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 802a5f9c32..755e78d5cd 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -204,7 +204,7 @@ fn failing_plugins_leave_the_document_and_history_alone() { } /// A filter's output may report a `notice`, which `plugin.run` returns once the output is applied, -/// escaped and capped by the host. It needs no permission: a filter granted none reports one too. +/// escaped and capped by the host, with the plug-in's name as `pluginName`. It needs no permission: a filter granted none reports one too. /// A `notice` that is not a string refuses the output, and the document and history stay as they /// were. #[test] @@ -215,6 +215,7 @@ fn a_filter_s_notice_is_returned_once_its_output_is_applied() { install(&mut s, &asking(quiet, "[]", &json!({"objects": [], "notice": "Nothing to tidy"}))); let r = run(&mut s, "plugin.run", json!({"id": quiet})); assert_eq!((&r["plugin"], &r["notice"]), (&json!(quiet), &json!("Nothing to tidy"))); + assert_eq!(r["pluginName"], json!(format!("Test {quiet}"))); let reading = |s: &mut Session, id: &str, output: &Value| { let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, output)); run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})) @@ -227,7 +228,8 @@ fn a_filter_s_notice_is_returned_once_its_output_is_applied() { assert_eq!(shown.chars().count(), vectorcraft_plugins::objects::MAX_NOTICE_CHARS); let plain = "test.engine.notice.plain"; reading(&mut s, plain, &json!({"objects": [{"id": id}]})); - assert!(run(&mut s, "plugin.run", json!({"id": plain, "ids": [id]})).get("notice").is_none()); + let r = run(&mut s, "plugin.run", json!({"id": plain, "ids": [id]})); + assert!(r.get("notice").is_none() && r.get("pluginName").is_none(), "{r}"); let bad = "test.engine.notice.bad"; install(&mut s, &asking(bad, "[]", &json!({"objects": [], "notice": 3}))); let before = s.doc().unwrap().doc.clone(); diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 0fdefc15e7..4f2e0fc96c 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -833,17 +833,65 @@ pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans) /// The `notice` of output `v`: `None` when it has none (or `null`), else its text without the /// white space around it, as [`crate::permissions::display_text`] shows plug-in text (control, /// bidirectional formatting and separator characters escaped) and at most [`MAX_NOTICE_CHARS`] -/// characters. A `notice` that is not a string, or has no character besides white space, control -/// and zero-width ones, is an error. +/// characters. A `notice` that is not a string, or whose shown part has no character besides white +/// space, control characters and the default-ignorable characters the host does not escape, is an +/// error. pub fn decode_notice(v: &Value) -> Result> { - let shows = |c: char| !c.is_whitespace() && !c.is_control() && !matches!(c, '\u{00AD}' | '\u{200B}'..='\u{200D}' | '\u{2060}' | '\u{FEFF}'); match v.get("notice") { None | Some(Value::Null) => Ok(None), - Some(Value::String(s)) if s.chars().any(shows) => Ok(Some(crate::permissions::display_text(s.trim(), MAX_NOTICE_CHARS))), + Some(Value::String(s)) if shown_part_is_visible(s.trim()) => Ok(Some(crate::permissions::display_text(s.trim(), MAX_NOTICE_CHARS))), Some(_) => Err(Error::Output("`notice` must be a string with visible text".into())), } } +/// Does the part of notice `s` that [`crate::permissions::display_text`] keeps within +/// [`MAX_NOTICE_CHARS`], escapes counted and room left for the `…` when it cuts, hold a character +/// that draws something? +fn shown_part_is_visible(s: &str) -> bool { + let shows = |c: char| !c.is_whitespace() && !c.is_control() && !draws_nothing(c); + let width = |c: char| crate::permissions::display_text(c.encode_utf8(&mut [0; 4]), usize::MAX).chars().count(); + // Characters written through the end of `c`, and through the first visible character. + let mut used = 0; + let mut visible_by = None; + for c in s.chars() { + used += width(c); + if visible_by.is_none() && shows(c) { + visible_by = Some(used); + } + if used > MAX_NOTICE_CHARS { + break; + } + } + visible_by.is_some_and(|end| used <= MAX_NOTICE_CHARS || end < MAX_NOTICE_CHARS) +} + +/// Is `c` one of Unicode's default-ignorable characters (soft hyphen, zero-width and invisible +/// characters, fillers, variation selectors, tags) that [`crate::permissions::display_text`] keeps +/// as it is, so it draws nothing? The bidirectional ones it escapes are not among them. +fn draws_nothing(c: char) -> bool { + matches!( + c, + '\u{00AD}' + | '\u{034F}' + | '\u{115F}' + | '\u{1160}' + | '\u{17B4}' + | '\u{17B5}' + | '\u{180B}'..='\u{180F}' + | '\u{200B}'..='\u{200D}' + | '\u{2060}'..='\u{2065}' + | '\u{206A}'..='\u{206F}' + | '\u{3164}' + | '\u{FE00}'..='\u{FE0F}' + | '\u{FEFF}' + | '\u{FFA0}' + | '\u{FFF0}'..='\u{FFF8}' + | '\u{1BCA0}'..='\u{1BCA3}' + | '\u{1D173}'..='\u{1D17A}' + | '\u{E0000}'..='\u{E0FFF}' + ) +} + /// Parses a plug-in's objects: `{"objects": [...]}`, or `{"error": "message"}` when the plug-in /// declined (the message reaches the user). A live effect's other keys don't matter. pub fn decode(bytes: &[u8]) -> Result> { diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index c271127236..39d2d78776 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -1196,9 +1196,28 @@ fn notice_is_escaped_capped_and_checked() { // Escapes count toward the limit, so a notice of right-to-left overrides stays within it too. let escaped = out(Some(json!("\u{202E}".repeat(10_000)))).unwrap().unwrap_or_default(); assert!(escaped.chars().count() <= MAX_NOTICE_CHARS && !escaped.contains('\u{202E}'), "{escaped}"); - for bad in [json!(""), json!(" \t\n "), json!("\u{200B}\u{FEFF}"), json!(12), json!(["a"]), json!({"text": "a"}), json!(true)] { + for bad in [ + json!(""), + json!(" \t\n "), + json!("\u{200B}\u{FEFF}"), + json!("\u{034F}"), + json!("\u{3164}\u{FE0F}\u{E0041}"), + // The visible text comes after the cut, so the status bar would show only the `…`. + json!(format!("{}AB", "\u{200B}".repeat(MAX_NOTICE_CHARS - 1))), + json!(format!("{}A", "\u{7}".repeat(MAX_NOTICE_CHARS / 8))), + json!(12), + json!(["a"]), + json!({"text": "a"}), + json!(true), + ] { assert!(matches!(out(Some(bad.clone())), Err(Error::Output(ref e)) if e.contains("`notice`")), "{bad}"); } + // Text with a visible character keeps the invisible ones, and its bidirectional ones escaped. + assert_eq!(out(Some(json!("\u{2067}Done\u{034F}"))).unwrap().as_deref(), Some("\\u{2067}Done\u{034F}")); + // A visible character in the last place the limit shows, whole or before the `…`, is enough. + let pad = "\u{200B}".repeat(MAX_NOTICE_CHARS - 2); + assert_eq!(out(Some(json!(format!("{pad}\u{200B}A")))).unwrap(), Some(format!("{pad}\u{200B}A"))); + assert_eq!(out(Some(json!(format!("{pad}ABC")))).unwrap(), Some(format!("{pad}A…"))); // A decline is still a decline. assert!(matches!(decode_output(br#"{"error": "No pens.", "notice": "Done"}"#), Err(Error::Failed(_)))); } diff --git a/crates/plugins/src/painted.rs b/crates/plugins/src/painted.rs index 484e761677..e7ed51e225 100644 --- a/crates/plugins/src/painted.rs +++ b/crates/plugins/src/painted.rs @@ -47,8 +47,8 @@ pub enum Scope { } /// Parses and checks a painted result: `{"objects": [...]}`, or `{"error": "message"}` when the -/// plug-in declined. `rule` is the fill rule a piece without `fillRule` takes. Any other top-level -/// key, an unknown key in a piece, stroke or paint, a list or count past its limit, a number out of +/// plug-in declined. `rule` is the fill rule a piece without `fillRule` takes. A top-level `notice` +/// is ignored. Any other top-level key, an unknown key in a piece, stroke or paint, a list or count past its limit, a number out of /// range or a paint of the wrong form refuses the whole result, naming the field. pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result> { let v: Value = serde_json::from_slice(bytes).map_err(|e| out_err("output", format!("not JSON: {e}")))?; @@ -56,8 +56,8 @@ pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result> return Err(e); } let top = v.as_object().ok_or_else(|| out_err("output", "expected {\"objects\": [...]}"))?; - if let Some(k) = top.keys().find(|k| !matches!(k.as_str(), "objects" | "error")) { - return Err(out_err(k, "a painted live effect returns only `objects`")); + if let Some(k) = top.keys().find(|k| !matches!(k.as_str(), "objects" | "error" | "notice")) { + return Err(out_err(k, "a painted live effect returns only `objects` and `notice`")); } let objects = top.get("objects").and_then(Value::as_array).ok_or_else(|| out_err("objects", "expected {\"objects\": [...]}"))?; if objects.len() > MAX_OBJECTS { diff --git a/crates/plugins/src/painted/tests.rs b/crates/plugins/src/painted/tests.rs index 59acf18521..471c12ea48 100644 --- a/crates/plugins/src/painted/tests.rs +++ b/crates/plugins/src/painted/tests.rs @@ -154,6 +154,21 @@ fn faults_refuse_the_whole_result_by_field() { assert_eq!(declined, Error::Failed("nothing to do".into())); } +/// A top-level `notice` is ignored, as a filter-only key a live effect may hand back; other +/// unknown top-level keys still refuse the result. +#[test] +fn a_notice_is_ignored_and_other_top_level_keys_refused() { + let ok = json!({"path": square(), "fills": [red()]}); + let decode_top = |top: Value| decode(&serde_json::to_vec(&top).unwrap(), Scope::Object, FillRule::NonZero); + let pieces = decode_top(json!({"objects": [ok], "notice": "Done"})).unwrap(); + assert_eq!(pieces.len(), 1); + assert_eq!(decode_top(json!({"objects": [ok], "notice": 12})).unwrap().len(), 1); + for key in ["note", "notices", "message"] { + let e = decode_top(json!({"objects": [ok], key: "Done"})).unwrap_err().to_string(); + assert!(e.contains(&format!("{key}:")) && e.contains("returns only `objects` and `notice`"), "{key}: {e}"); + } +} + /// A key a paint does not have, at any level of it, refuses the result and is named; it is not /// dropped. #[test] diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index fc902f4dd7..bac3171ea4 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1026,9 +1026,21 @@ fn plugin_notice_shows_after_the_plug_in_s_name_and_is_never_translated() { app.status(""); assert!(app.run("plugin.run", json!({"id": bad})).is_err()); assert!(!app.ui.status.starts_with("Plug-in “"), "{}", app.ui.status); - for id in [id, bad] { - app.run("plugin.remove", json!({"id": id})).unwrap(); - } + // A plug-in step of a batch, as an action plays it, shows its notice too. + app.status(""); + app.replay("command.batch", json!({"commands": [{"command": "plugin.run", "params": {"id": id}}, {"command": "select.none"}]})).unwrap(); + assert_eq!(app.ui.status, format!("Plug-in “Test {id}”: invalid array length")); + // A batch without a plug-in step leaves the status bar as it is. + app.status("kept"); + app.run("command.batch", json!({"commands": [{"command": "select.none"}]})).unwrap(); + assert_eq!(app.ui.status, "kept"); + // The notice keeps the plug-in's name when a later step of the batch removes the plug-in. + app.status(""); + let run_and_remove = json!({"commands": [{"command": "plugin.run", "params": {"id": id}}, {"command": "plugin.remove", "params": {"id": id}}]}); + app.run("command.batch", run_and_remove).unwrap(); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + assert_eq!(app.ui.status, format!("Plug-in “Test {id}”: invalid array length")); + app.run("plugin.remove", json!({"id": bad})).unwrap(); } /// The message of an open that starts with a line about its linked files lists the open's notes on diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 14e94525f4..fdf2f6cf67 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7763,7 +7763,7 @@ variable-list-end {0}, {1} {0} i {1} @msg a list of {min_items} to {max_items} numbers una llista de {min_items} a {max_items} nombres @msg a new object needs a `path` un objecte nou necessita un `path` @msg a number un nombre -@msg a painted live effect returns only `objects` un efecte dinàmic de pintura només retorna `objects` +@msg a painted live effect returns only `objects` and `notice` un efecte dinàmic de pintura només retorna `objects` i `notice` @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` una peça d’un efecte dinàmic de pintura només té `path`, `fillRule`, `fills` i `strokes` @msg a read-only object was left out s’ha omès un objecte de només lectura @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given s’ha omès un objecte de només lectura: retorneu-lo com a {{"id": …}} sol o tal com s’ha rebut diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a0e98d061a..7b74d9dcd8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7373,7 +7373,7 @@ axis Y Axis osa Y @msg a list of {min_items} to {max_items} numbers seznam {min_items} až {max_items} čísel @msg a new object needs a `path` nový objekt potřebuje `path` @msg a number číslo -@msg a painted live effect returns only `objects` malující živý efekt vrací jen `objects` +@msg a painted live effect returns only `objects` and `notice` malující živý efekt vrací jen `objects` a `notice` @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` část malujícího živého efektu má jen `path`, `fillRule`, `fills` a `strokes` @msg a read-only object was left out objekt jen pro čtení byl vynechán @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given objekt jen pro čtení byl vynechán: vraťte ho jako samotné {{"id": …}} nebo tak, jak byl předán diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index fc1b9c9c02..1cbbdc8b57 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -604,7 +604,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg a list of {min_items} to {max_items} numbers en liste med {min_items} til {max_items} tal @msg a new object needs a `path` et nyt objekt kræver en `path` @msg a number et tal -@msg a painted live effect returns only `objects` en malet live-effekt returnerer kun `objects` +@msg a painted live effect returns only `objects` and `notice` en malet live-effekt returnerer kun `objects` og `notice` @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` et stykke fra en malet live-effekt har kun `path`, `fillRule`, `fills` og `strokes` @msg a read-only object was left out et skrivebeskyttet objekt blev udeladt @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given et skrivebeskyttet objekt blev udeladt: returnér det, som {{"id": …}} alene eller som det blev givet diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 0f27ad3bd6..d38b4fb0f9 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6956,7 +6956,7 @@ axis Y Axis Y-Achse @msg a list of {min_items} to {max_items} numbers eine Liste von {min_items} bis {max_items} Zahlen @msg a new object needs a `path` ein neues Objekt braucht einen `path` @msg a number eine Zahl -@msg a painted live effect returns only `objects` ein malender Live-Effekt gibt nur `objects` zurück +@msg a painted live effect returns only `objects` and `notice` ein malender Live-Effekt gibt nur `objects` und `notice` zurück @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` ein Teil eines malenden Live-Effekts hat nur `path`, `fillRule`, `fills` und `strokes` @msg a read-only object was left out ein schreibgeschütztes Objekt wurde weggelassen @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given ein schreibgeschütztes Objekt wurde weggelassen: Geben Sie es zurück, als {{"id": …}} allein oder so, wie es übergeben wurde diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b61deb1f47..ba2727e5e6 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7363,7 +7363,7 @@ axis Y Axis Άξονας Y @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 returns only `objects` and `notice` ένα ζωντανό εφέ βαφής επιστρέφει μόνο `objects` και `notice` @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": …}} μόνο ή όπως δόθηκε diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2806acd349..ca85adc53f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7349,7 +7349,7 @@ axis Y Axis Eje Y @msg a list of {min_items} to {max_items} numbers una lista de {min_items} a {max_items} números @msg a new object needs a `path` un objeto nuevo necesita un `path` @msg a number un número -@msg a painted live effect returns only `objects` un efecto dinámico de pintura solo devuelve `objects` +@msg a painted live effect returns only `objects` and `notice` un efecto dinámico de pintura solo devuelve `objects` y `notice` @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` una pieza de un efecto dinámico de pintura solo tiene `path`, `fillRule`, `fills` y `strokes` @msg a read-only object was left out se omitió un objeto de solo lectura @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given se omitió un objeto de solo lectura: devuélvalo como {{"id": …}} solo o tal como se recibió diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 9f1a8e34bb..713989649b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7440,7 +7440,7 @@ axis Y Axis Y-akseli @msg a list of {min_items} to {max_items} numbers {min_items}-{max_items} luvun luettelo @msg a new object needs a `path` uusi objekti tarvitsee kentän `path` @msg a number luku -@msg a painted live effect returns only `objects` maalaava live-tehoste palauttaa vain kentän `objects` +@msg a painted live effect returns only `objects` and `notice` maalaava live-tehoste palauttaa vain kentät `objects` ja `notice` @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` maalaavan live-tehosteen osalla on vain `path`, `fillRule`, `fills` ja `strokes` @msg a read-only object was left out vain luku -objekti jätettiin pois @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given vain luku -objekti jätettiin pois: palauta se pelkkänä {{"id": …}}-muotona tai sellaisena kuin se annettiin diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index d5ebc7f6cd..0ccc61c74e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7369,7 +7369,7 @@ axis Y Axis Axe Y @msg a list of {min_items} to {max_items} numbers une liste de {min_items} à {max_items} nombres @msg a new object needs a `path` un nouvel objet nécessite un `path` @msg a number un nombre -@msg a painted live effect returns only `objects` un effet dynamique de peinture renvoie seulement `objects` +@msg a painted live effect returns only `objects` and `notice` un effet dynamique de peinture renvoie seulement `objects` et `notice` @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` une pièce d’un effet dynamique de peinture a seulement `path`, `fillRule`, `fills` et `strokes` @msg a read-only object was left out un objet en lecture seule a été omis @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given un objet en lecture seule a été omis : renvoyez-le, sous la forme {{"id": …}} seul ou tel qu’il a été fourni diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cd015d705e..cd04259684 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6555,7 +6555,7 @@ arrowhead Feather पंख @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 returns only `objects` and `notice` पेंट करने वाला लाइव इफ़ेक्ट केवल `objects` और `notice` लौटाता है @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": …}} के रूप में या जैसा दिया गया था वैसा लौटाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 61f02f0851..19373b4b83 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7358,7 +7358,7 @@ axis Y Axis Y tengely @msg a list of {min_items} to {max_items} numbers {min_items}-{max_items} számból álló lista @msg a new object needs a `path` az új objektumhoz `path` kell @msg a number szám -@msg a painted live effect returns only `objects` a festő élő effektus csak `objects` értéket ad vissza +@msg a painted live effect returns only `objects` and `notice` a festő élő effektus csak `objects` és `notice` értéket ad vissza @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` a festő élő effektus darabjának csak `path`, `fillRule`, `fills` és `strokes` kulcsa van @msg a read-only object was left out kimaradt egy írásvédett objektum @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given kimaradt egy írásvédett objektum: adja vissza önmagában {{"id": …}} formában vagy úgy, ahogy megkapta diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 5eabf8a13c..8f6486bd9c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -486,7 +486,7 @@ @msg a list of {min_items} to {max_items} numbers daftar berisi {min_items} sampai {max_items} angka @msg a new object needs a `path` objek baru memerlukan `path` @msg a number angka -@msg a painted live effect returns only `objects` efek langsung yang dicat hanya mengembalikan `objects` +@msg a painted live effect returns only `objects` and `notice` efek langsung yang dicat hanya mengembalikan `objects` dan `notice` @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` potongan efek langsung yang dicat hanya memiliki `path`, `fillRule`, `fills` dan `strokes` @msg a read-only object was left out objek baca-saja dihilangkan @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given objek baca-saja dihilangkan: kembalikan objek itu, sebagai {{"id": …}} saja atau seperti yang diberikan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a0e4fecb4f..1d39078f67 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6995,7 +6995,7 @@ axis Y Axis Asse Y @msg a list of {min_items} to {max_items} numbers un elenco da {min_items} a {max_items} numeri @msg a new object needs a `path` un nuovo oggetto richiede un `path` @msg a number un numero -@msg a painted live effect returns only `objects` un effetto dinamico di pittura restituisce solo `objects` +@msg a painted live effect returns only `objects` and `notice` un effetto dinamico di pittura restituisce solo `objects` e `notice` @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` un pezzo di un effetto dinamico di pittura ha solo `path`, `fillRule`, `fills` e `strokes` @msg a read-only object was left out è stato omesso un oggetto di sola lettura @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given è stato omesso un oggetto di sola lettura: restituiscilo come {{"id": …}} da solo o così come è stato fornito diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 788733b3f1..6c9b5bf3b0 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7070,7 +7070,7 @@ axis Y Axis Y 軸 @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 returns only `objects` and `notice` ペイント型のライブ効果が返すのは `objects` と `notice` だけです @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": …}} だけの形か、渡されたとおりの形で返してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index dab67fdd92..1ab1c80788 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9476,7 +9476,7 @@ axis Y Axis Y ღერძი @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 returns only `objects` and `notice` მხატვრული ცოცხალი ეფექტი აბრუნებს მხოლოდ `objects`-სა და `notice`-ს @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": …}}-ის სახით ან ისე, როგორც მიიღეთ diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f30279162f..c2b2b95225 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6967,7 +6967,7 @@ axis Y Axis Y축 @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 returns only `objects` and `notice` 페인트형 라이브 효과는 `objects`와 `notice`만 반환합니다 @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": …}}만 있는 형태나 받은 그대로 반환하십시오 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 766b2f8553..84b95f01bf 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -450,7 +450,7 @@ liquify-list-end {0}, {1} {0} en {1} @msg a list of {min_items} to {max_items} numbers een lijst met {min_items} tot {max_items} getallen @msg a new object needs a `path` een nieuw object heeft een `path` nodig @msg a number een getal -@msg a painted live effect returns only `objects` een geschilderd live-effect geeft alleen `objects` terug +@msg a painted live effect returns only `objects` and `notice` een geschilderd live-effect geeft alleen `objects` en `notice` terug @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` een stuk van een geschilderd live-effect heeft alleen `path`, `fillRule`, `fills` en `strokes` @msg a read-only object was left out een alleen-lezen object is weggelaten @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given een alleen-lezen object is weggelaten: geef het terug, als alleen {{"id": …}} of zoals het is gegeven diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 98329f7a76..6723399177 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7228,7 +7228,7 @@ axis Y Axis Oś Y @msg a list of {min_items} to {max_items} numbers listą od {min_items} do {max_items} liczb @msg a new object needs a `path` nowy obiekt wymaga `path` @msg a number liczbą -@msg a painted live effect returns only `objects` malujący efekt dynamiczny zwraca tylko `objects` +@msg a painted live effect returns only `objects` and `notice` malujący efekt dynamiczny zwraca tylko `objects` i `notice` @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` element malującego efektu dynamicznego ma tylko `path`, `fillRule`, `fills` i `strokes` @msg a read-only object was left out pominięto obiekt tylko do odczytu @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given pominięto obiekt tylko do odczytu: zwróć go jako samo {{"id": …}} lub w postaci, w jakiej został przekazany diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index edfd302666..5ddb3f83d0 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7272,7 +7272,7 @@ axis Y Axis Eixo Y @msg a list of {min_items} to {max_items} numbers uma lista de {min_items} a {max_items} números @msg a new object needs a `path` um objeto novo precisa de um `path` @msg a number um número -@msg a painted live effect returns only `objects` um efeito dinâmico de pintura retorna apenas `objects` +@msg a painted live effect returns only `objects` and `notice` um efeito dinâmico de pintura retorna apenas `objects` e `notice` @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` uma peça de um efeito dinâmico de pintura tem apenas `path`, `fillRule`, `fills` e `strokes` @msg a read-only object was left out um objeto somente leitura foi omitido @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given um objeto somente leitura foi omitido: retorne-o como {{"id": …}} sozinho ou como foi recebido diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fb6326f53b..a7a6dd1554 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6995,7 +6995,7 @@ axis Y Axis Ось Y @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 returns only `objects` and `notice` рисующий динамический эффект возвращает только `objects` и `notice` @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": …}} или в том виде, в каком он был передан diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6794b14981..23fc0ac5de 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7385,7 +7385,7 @@ axis Y Axis Y-axel @msg a list of {min_items} to {max_items} numbers en lista med {min_items} till {max_items} tal @msg a new object needs a `path` ett nytt objekt behöver en `path` @msg a number ett tal -@msg a painted live effect returns only `objects` en målande live-effekt returnerar bara `objects` +@msg a painted live effect returns only `objects` and `notice` en målande live-effekt returnerar bara `objects` och `notice` @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` en del av en målande live-effekt har bara `path`, `fillRule`, `fills` och `strokes` @msg a read-only object was left out ett skrivskyddat objekt utelämnades @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given ett skrivskyddat objekt utelämnades: returnera det som enbart {{"id": …}} eller som det gavs diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d146fc8a3e..7343de5f0b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7445,7 +7445,7 @@ axis Y Axis Y ekseni @msg a list of {min_items} to {max_items} numbers {min_items} ile {max_items} arasında sayıdan oluşan bir liste @msg a new object needs a `path` yeni bir nesnenin `path` değerine ihtiyacı vardır @msg a number bir sayı -@msg a painted live effect returns only `objects` boyama türü canlı efekt yalnızca `objects` döndürür +@msg a painted live effect returns only `objects` and `notice` boyama türü canlı efekt yalnızca `objects` ve `notice` döndürür @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` boyama türü canlı efektin bir parçasında yalnızca `path`, `fillRule`, `fills` ve `strokes` bulunur @msg a read-only object was left out salt okunur bir nesne atlandı @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given salt okunur bir nesne atlandı: onu yalnızca {{"id": …}} olarak veya verildiği gibi döndürün diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d6a0ea26e4..a2aa700a24 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6977,7 +6977,7 @@ axis Y Axis Вісь Y @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 returns only `objects` and `notice` малювальний динамічний ефект повертає лише `objects` і `notice` @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": …}} або в тому вигляді, у якому його передано diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index bca4098192..1f02f2da6a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7024,7 +7024,7 @@ axis Y Axis Trục Y @msg a list of {min_items} to {max_items} numbers một danh sách gồm {min_items} đến {max_items} số @msg a new object needs a `path` đối tượng mới cần một `path` @msg a number một số -@msg a painted live effect returns only `objects` hiệu ứng động kiểu tô chỉ trả về `objects` +@msg a painted live effect returns only `objects` and `notice` hiệu ứng động kiểu tô chỉ trả về `objects` và `notice` @msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` một phần của hiệu ứng động kiểu tô chỉ có `path`, `fillRule`, `fills` và `strokes` @msg a read-only object was left out một đối tượng chỉ đọc đã bị bỏ sót @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given một đối tượng chỉ đọc đã bị bỏ sót: hãy trả lại nó dưới dạng chỉ {{"id": …}} hoặc như khi được nhận diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3914f7423b..cb6eba1378 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7205,7 +7205,7 @@ axis Y Axis Y 轴 @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 returns only `objects` and `notice` 绘制型实时效果只返回 `objects` 和 `notice` @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": …}} 或原样返回它 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 11d1a5df17..afdde7c9e9 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7026,7 +7026,7 @@ axis Y Axis Y 軸 @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 returns only `objects` and `notice` 繪製型即時效果只傳回 `objects` 和 `notice` @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": …}} 或原樣傳回它 diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index e5623d33fd..e0bb0dc0e0 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -156,15 +156,29 @@ fn finish(app: &mut VectorcraftApp, r: Running, done: Option) { } /// Shows in the status bar the notice of the plug-in run that command `cmd` (`plugin.run` or a -/// plug-in command) applied, with result `r`: `Plug-in “name”: notice`, the plug-in's name escaped -/// and capped as prompts show it. The notice is shown as the run returned it (escaped and capped by -/// the host) and never translated. A result without a notice leaves the status bar as it is. +/// plug-in command) applied, with result `r`: `Plug-in “name”: notice`, the name of the plug-in that +/// ran (`pluginName`) escaped and capped as prompts show it. The notice is shown as the run returned +/// it (escaped and capped by the host) and never translated. A result without a notice leaves the +/// status bar as it is. For a `command.batch`, such as an action's steps, the last plug-in run among +/// its steps with a notice shows it. pub fn show_notice(app: &mut VectorcraftApp, cmd: &str, r: &Value) { - if cmd != "plugin.run" && !vectorcraft_engine::cmd::plugin::is_command_id(cmd) { + let r = if cmd == "command.batch" { + match last_batch_notice(r) { + Some(step) => step, + None => return, + } + } else if cmd == "plugin.run" || vectorcraft_engine::cmd::plugin::is_command_id(cmd) { + r + } else { return; - } + }; let (Some(notice), Some(id)) = (r.get("notice").and_then(Value::as_str), r.get("plugin").and_then(Value::as_str)) else { return }; - let name = registry::get(id).map_or_else(|| id.to_string(), |p| p.manifest().name.trim().trim_end_matches('…').to_string()); + let name = r + .get("pluginName") + .and_then(Value::as_str) + .map(str::to_string) + .or_else(|| registry::get(id).map(|p| p.manifest().name.clone())) + .map_or_else(|| id.to_string(), |name| name.trim().trim_end_matches('…').to_string()); let name = permissions::display_text(&name, permissions::MAX_SHOWN_NAME); let status = format!("Plug-in “{name}”: {notice}"); let before = status.strip_suffix(notice).unwrap_or_default().to_string(); @@ -172,6 +186,14 @@ pub fn show_notice(app: &mut VectorcraftApp, cmd: &str, r: &Value) { app.ui.status_kept = Some((before, notice.to_string(), String::new())); } +/// The result of the last step of `command.batch` result `r` that a plug-in run with a notice gave +/// (`{plugin, ids, notice}`). +fn last_batch_notice(r: &Value) -> Option<&Value> { + r.get("results")?.as_array()?.iter().rev().find(|step| { + step.get("notice").is_some_and(Value::is_string) && step.get("plugin").is_some_and(Value::is_string) && step.get("ids").is_some() + }) +} + /// The progress window's Cancel (also Esc): every filter running in the background stops (at once when it checks /// `vc_cancelled`, else at the next slice of its budget) and changes nothing → `{cancelled: n}`. pub fn cancel_all(app: &mut VectorcraftApp) -> Value { diff --git a/docs/mcp.md b/docs/mcp.md index c0943f697d..87ae1b2f91 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13250,10 +13250,10 @@ while it changes it, so installs, removals, grants and plug-in settings from two be locked, `plugin.install` and `plugin.remove` fail and change nothing: `plugin.install {path | dataBase64}` installs one, `plugin.list` / `plugin.info {id}` describe them (parameters, schema, defaults). An object filter runs on the selected paths and compound paths with `plugin.run {id, params}` (one -undo step; it may change, delete or add objects, and the result is selected) → `{plugin, ids, notice?}`. `notice` is -the text the filter's output reports in its `notice` key, escaped and cut at 200 characters -([plug-ins](plugins.md#output)); it is returned only when the output was applied, and the desktop app shows it in the -status bar after the plug-in's name. A filter whose manifest lists `inputs` +undo step; it may change, delete or add objects, and the result is selected) → `{plugin, ids, notice?, pluginName?}`. +`notice` is the text the filter's output reports in its `notice` key, escaped and cut at 200 characters +([plug-ins](plugins.md#output)); it is returned only when the output was applied, with `pluginName`, the manifest name +of the plug-in that ran, and the desktop app shows it in the status bar after that name. A filter whose manifest lists `inputs` (`type`, `image`, `symbolInstance`; `inputs` in its `plugin.list` entry) also lists `doc.read` in its `permissions`, so installing it needs a person's approval. It is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs over one run (an object that doesn't fit what the objects @@ -13371,7 +13371,8 @@ value or the folder the preference already holds, and the web build does not che A filter or live effect may declare commands of its own ([plugins.md](plugins.md#commands)): each is the command `plugin..` while the plug-in is installed, listed by `command_list` and in its `plugin.list` entry (`commands: [{id, command, label, params, paramsSchema}]`). Run it with `{ids?, params?}` (its parameters may also -be top-level keys) → `{plugin, command, ids, notice?}`, with `notice` as `plugin.run` returns it: the parameters are +be top-level keys) → `{plugin, command, ids, notice?, pluginName?}`, with `notice` and `pluginName` as `plugin.run` +returns them: the parameters are checked before the plug-in runs, a run is one undo step named after the command, and a run that traps or runs out of its instruction budget returns an error that starts with the plug-in's name and the command's label and leaves the document and the undo history as they were. For `plugin.run` and plug-in commands, `ids` left out or null means the selection, and an `ids` that is not a list of object ids is an error. diff --git a/docs/plugins.md b/docs/plugins.md index 709baf3c80..4378aa87b0 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -795,13 +795,17 @@ is worked out from the object alone. To report what a run did, a filter or a plug-in command adds `notice`: one string, such as `{"objects": [...], "notice": "Selected 12 objects"}`. It needs no permission and no host import. Once the output is applied, the desktop app and the web build show it in the status bar as `Plug-in “name”: notice`, the plug-in's name -first, and `plugin.run` and the plug-in command return it as `notice` in their result. The host trims the white space around it, writes control, bidirectional and line +first, and `plugin.run` and the plug-in command return it as `notice` in their result, with the plug-in's name as +`pluginName`. The host trims the white space around it, writes control, bidirectional and line separator characters as `\u{202E}` escapes and cuts it at 200 characters, escapes included, ending it with `…`. Each run -reports at most one notice, and a later status message replaces it. A `notice` that is not a string or has no visible -character refuses the whole output, and nothing changes. A run that declines, fails, is refused, is canceled or +reports at most one notice, and a later status message replaces it. A plug-in step of an action or a `command.batch` +shows its notice too; when several steps report one, the last of them shows. A `notice` that is not a string, or has no visible +character in the part the status bar shows, refuses the whole output, and nothing changes; white space, control characters and the invisible +characters that are not escaped (soft hyphen, zero-width and filler characters, variation selectors, tags) do not +count as visible. A run that declines, fails, is refused, is canceled or finishes after the document changed shows none; an output that changes nothing still shows its notice. The status bar translates the words around the notice, never the notice itself. A live effect's -`notice` is ignored, since it runs whenever its object is drawn. These limits are VectorCraft's own values. Hosts +`notice`, painted or not, is ignored without being checked, since the effect runs whenever its object is drawn. These limits are VectorCraft's own values. Hosts from before `notice` ignore it. For a **live effect**, the geometry of every returned object's `path` (their subpaths, in order) replaces the @@ -822,7 +826,8 @@ is a piece drawn by itself, in the order returned, with paints of its own: ``` - `path` is required; `fillRule` defaults to the object's. `type` and `bounds` may be handed back as given and are - ignored. Any other key (`opacity`, `effects`, `guide`, `locked`, `name`, a top-level `documentData`…) refuses the + ignored, as is a top-level `notice`. Any other key (`opacity`, `effects`, `guide`, `locked`, `name`, a top-level + `documentData`…) refuses the result, as does a key that a paint, its color, a gradient stop, a gradient's placement or a freeform point does not have, such as `opacity` on a solid paint. - `fills` and `strokes` take the forms a filter returns ([Input](#input)). A piece without `fills` (or `strokes`) is From 050ddcb567602124c4fc949525cf88f348439d4e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:29:23 -0800 Subject: [PATCH 035/101] Fix #9051: Display Print Size shows 100% at the display's physical size MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With Preferences › General › Display Print Size at 100% Zoom on, 100% took 96 screen points to an inch on every display, so a ruler held to the screen measured more or less than the document said on any display of another density. The desktop app now measures the density of the display that shows the main window from the physical size the system reports (CGDisplayScreenSize on macOS, the monitor's raw DPI on Windows, the RandR output's millimeters on X11, the wl_output geometry on Wayland), and measures it again when the window moves to another display, where every document window keeps its zoom percentage so the art keeps its physical size. Actual Size, the zoom field, the zoom stops and the tab titles count 100% from that density. Where the system reports no size, or a size no display has (zero, an aspect ratio given as the size, or axes that disagree), an inch stays 96 points, as on the web. Zoom stepping takes the density from the app instead of a process-wide flag, and the last zoom stop in each direction stays in the zoom range. --- apps/vectorcraft/Cargo.toml | 8 +- apps/vectorcraft/src/app.rs | 5 + apps/vectorcraft/src/main.rs | 7 + apps/vectorcraft/src/screen_density.rs | 252 ++++++++++++++++++ apps/vectorcraft/src/windows_display_size.rs | 19 ++ crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/app.rs | 1 - crates/ui-egui/src/app/commands.rs | 1 - crates/ui-egui/src/app/view.rs | 28 ++ crates/ui-egui/src/canvas/input.rs | 6 +- crates/ui-egui/src/canvas/tests.rs | 45 +++- crates/ui-egui/src/canvas/view.rs | 13 +- crates/ui-egui/src/chrome/status_bar.rs | 2 +- crates/ui-egui/src/chrome/tabs.rs | 10 +- crates/ui-egui/src/chrome/tests.rs | 2 +- crates/ui-egui/src/control/tests.rs | 2 +- crates/ui-egui/src/doc_windows/views.rs | 9 + crates/ui-egui/src/menus/run.rs | 6 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/info.rs | 6 +- .../ui-egui/src/prefs_dialog/descriptions.rs | 5 +- crates/ui-egui/src/services.rs | 6 + crates/ui-egui/src/state.rs | 91 ++++--- docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 25 files changed, 464 insertions(+), 71 deletions(-) create mode 100644 apps/vectorcraft/src/screen_density.rs create mode 100644 apps/vectorcraft/src/windows_display_size.rs diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 0fe5804a16..a62f75ca37 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -65,8 +65,9 @@ pollster = "1" # which src/host_services.rs uses to read the path PhotoCraft registers under App Paths. # Win32_Devices_Display has `QueryDisplayConfig`, Win32_UI_ColorSystem the display's ICC profile and # Win32_System_LibraryLoader `GetProcAddress`, which src/display_profile.rs uses to read the -# display's color profile for the canvas. -windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } +# display's color profile for the canvas. Win32_UI_HiDpi has `GetDpiForMonitor`, which +# src/windows_display_size.rs uses to read a monitor's raw density for Display Print Size. +windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "Win32_UI_HiDpi", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } # The renderer's worker count follows those cores (src/windows_cores.rs). vectorcraft-render = { workspace = true } @@ -90,7 +91,8 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std" # The windows' Metal layers and the sRGB color space they are tagged with (src/mac_color_space.rs). # Zlib OR Apache-2.0 OR MIT, already in the build through wgpu with these features. objc2-quartz-core = { version = "0.3", default-features = false, features = ["std", "objc2-core-foundation", "objc2-core-graphics", "CALayer", "CAMetalLayer"] } -objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGColorSpace"] } +# CGDisplayScreenSize gives a display's physical size for Display Print Size (src/screen_density.rs). +objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGColorSpace", "CGDirectDisplay", "CGDisplayConfiguration"] } # Waits for the answer of a file dialog shown as a sheet (src/main.rs, #867). MIT OR Apache-2.0, # already in the build through eframe. pollster = "1" diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index a40eb0c92f..c93a1d0341 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -208,6 +208,11 @@ impl App { } if let Some(w) = &self.winit_window { self.display_profile.tick(w, now, self.app.session.prefs.monitor_profile_display, &self.app.display_profile, ctx); + if let Some(read) = self.screen_density.tick(w, now) + && self.app.set_screen_ppi(read) + { + ctx.request_repaint(); + } } self.app.tick(ctx); if self.pending_maximize { diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 29cb56bdfa..00e82a0298 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -67,6 +67,7 @@ mod presentation; mod printing; #[cfg(not(any(target_os = "macos", windows)))] mod quit_windows; +mod screen_density; #[cfg(not(target_os = "macos"))] mod single_instance; #[cfg(windows)] @@ -77,6 +78,8 @@ mod window_frame; mod windows_alt_codes; #[cfg(windows)] mod windows_cores; +#[cfg(windows)] +mod windows_display_size; mod windows_screen_color; mod windows_stylus; mod xwayland; @@ -140,6 +143,9 @@ struct App { monitors_listed: Option<(f64, f32)>, /// Reads the profile of the display that shows the main window, for the canvas. display_profile: display_profile::Reader, + /// Measures the density of the display that shows the main window, for Display Print Size at + /// 100% Zoom. + screen_density: screen_density::Tracker, /// When this frame's input hook started, for the hang report's frame times (`hang_watch`). frame_start: Option, /// The shortest time between the starts of two frames, while the window presents without vsync @@ -712,6 +718,7 @@ fn main() -> std::process::ExitCode { held_files, monitors_listed: None, display_profile: Default::default(), + screen_density: Default::default(), frame_start: None, min_frame, last_frame_began: None, diff --git a/apps/vectorcraft/src/screen_density.rs b/apps/vectorcraft/src/screen_density.rs new file mode 100644 index 0000000000..3a91f7f4d4 --- /dev/null +++ b/apps/vectorcraft/src/screen_density.rs @@ -0,0 +1,252 @@ +//! The density of the display that shows most of the main window, in the window's points per +//! inch, for Preferences › General › Display Print Size at 100% Zoom (`Services::screen_ppi`): +//! the display's size in points divided by the physical size the system reports for it. +//! +//! - macOS: `CGDisplayScreenSize`. +//! - Windows: `GetDpiForMonitor`'s raw density (`windows_display_size`). +//! - X11, XWayland included: the RandR output's width and height in millimeters. +//! - Wayland: the physical width and height of the compositor's `wl_output` for the display. +//! +//! A display that reports no size, or a size no display has, gives `None`, and an inch then takes +//! 96 points. The window's display is looked up once a second while the app draws, and read when +//! it changes. + +use winit::dpi::{PhysicalPosition, PhysicalSize}; +use winit::monitor::MonitorHandle; + +/// Seconds between two checks of which display shows the window. +const LOOK_EVERY: f64 = 1.0; + +/// Millimeters in an inch. +const MM_PER_INCH: f64 = 25.4; + +/// How far the horizontal and vertical densities of one display may differ, as a fraction of the +/// larger: square pixels on a display that reports its true size give two densities this close. +const AXES_AGREE: f64 = 0.1; + +/// What identifies the display and the window's scale on it between two looks. +type Shown = (Option, PhysicalPosition, PhysicalSize, u64); + +/// Keeps the density current from the main window's frames. +#[derive(Default)] +pub(crate) struct Tracker { + /// When the window's display was last looked up. + looked: Option, + /// The display read last, with the window's scale factor then. + shown: Option, +} + +impl Tracker { + /// Looks up the window's display when a look is due at `now` (seconds), and returns its + /// density (`None` inside for a display that reports no size) when the display or the + /// window's scale changed since the last reading. + pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64) -> Option> { + if self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) { + return None; + } + self.looked = Some(now); + let monitor = window.current_monitor(); + let scale = window.scale_factor(); + let shown = monitor.as_ref().map(|m| (m.name(), m.position(), m.size(), scale.to_bits())); + if shown == self.shown { + return None; + } + self.shown = shown; + let read = monitor.and_then(|m| points_per_inch(m.size(), scale, physical_mm(window, &m)?)); + match read { + Some(p) => log::info!("the window's display has {p:.1} points to an inch"), + None => log::info!("the window's display reports no physical size; an inch is 96 points"), + } + Some(read) + } +} + +/// The density, in points per inch, of a display `size` physical pixels wide and high, with the +/// window drawn at `scale` pixels to a point, that the system says is `mm` millimeters wide and +/// high. `None` for a size that is no display's: zero or less, an aspect ratio given in place of +/// the size (16 × 9, 160 × 90 and the like), axes whose densities disagree in either orientation, +/// or a density outside [`vectorcraft_ui_egui::state::SCREEN_PPI_RANGE`]. A display turned a +/// quarter turn may report the size of its panel upright, so the axes are also tried swapped. +pub(crate) fn points_per_inch(size: PhysicalSize, scale: f64, mm: [f64; 2]) -> Option { + if !(scale.is_finite() && scale > 0.0) || mm.iter().any(|v| !(v.is_finite() && *v > 0.0)) || aspect_as_size(mm) { + return None; + } + let points = [f64::from(size.width) / scale, f64::from(size.height) / scale]; + let density = |[w, h]: [f64; 2]| [points[0] / (w / MM_PER_INCH), points[1] / (h / MM_PER_INCH)]; + let agree = |[x, y]: [f64; 2]| (x - y).abs() <= AXES_AGREE * x.max(y); + let [x, y] = [density(mm), density([mm[1], mm[0]])].into_iter().find(|d| agree(*d))?; + let ppi = (x + y) / 2.0; + vectorcraft_ui_egui::state::SCREEN_PPI_RANGE.contains(&ppi).then_some(ppi) +} + +/// Whether `mm` is an aspect ratio that a display's EDID gave in place of its size: 16:9, 16:10 +/// or 4:3, in centimeters or tenths of them. +fn aspect_as_size(mm: [f64; 2]) -> bool { + const RATIOS: [[f64; 2]; 3] = [[16.0, 9.0], [16.0, 10.0], [4.0, 3.0]]; + let sorted = if mm[0] >= mm[1] { mm } else { [mm[1], mm[0]] }; + RATIOS.iter().any(|r| [1.0, 10.0].iter().any(|k| sorted == [r[0] * k, r[1] * k])) +} + +/// The physical width and height, in millimeters, the system reports for `monitor`. +#[cfg(target_os = "macos")] +fn physical_mm(_: &winit::window::Window, monitor: &MonitorHandle) -> Option<[f64; 2]> { + use winit::platform::macos::MonitorHandleExtMacOS as _; + let size = objc2_core_graphics::CGDisplayScreenSize(monitor.native_id()); + Some([size.width, size.height]) +} + +#[cfg(windows)] +fn physical_mm(_: &winit::window::Window, monitor: &MonitorHandle) -> Option<[f64; 2]> { + use winit::platform::windows::MonitorHandleExtWindows as _; + let [x, y] = crate::windows_display_size::raw_dpi(monitor.hmonitor())?; + let size = monitor.size(); + Some([f64::from(size.width) / x * MM_PER_INCH, f64::from(size.height) / y * MM_PER_INCH]) +} + +#[cfg(target_os = "linux")] +fn physical_mm(window: &winit::window::Window, monitor: &MonitorHandle) -> Option<[f64; 2]> { + use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; + let wayland = window.window_handle().ok().is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Wayland(_))); + let read = if wayland { wayland::physical_mm(monitor.name().as_deref()) } else { x11::physical_mm(monitor) }; + read.unwrap_or_else(|e| { + log::debug!("couldn't read the display's physical size: {e}"); + None + }) +} + +#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))] +fn physical_mm(_: &winit::window::Window, _: &MonitorHandle) -> Option<[f64; 2]> { + None +} + +#[cfg(target_os = "linux")] +mod x11 { + use winit::monitor::MonitorHandle; + use winit::platform::x11::MonitorHandleExtX11 as _; + use x11rb::CURRENT_TIME; + use x11rb::protocol::randr; + + /// The millimeters RandR reports for the first output of the CRTC that shows `monitor`. + pub(super) fn physical_mm(monitor: &MonitorHandle) -> Result, String> { + let (conn, _) = x11rb::connect(None).map_err(|e| format!("couldn't connect to the X11 display: {e}"))?; + let ask = |e: x11rb::errors::ConnectionError| format!("couldn't ask the X11 display: {e}"); + let crtc = randr::get_crtc_info(&conn, monitor.native_id(), CURRENT_TIME) + .map_err(ask)? + .reply() + .map_err(|e| format!("the X11 display has no such CRTC: {e}"))?; + let Some(output) = crtc.outputs.first() else { return Ok(None) }; + let info = randr::get_output_info(&conn, *output, CURRENT_TIME) + .map_err(ask)? + .reply() + .map_err(|e| format!("the X11 display has no such output: {e}"))?; + Ok(Some([f64::from(info.mm_width), f64::from(info.mm_height)])) + } +} + +#[cfg(target_os = "linux")] +mod wayland { + use wayland_client::globals::{GlobalListContents, registry_queue_init}; + use wayland_client::protocol::wl_output::{self, WlOutput}; + use wayland_client::protocol::wl_registry::{self, WlRegistry}; + use wayland_client::{Connection, Dispatch, QueueHandle}; + + /// The physical size the compositor gives for the output named `name`, asked on a connection + /// of its own; with no name, or a compositor that names no outputs, the only output's. + pub(super) fn physical_mm(name: Option<&str>) -> Result, String> { + let conn = Connection::connect_to_env().map_err(|e| format!("no Wayland compositor: {e}"))?; + let (globals, mut queue) = registry_queue_init::(&conn).map_err(|e| e.to_string())?; + let qh = queue.handle(); + let mut state = Outputs::default(); + for global in globals.contents().clone_list().into_iter().filter(|g| g.interface == "wl_output") { + // Version 4 names the output; older ones give its size only. + let output: WlOutput = globals.registry().bind(global.name, global.version.min(4), &qh, state.outputs.len()); + state.outputs.push((output, Output::default())); + } + // The compositor sends each output's geometry, name and `done` in reply to the bind. + queue.roundtrip(&mut state).map_err(|e| e.to_string())?; + let found: Vec<&Output> = state.outputs.iter().map(|(_, o)| o).collect(); + let pick = match name { + Some(name) if found.iter().any(|o| o.name.is_some()) => found.iter().find(|o| o.name.as_deref() == Some(name)), + _ if found.len() == 1 => found.first(), + _ => None, + }; + Ok(pick.and_then(|o| o.mm)) + } + + /// One output's name and physical size. + #[derive(Default)] + struct Output { + name: Option, + mm: Option<[f64; 2]>, + } + + /// The outputs bound, each with what its events gave. + #[derive(Default)] + struct Outputs { + outputs: Vec<(WlOutput, Output)>, + } + + impl Dispatch for Outputs { + fn event(_: &mut Self, _: &WlRegistry, _: wl_registry::Event, _: &GlobalListContents, _: &Connection, _: &QueueHandle) {} + } + + impl Dispatch for Outputs { + fn event(state: &mut Self, _: &WlOutput, event: wl_output::Event, index: &usize, _: &Connection, _: &QueueHandle) { + let Some((_, output)) = state.outputs.get_mut(*index) else { return }; + match event { + wl_output::Event::Geometry { physical_width, physical_height, .. } => { + output.mm = Some([f64::from(physical_width), f64::from(physical_height)]); + } + wl_output::Event::Name { name } => output.name = Some(name), + _ => {} + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A 14-inch laptop panel at twice its points: 3024 × 1964 pixels, 302 × 196 mm, draws 127 + /// points to an inch, more than the 96 a fixed inch assumes. + #[test] + fn a_laptop_panel_has_more_points_to_an_inch_than_the_reference() { + let ppi = points_per_inch(PhysicalSize::new(3024, 1964), 2.0, [302.0, 196.0]); + assert!(ppi.is_some_and(|p| p > 96.0 && (p - 1512.0 / (302.0 / MM_PER_INCH)).abs() < 1.0), "{ppi:?}"); + } + + /// The same display in a scaled mode (more points on the same glass) draws more points to an + /// inch, and at a higher scale factor fewer: the density counts the window's points. + #[test] + fn the_density_counts_points_at_the_windows_scale() { + let at = |w, h, scale| points_per_inch(PhysicalSize::new(w, h), scale, [527.0, 296.0]).unwrap_or(0.0); + assert!(at(1920, 1080, 1.0) > 0.0); + assert!(at(2560, 1440, 1.0) > at(1920, 1080, 1.0), "more pixels on the same glass"); + assert!(at(3840, 2160, 2.0) < at(3840, 2160, 1.5), "a larger scale factor makes each point larger"); + } + + /// A display turned a quarter turn whose system reports its panel's size upright still + /// measures; axes that disagree either way do not. + #[test] + fn a_turned_display_measures_and_disagreeing_axes_do_not() { + let upright = points_per_inch(PhysicalSize::new(1920, 1080), 1.0, [527.0, 296.0]); + let turned = points_per_inch(PhysicalSize::new(1080, 1920), 1.0, [527.0, 296.0]); + assert!(upright.is_some() && turned.is_some()); + assert!((upright.unwrap_or(0.0) - turned.unwrap_or(1.0)).abs() < 1e-9); + assert_eq!(points_per_inch(PhysicalSize::new(1920, 1080), 1.0, [527.0, 527.0]), None); + } + + /// Sizes no display has give no density: none, an aspect ratio in place of the size, and + /// densities past the range a display can have. + #[test] + fn reports_that_are_no_displays_size_give_no_density() { + let at = |mm| points_per_inch(PhysicalSize::new(1920, 1080), 1.0, mm); + for mm in [[0.0, 0.0], [-1.0, 300.0], [f64::NAN, 300.0], [160.0, 90.0], [16.0, 9.0], [160.0, 100.0], [40.0, 30.0], [9.0, 16.0]] { + assert_eq!(at(mm), None, "{mm:?}"); + } + assert_eq!(points_per_inch(PhysicalSize::new(1920, 1080), 0.0, [527.0, 296.0]), None, "no scale"); + assert_eq!(points_per_inch(PhysicalSize::new(100, 56), 1.0, [5270.0, 2960.0]), None, "under the range"); + assert_eq!(points_per_inch(PhysicalSize::new(7680, 4320), 1.0, [53.0, 30.0]), None, "over it"); + } +} diff --git a/apps/vectorcraft/src/windows_display_size.rs b/apps/vectorcraft/src/windows_display_size.rs new file mode 100644 index 0000000000..a46c7989b2 --- /dev/null +++ b/apps/vectorcraft/src/windows_display_size.rs @@ -0,0 +1,19 @@ +//! Windows: a monitor's raw density, the pixels per inch of the screen itself as Windows reads it +//! from the monitor, for Display Print Size at 100% Zoom (`crate::screen_density`). +//! +//! `GetDpiForMonitor` is a C API with no safe binding, hence the scoped `unsafe_code` allowance. +#![allow(unsafe_code)] + +use windows::Win32::Graphics::Gdi::HMONITOR; +use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_RAW_DPI}; + +/// The horizontal and vertical pixels per inch of the monitor winit's handle `monitor` names, or +/// `None` when Windows reports none for it. +pub(crate) fn raw_dpi(monitor: isize) -> Option<[f64; 2]> { + let (mut x, mut y) = (0u32, 0u32); + // SAFETY: `monitor` is a handle winit got from Windows for a connected monitor; a handle that + // has gone stale makes the call fail, which returns `None`. Both pointers point at live `u32`s + // for the length of the call. + unsafe { GetDpiForMonitor(HMONITOR(monitor as *mut core::ffi::c_void), MDT_RAW_DPI, &mut x, &mut y) }.ok()?; + (x > 0 && y > 0).then(|| [f64::from(x), f64::from(y)]) +} diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..55b0df872e 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -484,7 +484,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "view.actualSize", "Actual Size", "Cmd+1", - "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills 96 screen points (an inch at the system's reference density, whatever the display scaling); the same at every UI Scaling", + "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills an inch of the display that shows the window, measured from the physical size the system reports for it, or 96 screen points where it reports none; the same at every UI Scaling", ), ("view.setZoom", "Set Zoom", "", "{zoom: percent, center?: [x,y]}"), ( diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..47358b5842 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -586,7 +586,6 @@ impl VectorcraftApp { ctx.request_repaint(); return; } - crate::state::sync_zoom_stops_display_print_size(self.session.prefs.display_print_size); // Whether this pass draws the last step of an action playing at Step by Step. let step_held = crate::panels::actions::playback_held(self); let t0 = now_ms(); diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 042e8b37a5..0bad136114 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -136,7 +136,6 @@ impl VectorcraftApp { /// [`Self::run`] it, inside what asks for file dialogs. fn run_now(&mut self, id: &str, params: Value) -> Result { - crate::state::sync_zoom_stops_display_print_size(self.session.prefs.display_print_size); self.run_count = self.run_count.wrapping_add(1); // In debug builds the app's own calls are held to the params descriptions too (#1442): a // panel passing a key its command doesn't read shows up in the tests. Saved steps aren't diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 1e9d931a0a..ae107769e6 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -104,6 +104,34 @@ impl VectorcraftApp { self.session.active().map_or(vectorcraft_geom::Point::ZERO, |d| d.doc.ruler_origin_for(artboard)) } + /// The screen points an inch takes at 100% zoom with Display Print Size at 100% Zoom on, for + /// the display that shows the window; `None` with it off ([`crate::state::print_ppi`]). + pub(crate) fn print_ppi(&self) -> Option { + crate::state::print_ppi(self.session.prefs.display_print_size, self.services.screen_ppi) + } + + /// Takes `ppi` as the measured density of the main window's display + /// ([`crate::Services::screen_ppi`]). With Display Print Size at 100% Zoom on, every document + /// window's view keeps its zoom percentage, so the art keeps its physical size on the new + /// display. Returns whether the density changed. + pub fn set_screen_ppi(&mut self, ppi: Option) -> bool { + if self.services.screen_ppi == ppi { + return false; + } + let before = self.print_ppi(); + self.services.screen_ppi = ppi; + if let (Some(before), Some(after)) = (before, self.print_ppi()) + && before != after + { + let k = after / before; + for v in &mut self.views { + v.zoom = (v.zoom * k).clamp(0.0313, 640.0); + } + self.canvas.windows.views.scale_zooms(k); + } + true + } + pub fn view_mut(&mut self) -> Option<&mut View> { self.sync_views(); let i = self.session.active_index()?; diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index a6a0509de5..9e1d9cf151 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -602,7 +602,7 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po }); // Backtick as it was at the button-up: a key pressed or released later in the frame does not count. let backquote = backquote_at_release(ui, egui::PointerButton::Primary, f.backquote_before); - let ui_zoom = app.canvas_ui_zoom; + let (ui_zoom, print) = (app.canvas_ui_zoom, app.print_ppi()); match d { Drag::ZoomBox { start } => { let start = zoom_marquee_start(ui, start, before, p); @@ -615,14 +615,14 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po let fill = (rect.width() / r.width()).min(rect.height() / r.height()); vm.zoom = (xf.zoom * f64::from(ui_zoom) * f64::from(fill)).clamp(0.0313, 640.0); } else { - zoom_about(vm, rect, p, crate::state::next_zoom(vm.zoom, !m.alt), ui_zoom); + zoom_about(vm, rect, p, crate::state::next_zoom(vm.zoom, !m.alt, print), ui_zoom); } } } // A click (not held, not dragged) steps the zoom as with the marquee. Drag::ZoomScrub { held, moved: false, .. } if held <= HOLD_DELAY => { if let Some(vm) = app.view_mut() { - zoom_about(vm, rect, p, crate::state::next_zoom(vm.zoom, !m.alt), ui_zoom); + zoom_about(vm, rect, p, crate::state::next_zoom(vm.zoom, !m.alt, print), ui_zoom); } } Drag::ZoomScrub { .. } => {} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..3cbe57eefd 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -8550,6 +8550,41 @@ fn view_actual_size_follows_display_print_size() { assert!((app.view().unwrap().zoom - 96.0 / 72.0).abs() < 1e-12, "an inch is 96 screen points"); } +/// #9051: with Display Print Size on, Actual Size shows a document inch in an inch of the display +/// the window is on, from the density the host measured for it. When the window moves to a +/// display of another density, every document window keeps its zoom percentage, so the art keeps +/// its physical size there. +#[test] +fn view_actual_size_fills_an_inch_of_the_measured_display() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let rect = egui::Rect::from_min_size(Pos2::ZERO, vec2(460.0, 260.0)); + app.canvas_rect = Some(rect); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + assert!(app.set_screen_ppi(Some(127.0))); + let inch = |v: &View| { + let xf = Xf::new(rect, v); + f64::from(xf.to_screen(Point::new(72.0, 0.0)).x - xf.to_screen(Point::new(0.0, 0.0)).x) + }; + app.run("view.actualSize", json!({})).unwrap(); + assert!((inch(app.view().unwrap()) - 127.0).abs() < 1e-3, "72 pt take the display's 127 points to an inch"); + app.run("window.newWindow", json!({})).unwrap(); + let stepped = app.run("view.zoomIn", json!({})).unwrap()["zoom"].as_f64().unwrap_or(0.0); + assert!((stepped - 150.0).abs() < 1e-9, "the stops count from that 100%: {stepped}"); + assert!(app.set_screen_ppi(Some(91.0)), "the window moved to a sparser display"); + assert!(!app.set_screen_ppi(Some(91.0)), "the same reading changes nothing"); + let first = *crate::doc_windows::view(&app, (0, 1)).unwrap(); + assert!((inch(&first) - 91.0).abs() < 1e-3, "the other window's 100% still fills an inch"); + assert_eq!(crate::state::zoom_label(first.zoom, app.print_ppi()), "100%"); + assert_eq!(crate::state::zoom_label(app.view().unwrap().zoom, app.print_ppi()), "150%"); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + let zoom = app.view().unwrap().zoom; + assert!(app.set_screen_ppi(Some(127.0))); + assert_eq!(app.view().unwrap().zoom, zoom, "off, a move leaves the zoom alone"); + app.run("view.actualSize", json!({})).unwrap(); + assert!((app.view().unwrap().zoom - 1.0).abs() < 1e-12, "and 100% stays one point per point"); +} + /// Fit Artboard in Window fits the artboard as a rotated view shows it: at 45° every corner is /// on the canvas and one is within the 30-point margin of an edge. At 0° the zoom is unchanged. #[test] @@ -8604,7 +8639,7 @@ fn animated_zoom_scrubs_and_holds_else_the_zoom_tool_zooms_to_an_area() { press(&mut app, vec2(-100.0, 0.0), 0); assert!((app.view().unwrap().zoom - z0).abs() < 1e-6, "and back to the left"); press(&mut app, vec2(0.0, 0.0), 0); - assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(z0, true), "a click steps"); + assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(z0, true, None), "a click steps"); let z2 = app.view().unwrap().zoom; press(&mut app, vec2(0.0, 0.0), 40); assert!(app.view().unwrap().zoom > z2 * 1.2, "held, it zooms on"); @@ -8959,9 +8994,9 @@ fn cmd_space_zooms_and_space_pans_whatever_the_tool() { let z0 = app.view().unwrap().zoom; drag(&mut app, Modifiers::COMMAND, at); let z1 = app.view().unwrap().zoom; - assert_eq!(z1, crate::state::next_zoom(z0, true), "Cmd+Space click zooms in"); + assert_eq!(z1, crate::state::next_zoom(z0, true, None), "Cmd+Space click zooms in"); drag(&mut app, Modifiers::COMMAND | Modifiers::ALT, at); - assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(z1, false), "Cmd+Alt+Space click zooms out"); + assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(z1, false, None), "Cmd+Alt+Space click zooms out"); assert_eq!(app.session.active().unwrap().doc.art_bounds(), None, "the Rectangle tool drew nothing"); // Space alone pans, with the Zoom tool too. app.select_tool("zoom"); @@ -9009,7 +9044,7 @@ fn space_types_a_space_while_editing_text_and_does_not_pan() { assert_eq!(shown(&mut app), CursorIcon::ZoomIn, "Cmd+Space shows the magnifier"); typing_frame(&mut app, &ctx, vec![button(at, true, Modifiers::COMMAND)]); typing_frame(&mut app, &ctx, vec![button(at, false, Modifiers::COMMAND)]); - assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(before.zoom, true), "Cmd+Space click zooms in"); + assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(before.zoom, true, None), "Cmd+Space click zooms in"); typing_frame(&mut app, &ctx, vec![space(false, Modifiers::COMMAND), Event::ModifiersChanged(Modifiers::NONE)]); assert_eq!(plain(&app, id), "a ", "the text is as typed"); } @@ -9119,7 +9154,7 @@ fn space_shift_drag_rotates_the_view_whatever_the_tool() { assert_eq!((panned.rotation, panned.zoom), (v.rotation, v.zoom)); assert_ne!(panned.center, v.center, "Space pans"); drag(&mut app, Modifiers::COMMAND | Modifiers::SHIFT, true, c, c); - assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(v.zoom, true), "Cmd+Shift+Space click zooms in"); + assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(v.zoom, true, None), "Cmd+Shift+Space click zooms in"); assert_eq!(app.view().unwrap().rotation, v.rotation); // The Rotate View tool's Shift still rounds to 15°. app.select_tool("rotateView"); diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index b2669b128d..825db3940d 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -31,7 +31,7 @@ pub fn fit(app: &mut VectorcraftApp, how: &str) { }; let Some(target) = target else { return }; let zoom = if how == "view.actualSize" { - actual_size_zoom(app.session.prefs.display_print_size) + actual_size_zoom(app.print_ppi()) } else { fit_zoom(rect, target, app.view().map_or(0.0, |v| v.rotation), app.canvas_ui_zoom) }; @@ -102,11 +102,12 @@ pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool { } /// Zoom for View → Actual Size (`view.actualSize`). With Preferences › General › Display Print -/// Size at 100% Zoom off, one document point is one screen point. On, one document inch (72 pt) -/// fills an inch of the screen as the system counts it: 96 screen points, the reference density -/// that display scaling is set against (a CSS inch), whatever the scale factor. -pub(crate) fn actual_size_zoom(display_print_size: bool) -> f64 { - if display_print_size { 96.0 / 72.0 } else { 1.0 } +/// Size at 100% Zoom off (`print` `None`), one document point is one screen point. On, one +/// document inch (72 pt) fills an inch of the display that shows the window: `print` screen +/// points, its measured density, or 96 (a CSS inch) where the system reports no physical size +/// ([`crate::state::print_ppi`]). +pub(crate) fn actual_size_zoom(print: Option) -> f64 { + crate::state::zoom_baseline(print) } /// Zoom view `vm` of the canvas `rect` to `zoom` (clamped to the zoom range), keeping the document diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 126cc956f3..8149c3cb5a 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -10,7 +10,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { .show(ui, |ui| { ui.horizontal_centered(|ui| { let zoom = app.view().map(|v| v.zoom).unwrap_or(1.0); - let print = app.session.prefs.display_print_size; + let print = app.print_ppi(); let shown = crate::state::zoom_display_percent(zoom, print); ui.name_inputs(tl!("Zoom"), |ui| { craft_ui::ComboBox::from_id_salt("zoom-combo") diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index b92d1e5d04..e27877ca11 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -2,21 +2,21 @@ use super::{Sense, Stroke, Tokens, Ui, VectorcraftApp, icons, json, theme, vec2, /// [`view_tab_title`] for a document with one view. #[cfg(test)] -pub(super) fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bool, display_print_size: bool) -> String { - view_tab_title(d, None, zoom, outline, display_print_size) +pub(super) fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bool, print: Option) -> String { + view_tab_title(d, None, zoom, outline, print) } /// A document tab's title: "Name* @ 66.67 % (RGB/Preview)", or while an opacity mask is edited /// "Name* @ 66.67 % (/Opacity Mask)". For a view of a document with more than one /// view, the view's `number` follows the name: "Name:2* @ 66.67 % (RGB/Preview)". -fn view_tab_title(d: &vectorcraft_engine::DocState, number: Option, zoom: f64, outline: bool, display_print_size: bool) -> String { +fn view_tab_title(d: &vectorcraft_engine::DocState, number: Option, zoom: f64, outline: bool, print: Option) -> String { let mode = if d.doc.mask_edit.is_some() { format!("<{0}>/{0}", tl!("Opacity Mask")) } else { let color = if d.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { "CMYK" } else { "RGB" }; format!("{color}/{}", if outline { tl!("Outline") } else { tl!("Preview") }) }; - format!("{} @ {} ({mode})", view_tab_name(d, number), zoom_label(zoom, display_print_size).replace('%', " %")) + format!("{} @ {} ({mode})", view_tab_name(d, number), zoom_label(zoom, print).replace('%', " %")) } /// The start of [`view_tab_title`], which an inactive document tab shows alone (#8582): "Name*", @@ -31,7 +31,7 @@ fn view_tab_name(d: &vectorcraft_engine::DocState, number: Option) -> Strin fn window_tab_title(app: &VectorcraftApp, w: crate::doc_windows::Win, d: &vectorcraft_engine::DocState) -> String { let view = crate::doc_windows::view(app, w); let zoom = view.map_or(1.0, |v| v.zoom); - view_tab_title(d, crate::doc_windows::label(app, w), zoom, view.is_some_and(|v| v.outline), app.session.prefs.display_print_size) + view_tab_title(d, crate::doc_windows::label(app, w), zoom, view.is_some_and(|v| v.outline), app.print_ppi()) } /// The title of window `w`'s tab and floating window ([`crate::doc_windows`]). diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..d5a5743744 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1918,7 +1918,7 @@ fn the_tab_title_names_the_opacity_mask_while_it_is_edited() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); - let title = |s: &Session| super::tab_title(s.active().unwrap(), 1.0, false, false); + let title = |s: &Session| super::tab_title(s.active().unwrap(), 1.0, false, None); assert!(title(&s).ends_with("(RGB/Preview)"), "{}", title(&s)); s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); assert!(title(&s).ends_with("(/Opacity Mask)"), "{}", title(&s)); diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 96c4880d39..96ffd47261 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -974,7 +974,7 @@ fn ui_commands_refuse_params_of_the_wrong_type() { assert_eq!(after, before, "{id} {params}: nothing changes"); } app.run("view.setZoom", json!({"zoom": null, "center": null})).unwrap(); - assert_eq!(app.view().map(|v| v.zoom), Some(crate::state::zoom_from_display_percent(100.0, app.session.prefs.display_print_size))); + assert_eq!(app.view().map(|v| v.zoom), Some(crate::state::zoom_from_display_percent(100.0, app.print_ppi()))); } #[test] diff --git a/crates/ui-egui/src/doc_windows/views.rs b/crates/ui-egui/src/doc_windows/views.rs index dda76952ee..885e91fbee 100644 --- a/crates/ui-egui/src/doc_windows/views.rs +++ b/crates/ui-egui/src/doc_windows/views.rs @@ -36,6 +36,15 @@ pub struct Views { shown: HashMap, } +impl Views { + /// Multiplies the zoom of every view kept here by `k`, within the zoom range. + pub(crate) fn scale_zooms(&mut self, k: f64) { + for o in &mut self.others { + o.view.zoom = (o.view.zoom * k).clamp(0.0313, 640.0); + } + } +} + fn uid(app: &VectorcraftApp, i: usize) -> Option { app.session.documents().get(i).map(|d| d.uid) } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index aa9451d3f9..7eda9e95ca 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -455,12 +455,12 @@ fn run_ui_part5(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option flag(&mut app.ui.view.snap_to_point), "view.zoomIn" | "view.zoomOut" => { let up = id == "view.zoomIn"; - let print = app.session.prefs.display_print_size; + let print = app.print_ppi(); // Selection & Anchor Display › Zoom to Selection: the selection comes to the middle. let focus = if app.session.prefs.zoom_to_selection { app.selection_box().map(|b| b.center()) } else { None }; match app.view_mut() { Some(v) => { - v.zoom = next_zoom(v.zoom, up); + v.zoom = next_zoom(v.zoom, up, print); if let Some(c) = focus { v.center = c; } @@ -470,7 +470,7 @@ fn run_ui_part5(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { - let print = app.session.prefs.display_print_size; + let print = app.print_ppi(); let (zoom, center) = match opt_number(p, "zoom").and_then(|z| Ok((z, opt_point(p, "center")?))) { Ok(given) => given, Err(e) => return Some(Err(e)), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..920331ea39 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -485,7 +485,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "view.actualSize", "Actual Size", "Cmd+1", - "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills 96 screen points (an inch at the system's reference density, whatever the display scaling); the same at every UI Scaling", + "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills an inch of the display that shows the window, measured from the physical size the system reports for it, or 96 screen points where it reports none; the same at every UI Scaling", ), ("view.setZoom", "Set Zoom", "", "{zoom: percent, center?: [x,y]}"), ( diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index 753a4cc20b..367ed4ee80 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -179,7 +179,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); if app.session.tool_id() == "zoom" { let zoom = app.view().map_or(1.0, |v| v.zoom); - mono(ui, format!("{} {}", crate::i18n::colon(tl!("Zoom")), crate::state::zoom_label(zoom, app.session.prefs.display_print_size))); + mono(ui, format!("{} {}", crate::i18n::colon(tl!("Zoom")), crate::state::zoom_label(zoom, app.print_ppi()))); } if let Some(Readout::Brush { name: Some(name) }) = readout { mono(ui, name); @@ -315,7 +315,7 @@ mod tests { assert!(!texts(&mut app).iter().any(|t| t.starts_with("Zoom:"))); app.session.select_tool("zoom", view()).unwrap(); let zoom = app.view().map_or(1.0, |v| v.zoom); - let want = format!("Zoom: {}", crate::state::zoom_label(zoom, app.session.prefs.display_print_size)); + let want = format!("Zoom: {}", crate::state::zoom_label(zoom, app.print_ppi())); assert!(texts(&mut app).contains(&want), "{want}: {:?}", texts(&mut app)); } @@ -331,7 +331,7 @@ mod tests { crate::i18n::set_current(crate::i18n::Lang::EN); assert_eq!(shear.right[1], format!("{}\u{a0}: -12.5°", crate::i18n::tr(fr, "Shear"))); let zoom = app.view().map_or(1.0, |v| v.zoom); - let want = format!("{}\u{a0}: {}", crate::i18n::tr(fr, "Zoom"), crate::state::zoom_label(zoom, app.session.prefs.display_print_size)); + let want = format!("{}\u{a0}: {}", crate::i18n::tr(fr, "Zoom"), crate::state::zoom_label(zoom, app.print_ppi())); assert!(shown_texts.contains(&want), "{want}: {shown_texts:?}"); } diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index ec8aea7063..0593304e0b 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -28,7 +28,10 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ "usePreviewBounds", "Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured.", ), - ("displayPrintSize", "At 100% zoom, one inch of the document takes 96 screen points instead of 72."), + ( + "displayPrintSize", + "At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size.", + ), ("doubleClickToIsolate", "Double-clicking a group, path or image with the Selection tool opens it in isolation mode."), ( "transformPatternTiles", diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 6c38464bd0..0fdf34b526 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -220,6 +220,12 @@ pub struct Services { /// reports for a window on that monitor. Empty on the web, and where the host cannot place a /// window by these points, which sends floating panels to the main window's monitor. pub dock_monitors: Vec, + /// The density of the display that shows most of the main window, in the window's points + /// (before UI Scaling) per inch, from the physical size the system reports for that display. + /// The desktop host keeps it current as the window moves between displays. With Display Print + /// Size at 100% Zoom, 100% shows one document inch in this many points ([`crate::state::print_ppi`]). + /// `None` on the web and where the system reports no size, and then an inch takes 96 points. + pub screen_ppi: Option, /// The text Help › Copy Troubleshooting Info copies (desktop: the platform, the graphics /// processor, recent commands and frame times, and the hang reports of this session and the /// one before). Without it the command copies the version only ([`crate::troubleshooting`]). diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f8bce4e088..fe30649b14 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -107,15 +107,21 @@ pub const ROTATE_VIEW_ANGLES: [(&str, f64); 12] = [ ]; use super::ControlResponse; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::Sender; -/// Zoom stop stepping reads this (set each UI frame and before commands) so canvas wheel zoom -/// matches the status bar when Display Print Size at 100% Zoom is on. -static ZOOM_STOPS_PRINT_SIZE: AtomicBool = AtomicBool::new(false); +/// Screen points in an inch when the system reports no physical size for the display: the +/// reference density that display scaling is set against (a CSS inch). +pub const REFERENCE_PPI: f64 = 96.0; -pub fn sync_zoom_stops_display_print_size(v: bool) { - ZOOM_STOPS_PRINT_SIZE.store(v, Ordering::Relaxed); +/// The densities a measured display may have, in screen points per inch. A size outside them is +/// a wrong report (a projector or television that gives its aspect ratio as its size, or none). +pub const SCREEN_PPI_RANGE: std::ops::RangeInclusive = 30.0..=1000.0; + +/// The screen points one inch takes at 100% zoom: `None` with Preferences › General › Display +/// Print Size at 100% Zoom off, else the measured density of the display (`screen_ppi`, +/// [`crate::Services::screen_ppi`]), or [`REFERENCE_PPI`] when the display has none. +pub fn print_ppi(display_print_size: bool, screen_ppi: Option) -> Option { + display_print_size.then(|| screen_ppi.filter(|p| SCREEN_PPI_RANGE.contains(p)).unwrap_or(REFERENCE_PPI)) } /// The preset zoom stops, in percent. @@ -125,36 +131,35 @@ pub const ZOOM_STOPS: [f64; 26] = [ ]; /// Document zoom at 100% in the status bar: one screen point per document point, or with -/// Preferences › General › Display Print Size at 100% Zoom, one document inch in 96 screen points. -pub fn zoom_baseline(display_print_size: bool) -> f64 { - if display_print_size { 96.0 / 72.0 } else { 1.0 } +/// Preferences › General › Display Print Size at 100% Zoom ([`print_ppi`] `Some`), one document +/// inch (72 pt) in an inch of the screen, `print` screen points. +pub fn zoom_baseline(print: Option) -> f64 { + print.map_or(1.0, |ppi| ppi / 72.0) } -pub fn zoom_display_percent(z: f64, display_print_size: bool) -> f64 { - z / zoom_baseline(display_print_size) * 100.0 +pub fn zoom_display_percent(z: f64, print: Option) -> f64 { + z / zoom_baseline(print) * 100.0 } -pub fn zoom_from_display_percent(pct: f64, display_print_size: bool) -> f64 { - pct / 100.0 * zoom_baseline(display_print_size) +pub fn zoom_from_display_percent(pct: f64, print: Option) -> f64 { + pct / 100.0 * zoom_baseline(print) } -pub fn next_zoom(z: f64, up: bool) -> f64 { - next_zoom_with_display(z, up, ZOOM_STOPS_PRINT_SIZE.load(Ordering::Relaxed)) -} - -pub fn next_zoom_with_display(z: f64, up: bool, display_print_size: bool) -> f64 { - let pct = zoom_display_percent(z, display_print_size); +/// The preset zoom stop after zoom `z` (`up`) or before it, counted in the percentages the zoom +/// field shows with 100% at [`zoom_baseline`]`(print)`, kept in the zoom range. +pub fn next_zoom(z: f64, up: bool, print: Option) -> f64 { + let pct = zoom_display_percent(z, print); let stop = if up { ZOOM_STOPS.iter().find(|s| **s > pct + 0.01).copied().unwrap_or(64000.0) } else { ZOOM_STOPS.iter().rev().find(|s| **s < pct - 0.01).copied().unwrap_or(3.13) }; - zoom_from_display_percent(stop, display_print_size) + zoom_from_display_percent(stop, print).clamp(0.0313, 640.0) } /// Format for the tab/zoom field: up to 2 decimals, no trailing zeros. -pub fn zoom_label(z: f64, display_print_size: bool) -> String { - let s = format!("{:.2}", zoom_display_percent(z, display_print_size)); +pub fn zoom_label(z: f64, print: Option) -> String { + let s = format!("{:.2}", zoom_display_percent(z, print)); let s = s.trim_end_matches('0').trim_end_matches('.'); format!("{s}%") } @@ -1590,22 +1595,42 @@ mod tests { #[test] fn zoom_steps() { - assert_eq!(next_zoom_with_display(1.0, true, false), 1.5); - assert!((next_zoom_with_display(1.0, false, false) - 0.6667).abs() < 1e-9); - assert_eq!(next_zoom_with_display(640.0, true, false), 640.0); - assert_eq!(zoom_label(0.6667, false), "66.67%"); - assert_eq!(zoom_label(1.0, false), "100%"); - assert_eq!(zoom_label(0.125, false), "12.5%"); + assert_eq!(next_zoom(1.0, true, None), 1.5); + assert!((next_zoom(1.0, false, None) - 0.6667).abs() < 1e-9); + assert_eq!(next_zoom(640.0, true, None), 640.0); + assert_eq!(zoom_label(0.6667, None), "66.67%"); + assert_eq!(zoom_label(1.0, None), "100%"); + assert_eq!(zoom_label(0.125, None), "12.5%"); } /// storytold/vectorcraft#2719: 100% in the zoom field matches Actual Size when Display Print Size is on. #[test] fn zoom_percent_honors_display_print_size_baseline() { - let b = zoom_baseline(true); - assert!((zoom_from_display_percent(100.0, true) - b).abs() < 1e-12); - assert_eq!(zoom_from_display_percent(100.0, false), 1.0); - assert_eq!(zoom_label(b, true), "100%"); - assert_eq!(next_zoom_with_display(b, true, true), zoom_from_display_percent(150.0, true)); + let print = print_ppi(true, None); + let b = zoom_baseline(print); + assert!((zoom_from_display_percent(100.0, print) - b).abs() < 1e-12); + assert_eq!(zoom_from_display_percent(100.0, None), 1.0); + assert_eq!(zoom_label(b, print), "100%"); + assert_eq!(next_zoom(b, true, print), zoom_from_display_percent(150.0, print)); + } + + /// #9051: with Display Print Size on, 100% follows the measured density of the display, so an + /// inch of the document takes as many screen points as an inch of that display holds. A + /// density outside the range a display can have counts as no measurement. + #[test] + fn print_size_follows_the_displays_measured_density() { + assert_eq!(print_ppi(false, Some(127.0)), None, "the preference off ignores the display"); + let (dense, sparse) = (print_ppi(true, Some(127.0)), print_ppi(true, Some(91.0))); + assert!(zoom_baseline(dense) > zoom_baseline(print_ppi(true, None)), "a denser display than the reference zooms 100% further in"); + assert!(zoom_baseline(sparse) < zoom_baseline(print_ppi(true, None)), "a sparser one zooms it out"); + assert!((zoom_baseline(dense) * 72.0 - 127.0).abs() < 1e-9, "an inch of the document fills an inch of the display"); + for wrong in [Some(0.0), Some(-5.0), Some(f64::NAN), Some(f64::INFINITY), Some(5000.0), None] { + assert_eq!(print_ppi(true, wrong), print_ppi(true, None), "{wrong:?} is no measurement"); + } + assert_eq!(zoom_label(zoom_from_display_percent(100.0, dense), dense), "100%"); + let thin = print_ppi(true, Some(40.0)); + assert!(next_zoom(0.04, false, thin) >= 0.0313, "the last stop down stays in the zoom range"); + assert!(next_zoom(600.0, true, print_ppi(true, Some(900.0))) <= 640.0, "and the last stop up"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..bdafc83ef8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8288,7 +8288,10 @@ control channel's `ui.drag` scrubs), `showHomeScreen` (on by default: the Home s off, an empty window, and the Home button or `app.home` still shows the screen), `autoCollapseIconPanels` (off by default: on, a click away from a panel popped out of the icon column puts it away), `displayPrintSize` (off by default: View › Actual Size / `view.actualSize` is one document point per screen point; on, one document inch fills -96 screen points, an inch at the system's reference density whatever the display scaling). `uiScaling` scales the +an inch of the display that shows the main window, measured from the physical size macOS, Windows, X11 or the +Wayland compositor reports for it and measured again when the window moves to another display, where every +document window keeps its zoom percentage; where the system +reports no size, as on the web, or a size no display has, an inch is 96 screen points). `uiScaling` scales the interface and not the art: a zoom shows the art at the same size at every UI Scaling. The tool shortcut preference `holdToolKeys` also needs the desktop app. It is on by default: a single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses the tool until the key is let go and then returns to the tool active diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..15ad6a5160 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1292,7 +1292,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen rubber band after a smooth anchor:** the preview segment to the pointer is the curve a click there adds, leaving the last anchor along its outgoing handle and arriving at the new corner anchor without a handle, so the segment keeps its shape when the anchor is placed, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes. Before, the preview was a different curve, and the segment changed shape at the click (#8296, in part; `pen::tests::rubber_band_is_the_segment_a_click_adds`); scores and estimates unchanged. - **Pen rubber band over an anchor a click ends on:** over the path's first anchor, the preview segment ends on that anchor, as the closing segment does; over an end of another open path, it ends on that end and arrives along the end's own handle, as the joining segment does. The preview picks these anchors at the pointer before snapping, as a press does. Before, the preview ended at the pointer and arrived without a handle, so the segment moved by up to the pick tolerance at the click, and changed shape when the other end was smooth (#8296, in part; the `pen_rubber_band` tests in `engine/tests/it`); scores and estimates unchanged. - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). + - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills an inch of the display that shows the main window, measured from the physical size the system reports for it, or 96 screen points where it reports none; `view.actualSize` / `prefs.set`, #394, #9051). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). - Preferences › General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default; dimmed while Zoom with Mouse Wheel is on): while Zoom with Mouse Wheel is off, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer, and once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. Under either wheel preference, Cmd/Ctrl with a touchpad zooms about the pointer. - Preferences › Type › Highlight Substituted Fonts (on by default) paints pink behind text drawn in a substitute for a missing font in every document, and turning it off removes that highlight everywhere (`prefs.set highlightSubstitutedFonts`); Document Setup keeps Highlight Substituted Glyphs ([help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/edit-text-without-replacing-missing-fonts.html)). - Preferences › User Interface › UI Scaling scales the interface ([help](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/modify-workspaces.html)). VectorCraft's own rule is that it leaves the art's size alone: at a given zoom a document point covers the same device pixels at every UI Scaling, so View › Actual Size shows the art at the same size whatever the UI Scaling. A click, a pinch or wheel zoom about the pointer, a pan, the Zoom tool's marquee, Fit, tiled panes, Pixel Preview and the Navigator's view box use the same mapping. Evidence: `canvas::tests_ui_scaling`, `tiled_documents_fit_their_panes_at_every_ui_scaling`, `the_view_box_outlines_the_canvas_at_every_ui_scaling`. Scores unchanged. From 3098776c077cb8526a666ea679e1886fae889084 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:22:22 -0800 Subject: [PATCH 036/101] Display Print Size: on by default, each window counts its own display MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Preferences › General › Display Print Size at 100% Zoom is now on by default, also for saved preferences that predate the key; a saved choice to turn it off stays off. A document floating in an OS window of its own counts 100% from the display that shows that window. A move of the main window leaves the zoom of floating windows alone, and a window that moves to a display of another density keeps its zoom percentage. The desktop app lists the displays once a second while the preference is on and reads their physical sizes on a background thread when the list changes; the UI thread does not wait for the X11 or Wayland queries. RandR is asked for its version before the CRTC and output queries. A reading that fails is tried again after 10 seconds, and the displays are read again a minute after the last reading, so a display replaced by one that lists the same gets its own size. The Navigator's zoom field, slider and thumbnail clicks count the zoom from Actual Size, as the status bar's zoom field does; before, a click on the thumbnail with the preference on changed the zoom. ui.inspect gives screenPpi and printPpi. The preference's description is updated in every catalog. --- apps/vectorcraft/src/app.rs | 6 +- apps/vectorcraft/src/screen_density.rs | 715 +++++++++++++++--- apps/vectorcraft/src/windows_display_size.rs | 15 +- crates/engine/src/prefs.rs | 4 +- crates/engine/src/tests/prefs_file.rs | 11 + crates/ui-egui/src/app.rs | 3 + crates/ui-egui/src/app/view.rs | 150 +++- crates/ui-egui/src/canvas.rs | 12 +- crates/ui-egui/src/canvas/grid.rs | 13 +- crates/ui-egui/src/canvas/panes.rs | 9 +- crates/ui-egui/src/canvas/tests.rs | 88 ++- crates/ui-egui/src/canvas/tests_ui_scaling.rs | 4 +- crates/ui-egui/src/canvas/view.rs | 8 + crates/ui-egui/src/chrome/status_bar.rs | 4 +- crates/ui-egui/src/chrome/tabs.rs | 2 +- crates/ui-egui/src/chrome/tests.rs | 2 +- crates/ui-egui/src/control.rs | 6 + crates/ui-egui/src/control/tests.rs | 19 +- crates/ui-egui/src/doc_windows.rs | 122 ++- crates/ui-egui/src/doc_windows/tests.rs | 68 ++ crates/ui-egui/src/doc_windows/views.rs | 9 - crates/ui-egui/src/i18n/bg.tsv | 2 +- crates/ui-egui/src/i18n/bs.tsv | 2 +- crates/ui-egui/src/i18n/ca.tsv | 2 +- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/da.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/gu.tsv | 2 +- crates/ui-egui/src/i18n/hi.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/id.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/panels/navigator.rs | 61 +- crates/ui-egui/src/services.rs | 64 +- crates/ui-egui/src/state.rs | 38 +- crates/ui-egui/src/tests/tab_overflow.rs | 2 + crates/ui-egui/src/toolbar/tests.rs | 2 +- docs/mcp.md | 18 +- docs/target-app-parity.md | 2 +- 57 files changed, 1303 insertions(+), 212 deletions(-) diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index c93a1d0341..8a0267f2cc 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -208,9 +208,9 @@ impl App { } if let Some(w) = &self.winit_window { self.display_profile.tick(w, now, self.app.session.prefs.monitor_profile_display, &self.app.display_profile, ctx); - if let Some(read) = self.screen_density.tick(w, now) - && self.app.set_screen_ppi(read) - { + if let Some(read) = self.screen_density.tick(w, self.app.session.prefs.display_print_size, ctx) { + self.app.services.screens = read.screens; + self.app.set_screen_reading(read.main); ctx.request_repaint(); } } diff --git a/apps/vectorcraft/src/screen_density.rs b/apps/vectorcraft/src/screen_density.rs index 3a91f7f4d4..c89934a3c7 100644 --- a/apps/vectorcraft/src/screen_density.rs +++ b/apps/vectorcraft/src/screen_density.rs @@ -1,6 +1,7 @@ -//! The density of the display that shows most of the main window, in the window's points per -//! inch, for Preferences › General › Display Print Size at 100% Zoom (`Services::screen_ppi`): -//! the display's size in points divided by the physical size the system reports for it. +//! The densities of the connected displays, in points (at each display's scale factor) per inch, +//! for Preferences › General › Display Print Size at 100% Zoom (`Services::screen_ppi` for the +//! display that shows most of the main window, `Services::screens` for every display): a +//! display's size in points divided by the physical size the system reports for it. //! //! - macOS: `CGDisplayScreenSize`. //! - Windows: `GetDpiForMonitor`'s raw density (`windows_display_size`). @@ -8,15 +9,26 @@ //! - Wayland: the physical width and height of the compositor's `wl_output` for the display. //! //! A display that reports no size, or a size no display has, gives `None`, and an inch then takes -//! 96 points. The window's display is looked up once a second while the app draws, and read when -//! it changes. +//! 96 points. While the preference is on, the displays are listed once a second while the app +//! draws. When the list changes, a background thread reads every display's size, and a later +//! frame takes the result. A reading that fails is tried again after [`RETRY_AFTER`] seconds. +use std::sync::mpsc::{Receiver, TryRecvError}; + +use vectorcraft_ui_egui::{ScreenDensity, ScreenPpi}; use winit::dpi::{PhysicalPosition, PhysicalSize}; use winit::monitor::MonitorHandle; -/// Seconds between two checks of which display shows the window. +/// Seconds between two listings of the displays. const LOOK_EVERY: f64 = 1.0; +/// Seconds after a failed reading before the same displays are read again. +const RETRY_AFTER: f64 = 10.0; + +/// Seconds after a reading before the same displays are read again: a display can be replaced by +/// one the listing cannot tell apart (the same connector, resolution and scale). +const READ_AGAIN_AFTER: f64 = 60.0; + /// Millimeters in an inch. const MM_PER_INCH: f64 = 25.4; @@ -24,49 +36,266 @@ const MM_PER_INCH: f64 = 25.4; /// larger: square pixels on a display that reports its true size give two densities this close. const AXES_AGREE: f64 = 0.1; -/// What identifies the display and the window's scale on it between two looks. -type Shown = (Option, PhysicalPosition, PhysicalSize, u64); - -/// Keeps the density current from the main window's frames. -#[derive(Default)] -pub(crate) struct Tracker { - /// When the window's display was last looked up. - looked: Option, - /// The display read last, with the window's scale factor then. - shown: Option, +/// A connected display as winit lists it: what a reading needs, and what tells two lists apart. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Display { + name: Option, + position: PhysicalPosition, + size: PhysicalSize, + /// The display's scale factor, as its bits. + scale: u64, + /// The system's id of the display ([`native_id`]). + id: i64, } -impl Tracker { - /// Looks up the window's display when a look is due at `now` (seconds), and returns its - /// density (`None` inside for a display that reports no size) when the display or the - /// window's scale changed since the last reading. - pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64) -> Option> { - if self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) { - return None; - } - self.looked = Some(now); - let monitor = window.current_monitor(); - let scale = window.scale_factor(); - let shown = monitor.as_ref().map(|m| (m.name(), m.position(), m.size(), scale.to_bits())); - if shown == self.shown { - return None; - } - self.shown = shown; - let read = monitor.and_then(|m| points_per_inch(m.size(), scale, physical_mm(window, &m)?)); - match read { - Some(p) => log::info!("the window's display has {p:.1} points to an inch"), - None => log::info!("the window's display reports no physical size; an inch is 96 points"), - } - Some(read) +impl Display { + fn of(m: &MonitorHandle) -> Self { + Self { name: m.name(), position: m.position(), size: m.size(), scale: m.scale_factor().to_bits(), id: native_id(m) } } } -/// The density, in points per inch, of a display `size` physical pixels wide and high, with the -/// window drawn at `scale` pixels to a point, that the system says is `mm` millimeters wide and -/// high. `None` for a size that is no display's: zero or less, an aspect ratio given in place of -/// the size (16 × 9, 160 × 90 and the like), axes whose densities disagree in either orientation, -/// or a density outside [`vectorcraft_ui_egui::state::SCREEN_PPI_RANGE`]. A display turned a -/// quarter turn may report the size of its panel upright, so the axes are also tried swapped. +/// One display's physical size in millimeters: `None` when the system reports none, an error when +/// asking for it failed. +type Size = Result, String>; + +/// The physical sizes of displays, one for each display read, or why none could be read. +type Reading = Result, String>; + +/// What the host hands the app: the density of the main window's display, unread while that +/// display is unknown or has not answered yet, and every display's that answered. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Densities { + pub(crate) main: ScreenPpi, + pub(crate) screens: Vec, +} + +/// What a display answered: its physical size (`Some(None)` for none), or `None` while it has not +/// answered. +type Answer = Option>; + +/// What a listing gives: the displays, the one that shows most of the main window, and the main +/// window's scale factor. +type Listing = (Vec, Option, f64); + +/// Keeps the densities current from the main window's frames. +#[derive(Default)] +pub(crate) struct Tracker { + /// When the displays were last listed. + looked: Option, + /// The display that showed most of the main window at the last listing, and the window's scale + /// factor then. + current: Option<(Display, f64)>, + /// The displays of the last reading that finished, each with what it answered. + read: Option>, + /// The displays of the last reading that failed, and when it failed. + failed: Option<(Vec, f64)>, + /// The reading in progress: the displays it reads, and where its result arrives. + running: Option<(Vec, Receiver)>, + /// The reading in progress started before the preference was last turned off: its result is + /// dropped when it arrives, and no other reading starts until then. + obsolete: bool, + /// What [`Self::tick`] returned last. + reported: Option, + /// The displays of the last listing. + listed: Option>, + /// When the last reading that finished ended. + read_at: f64, + /// When the first tick ran: the tracker's clock, which runs while the window draws nothing. + origin: Option, +} + +impl Tracker { + /// Lists the displays when a listing is due and Display Print Size is `enabled`, starts a + /// reading on a background thread when they changed, and returns the densities when they + /// differ from what it returned before. The thread asks `ctx` for a frame when its reading is + /// ready. + pub(crate) fn tick(&mut self, window: &winit::window::Window, enabled: bool, ctx: &egui::Context) -> Option { + let now = self.origin.get_or_insert_with(std::time::Instant::now).elapsed().as_secs_f64(); + let list = || { + // winit stops on a display that went away while it is being asked about (Windows); that + // listing is dropped, and the next one is made a second later. + let listing = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let current = window.current_monitor().map(|m| Display::of(&m)); + (window.available_monitors().map(|m| Display::of(&m)).collect::>(), current, window.scale_factor()) + })); + listing.map_err(|_| log::debug!("a display went away while the displays were listed")).ok() + }; + let wayland = is_wayland(window); + let start = |displays: Vec| { + let (tx, rx) = std::sync::mpsc::channel(); + let ctx = ctx.clone(); + let spawned = std::thread::Builder::new().name("display size".into()).spawn(move || { + // The app may have quit, and dropped the receiver, before the reading ends. + let _ = tx.send(read_all(&displays, wayland)); + ctx.request_repaint(); + }); + spawned.map(|_| rx).map_err(|e| format!("couldn't start reading the displays' sizes: {e}")) + }; + let densities = self.update(now, enabled, list, start); + // A failed reading is tried again at a listing RETRY_AFTER seconds later, also in an app + // that is not drawing. A reading in progress asks for a frame when it ends. + if enabled + && self.running.is_none() + && let Some((_, at)) = &self.failed + { + let due = (at + RETRY_AFTER).max(self.looked.map_or(0.0, |l| l + LOOK_EVERY)); + ctx.request_repaint_after(std::time::Duration::from_secs_f64((due - now).clamp(0.0, RETRY_AFTER))); + } + densities + } + + /// [`Self::tick`] with the listing (`list`) and the start of a reading (`start`) passed in. + fn update( + &mut self, + now: f64, + enabled: bool, + list: impl FnOnce() -> Option, + start: impl FnOnce(Vec) -> Result, String>, + ) -> Option { + let was_running = self.running.is_some(); + if let Some((displays, rx)) = self.running.take() { + match rx.try_recv() { + Err(TryRecvError::Empty) => self.running = Some((displays, rx)), + _ if self.obsolete => self.obsolete = false, + Ok(Ok(sizes)) => { + // A display whose size could not be read keeps what an earlier reading gave it, + // or stays unanswered, until the reading is tried again. + let mut failed = false; + let read: Vec<_> = displays + .iter() + .zip(sizes.into_iter().chain(std::iter::repeat(Ok(None)))) + .map(|(d, s)| { + let mm = s.map(Some).unwrap_or_else(|e| { + log::debug!("couldn't read a display's physical size: {e}"); + failed = true; + self.earlier(d) + }); + (d.clone(), mm) + }) + .collect(); + self.failed = failed.then_some((displays, now)); + self.read = Some(read); + self.read_at = now; + } + Ok(Err(e)) => { + log::debug!("couldn't read the displays' physical sizes: {e}"); + self.fail(displays, now); + } + Err(TryRecvError::Disconnected) => { + log::debug!("the reading of the displays' physical sizes stopped without a result"); + self.fail(displays, now); + } + } + } + // When a reading ends, the displays are listed again at once: they may have changed while + // it ran, and the frame its end asked for may be the last one for a while. + if was_running && self.running.is_none() { + self.looked = None; + } + if !enabled { + // Turned on again, the displays are read and the densities reported anew: a display + // may have been replaced meanwhile by one that lists the same. + self.reported = None; + self.read = None; + self.failed = None; + self.looked = None; + self.obsolete = self.running.is_some(); + return None; + } + // The densities change only at a listing, and one follows the end of every reading. + let listing = !self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)); + if !listing && self.reported.is_some() { + return None; + } + if listing { + self.looked = Some(now); + } + if let Some((displays, current, scale)) = listing.then(list).flatten() { + // winit can give the window's display as it was before a change of resolution: the + // display is found in the listing by its id and name. + let current = current.map(|c| displays.iter().find(|d| d.id == c.id && d.name == c.name).cloned().unwrap_or(c)); + self.current = current.map(|c| (c, scale)); + self.listed = Some(displays.clone()); + // These displays are read once, and again RETRY_AFTER seconds after a reading of them + // failed in whole or in part. + let known = self.read.as_ref().is_some_and(|r| r.iter().map(|(d, _)| d).eq(displays.iter())); + let due = match &self.failed { + Some((d, at)) if *d == displays => !(*at..*at + RETRY_AFTER).contains(&now), + _ => !known || now - self.read_at >= READ_AGAIN_AFTER, + }; + if self.running.is_none() && due { + match start(displays.clone()) { + Ok(rx) => self.running = Some((displays, rx)), + Err(e) => { + log::warn!("{e}"); + self.fail(displays, now); + } + } + } + } + let read = self.read.as_ref()?; + // The main window counts in its own scale factor, which on Wayland can be a fraction where + // the display gives a whole number. A window on no display (a Wayland window before it is + // shown, or after its display went), or on one that is being read or has not answered, has + // its density unread. + let main = match &self.current { + Some((c, scale)) => match read.iter().find(|(d, _)| d == c) { + Some((d, Some(mm))) => ScreenPpi::Read(mm.and_then(|mm| points_per_inch(d.size, *scale, mm))), + _ => ScreenPpi::Unread, + }, + None => ScreenPpi::Unread, + }; + // The displays where the last listing has them, each with what the reading of it gave; a + // display the readings have not reached yet is unread. + let listed = self.listed.as_deref().unwrap_or_default(); + let screens = listed + .iter() + .map(|d| { + let [w, h] = [d.size.width, d.size.height].map(|v| i32::try_from(v).unwrap_or(i32::MAX)); + let scale = f64::from_bits(d.scale); + let mm = read.iter().find(|(e, _)| e == d).and_then(|(_, mm)| *mm); + let ppi = mm.map_or(ScreenPpi::Unread, |mm| ScreenPpi::Read(mm.and_then(|mm| points_per_inch(d.size, scale, mm)))); + ScreenDensity { rect: [d.position.x, d.position.y, w, h], scale, ppi } + }) + .collect(); + let densities = Densities { main, screens }; + if self.reported.as_ref() == Some(&densities) { + return None; + } + match main { + ScreenPpi::Read(Some(p)) => log::info!("the window's display has {p:.1} points to an inch"), + ScreenPpi::Read(None) => log::info!("the window's display reports no physical size; an inch is 96 points"), + ScreenPpi::Unread => log::info!("the window's display has not been read; an inch is 96 points"), + } + self.reported = Some(densities.clone()); + Some(densities) + } +} + +impl Tracker { + /// What the last reading gave display `d`, when it answered. + fn earlier(&self, d: &Display) -> Answer { + self.read.as_ref()?.iter().find(|(e, _)| e == d)?.1 + } + + /// Records that reading `displays` failed at `now`; they are read again after [`RETRY_AFTER`] + /// seconds. After an earlier reading, they become the displays known, each with what that + /// reading gave it, if anything. Before any reading, nothing is reported yet. + fn fail(&mut self, displays: Vec, now: f64) { + if self.read.is_some() { + let read = displays.iter().map(|d| (d.clone(), self.earlier(d))).collect(); + self.read = Some(read); + } + self.failed = Some((displays, now)); + } +} + +/// The density, in points per inch, of a display `size` physical pixels wide and high, drawn at +/// `scale` pixels to a point, that the system says is `mm` millimeters wide and high. `None` for a +/// size that is no display's: zero or less, an aspect ratio given in place of the size (16 × 9, +/// 160 × 90 and the like), axes whose densities disagree in either orientation, or a density +/// outside [`vectorcraft_ui_egui::state::SCREEN_PPI_RANGE`]. A display turned a quarter turn may +/// report the size of its panel upright, so the axes are also tried swapped. pub(crate) fn points_per_inch(size: PhysicalSize, scale: f64, mm: [f64; 2]) -> Option { if !(scale.is_finite() && scale > 0.0) || mm.iter().any(|v| !(v.is_finite() && *v > 0.0)) || aspect_as_size(mm) { return None; @@ -87,59 +316,105 @@ fn aspect_as_size(mm: [f64; 2]) -> bool { RATIOS.iter().any(|r| [1.0, 10.0].iter().any(|k| sorted == [r[0] * k, r[1] * k])) } -/// The physical width and height, in millimeters, the system reports for `monitor`. +/// Whether `window` is a Wayland window, whose displays the compositor describes. +#[cfg(target_os = "linux")] +fn is_wayland(window: &winit::window::Window) -> bool { + use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; + window.window_handle().ok().is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Wayland(_))) +} + +#[cfg(not(target_os = "linux"))] +fn is_wayland(_: &winit::window::Window) -> bool { + false +} + +/// The system's id of `monitor`: the display id on macOS, the monitor handle on Windows, the RandR +/// CRTC on X11. #[cfg(target_os = "macos")] -fn physical_mm(_: &winit::window::Window, monitor: &MonitorHandle) -> Option<[f64; 2]> { +fn native_id(monitor: &MonitorHandle) -> i64 { use winit::platform::macos::MonitorHandleExtMacOS as _; - let size = objc2_core_graphics::CGDisplayScreenSize(monitor.native_id()); - Some([size.width, size.height]) + i64::from(monitor.native_id()) } #[cfg(windows)] -fn physical_mm(_: &winit::window::Window, monitor: &MonitorHandle) -> Option<[f64; 2]> { +fn native_id(monitor: &MonitorHandle) -> i64 { use winit::platform::windows::MonitorHandleExtWindows as _; - let [x, y] = crate::windows_display_size::raw_dpi(monitor.hmonitor())?; - let size = monitor.size(); - Some([f64::from(size.width) / x * MM_PER_INCH, f64::from(size.height) / y * MM_PER_INCH]) + monitor.hmonitor() as i64 } #[cfg(target_os = "linux")] -fn physical_mm(window: &winit::window::Window, monitor: &MonitorHandle) -> Option<[f64; 2]> { - use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; - let wayland = window.window_handle().ok().is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Wayland(_))); - let read = if wayland { wayland::physical_mm(monitor.name().as_deref()) } else { x11::physical_mm(monitor) }; - read.unwrap_or_else(|e| { - log::debug!("couldn't read the display's physical size: {e}"); - None - }) +fn native_id(monitor: &MonitorHandle) -> i64 { + use winit::platform::x11::MonitorHandleExtX11 as _; + i64::from(monitor.native_id()) } #[cfg(not(any(target_os = "macos", windows, target_os = "linux")))] -fn physical_mm(_: &winit::window::Window, _: &MonitorHandle) -> Option<[f64; 2]> { - None +fn native_id(_: &MonitorHandle) -> i64 { + 0 +} + +/// The physical width and height, in millimeters, the system reports for each of `displays`. +#[cfg(target_os = "macos")] +fn read_all(displays: &[Display], _: bool) -> Reading { + Ok(displays + .iter() + .map(|d| { + Ok(u32::try_from(d.id).ok().map(|id| { + let size = objc2_core_graphics::CGDisplayScreenSize(id); + [size.width, size.height] + })) + }) + .collect()) +} + +#[cfg(windows)] +fn read_all(displays: &[Display], _: bool) -> Reading { + Ok(displays + .iter() + .map(|d| { + let dpi = crate::windows_display_size::raw_dpi(d.id as isize)?; + Ok(dpi.map(|[x, y]| [f64::from(d.size.width) / x * MM_PER_INCH, f64::from(d.size.height) / y * MM_PER_INCH])) + }) + .collect()) +} + +#[cfg(target_os = "linux")] +fn read_all(displays: &[Display], wayland: bool) -> Reading { + if wayland { wayland::read_all(displays) } else { x11::read_all(displays) } +} + +#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))] +fn read_all(displays: &[Display], _: bool) -> Reading { + Ok(displays.iter().map(|_| Ok(None)).collect()) } #[cfg(target_os = "linux")] mod x11 { - use winit::monitor::MonitorHandle; - use winit::platform::x11::MonitorHandleExtX11 as _; use x11rb::CURRENT_TIME; use x11rb::protocol::randr; - /// The millimeters RandR reports for the first output of the CRTC that shows `monitor`. - pub(super) fn physical_mm(monitor: &MonitorHandle) -> Result, String> { + use super::{Display, Reading, Size}; + + /// The millimeters RandR reports for the first output of each display's CRTC. + pub(super) fn read_all(displays: &[Display]) -> Reading { let (conn, _) = x11rb::connect(None).map_err(|e| format!("couldn't connect to the X11 display: {e}"))?; let ask = |e: x11rb::errors::ConnectionError| format!("couldn't ask the X11 display: {e}"); - let crtc = randr::get_crtc_info(&conn, monitor.native_id(), CURRENT_TIME) - .map_err(ask)? - .reply() - .map_err(|e| format!("the X11 display has no such CRTC: {e}"))?; - let Some(output) = crtc.outputs.first() else { return Ok(None) }; - let info = randr::get_output_info(&conn, *output, CURRENT_TIME) - .map_err(ask)? - .reply() - .map_err(|e| format!("the X11 display has no such output: {e}"))?; - Ok(Some([f64::from(info.mm_width), f64::from(info.mm_height)])) + // RandR answers only a client that gave the version it speaks; 1.2 has CRTCs and outputs. + randr::query_version(&conn, 1, 2).map_err(ask)?.reply().map_err(|e| format!("the X11 display has no RandR 1.2: {e}"))?; + let size = |d: &Display| -> Size { + let Ok(crtc) = u32::try_from(d.id) else { return Ok(None) }; + let info = randr::get_crtc_info(&conn, crtc, CURRENT_TIME) + .map_err(ask)? + .reply() + .map_err(|e| format!("the X11 display has no such CRTC: {e}"))?; + let Some(output) = info.outputs.first() else { return Ok(None) }; + let info = randr::get_output_info(&conn, *output, CURRENT_TIME) + .map_err(ask)? + .reply() + .map_err(|e| format!("the X11 display has no such output: {e}"))?; + Ok(Some([f64::from(info.mm_width), f64::from(info.mm_height)])) + }; + Ok(displays.iter().map(size).collect()) } } @@ -150,9 +425,12 @@ mod wayland { use wayland_client::protocol::wl_registry::{self, WlRegistry}; use wayland_client::{Connection, Dispatch, QueueHandle}; - /// The physical size the compositor gives for the output named `name`, asked on a connection - /// of its own; with no name, or a compositor that names no outputs, the only output's. - pub(super) fn physical_mm(name: Option<&str>) -> Result, String> { + use super::{Display, Reading}; + + /// The physical size the compositor gives for the output of each display's name, asked on a + /// connection of its own; with no name, or a compositor that names no outputs, the only + /// output's. + pub(super) fn read_all(displays: &[Display]) -> Reading { let conn = Connection::connect_to_env().map_err(|e| format!("no Wayland compositor: {e}"))?; let (globals, mut queue) = registry_queue_init::(&conn).map_err(|e| e.to_string())?; let qh = queue.handle(); @@ -165,12 +443,18 @@ mod wayland { // The compositor sends each output's geometry, name and `done` in reply to the bind. queue.roundtrip(&mut state).map_err(|e| e.to_string())?; let found: Vec<&Output> = state.outputs.iter().map(|(_, o)| o).collect(); - let pick = match name { - Some(name) if found.iter().any(|o| o.name.is_some()) => found.iter().find(|o| o.name.as_deref() == Some(name)), - _ if found.len() == 1 => found.first(), - _ => None, - }; - Ok(pick.and_then(|o| o.mm)) + let named = found.iter().any(|o| o.name.is_some()); + Ok(displays + .iter() + .map(|d| { + let pick = match d.name.as_deref() { + Some(name) if named => found.iter().find(|o| o.name.as_deref() == Some(name)), + _ if found.len() == 1 => found.first(), + _ => None, + }; + Ok(pick.and_then(|o| o.mm)) + }) + .collect()) } /// One output's name and physical size. @@ -206,6 +490,9 @@ mod wayland { #[cfg(test)] mod tests { + use std::cell::Cell; + use std::sync::mpsc::{Sender, channel}; + use super::*; /// A 14-inch laptop panel at twice its points: 3024 × 1964 pixels, 302 × 196 mm, draws 127 @@ -249,4 +536,262 @@ mod tests { assert_eq!(points_per_inch(PhysicalSize::new(100, 56), 1.0, [5270.0, 2960.0]), None, "under the range"); assert_eq!(points_per_inch(PhysicalSize::new(7680, 4320), 1.0, [53.0, 30.0]), None, "over it"); } + + /// A 1920 × 1080 display at scale 1 and position `x`, named `name`. + fn display(name: &str, x: i32) -> Display { + Display { + name: Some(name.into()), + position: PhysicalPosition::new(x, 0), + size: PhysicalSize::new(1920, 1080), + scale: 1.0f64.to_bits(), + id: 0, + } + } + + /// The sizes of a 24-inch display (about 92 points to an inch) and a 27-inch one (about 82). + const SIZES: [[f64; 2]; 2] = [[531.0, 299.0], [598.0, 336.0]]; + + /// A reading that gives every display one of [`SIZES`], in turn. + fn sizes(n: usize) -> Reading { + Ok((0..n).map(|i| Ok(Some(SIZES[i % SIZES.len()]))).collect()) + } + + /// Drives a tracker: counts its listings and readings, and hands out the sender of the reading + /// it started last. + struct Rig { + tracker: Tracker, + displays: Vec, + current: usize, + /// The window's display as winit last gave it, when that lags behind the listing. + lagging: Option, + window_scale: f64, + lists: Cell, + reads: Cell, + sender: Option>, + fail_to_start: bool, + } + + impl Rig { + fn new() -> Self { + Self { + tracker: Tracker::default(), + displays: vec![display("left", 0), display("right", 1920)], + current: 0, + lagging: None, + window_scale: 1.0, + lists: Cell::new(0), + reads: Cell::new(0), + sender: None, + fail_to_start: false, + } + } + + fn tick(&mut self, now: f64, enabled: bool) -> Option { + let current = self.lagging.clone().or_else(|| self.displays.get(self.current).cloned()); + let (displays, scale) = (self.displays.clone(), self.window_scale); + let (lists, reads, fail) = (&self.lists, &self.reads, self.fail_to_start); + let mut sender = None; + let out = self.tracker.update( + now, + enabled, + || { + lists.set(lists.get() + 1); + Some((displays, current, scale)) + }, + |_| { + reads.set(reads.get() + 1); + if fail { + return Err("no thread".into()); + } + let (tx, rx) = channel(); + sender = Some(tx); + Ok(rx) + }, + ); + if sender.is_some() { + self.sender = sender; + } + out + } + + fn finish(&mut self, reading: Reading) { + if let Some(tx) = self.sender.take() { + tx.send(reading).unwrap(); + } + } + } + + /// The first listing starts a reading, and the densities arrive once the reading ends, without + /// a frame waiting for it. The main window's density is its display's, and every display gets + /// its own. + #[test] + fn the_densities_arrive_when_the_reading_ends() { + let mut rig = Rig::new(); + assert_eq!(rig.tick(0.0, true), None, "the reading runs in the background"); + assert_eq!(rig.reads.get(), 1); + assert_eq!(rig.tick(2.0, true), None, "still running: no second reading"); + assert_eq!(rig.reads.get(), 1); + rig.finish(sizes(2)); + let got = rig.tick(2.1, true).unwrap_or_else(|| panic!("the densities")); + let ppi = got.screens.iter().map(|s| s.ppi.ppi().unwrap_or(0.0)).collect::>(); + assert!(ppi[0] > ppi[1] && ppi[1] > 0.0, "the smaller display is denser: {ppi:?}"); + assert_eq!(got.main, ScreenPpi::Read(Some(ppi[0])), "the main window is on the left display"); + assert_eq!(got.screens[1].rect, [1920, 0, 1920, 1080]); + assert_eq!(rig.tick(5.0, true), None, "nothing changed"); + assert_eq!(rig.reads.get(), 1, "the same displays are not read again"); + assert_eq!(rig.tick(5.2, false), None, "off, nothing is reported"); + assert_eq!(rig.tick(5.4, true), None, "turned on again, the displays are read again at once"); + assert_eq!(rig.reads.get(), 2); + rig.finish(sizes(2)); + assert_eq!(rig.tick(5.5, true), Some(got), "and the densities reported anew"); + } + + /// The displays are listed at most once a second, and not at all with the preference off. + #[test] + fn the_displays_are_listed_once_a_second_while_the_preference_is_on() { + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.tick(0.5, true); + assert_eq!(rig.lists.get(), 1); + rig.tick(1.0, true); + assert_eq!(rig.lists.get(), 2); + rig.tick(5.0, false); + assert_eq!(rig.lists.get(), 2, "off, nothing is asked of the system"); + } + + /// The main window moving to the other display reports that display's density without a new + /// reading; a display joining the list is read again, and while a display that changed is + /// read, the densities reported before stay. + #[test] + fn a_change_of_display_is_reported() { + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.finish(sizes(2)); + let left = rig.tick(0.1, true).and_then(|d| d.main.ppi()); + rig.current = 1; + let right = rig.tick(1.5, true).and_then(|d| d.main.ppi()); + assert!(left.is_some() && right.is_some() && left != right, "{left:?} then {right:?}"); + assert_eq!(rig.reads.get(), 1); + // A window drawn at 1.5 pixels a point (a fractional scale the display does not list) + // has fewer points to an inch than the display's own scale of 1 gives. + rig.window_scale = 1.5; + let scaled = rig.tick(2.6, true).and_then(|d| d.main.ppi()); + assert!(scaled.zip(right).is_some_and(|(s, r)| (s * 1.5 - r).abs() < 1e-9), "{scaled:?} at 1.5, {right:?} at 1"); + rig.window_scale = 1.0; + rig.displays.push(display("third", 3840)); + rig.tick(4.0, true); + assert_eq!(rig.reads.get(), 2, "a new display is read"); + rig.finish(sizes(3)); + rig.tick(4.5, true); + // The window's display changes resolution: until it is read again its density is unread. + rig.displays[1].size = PhysicalSize::new(2560, 1440); + assert_eq!(rig.tick(6.0, true).map(|d| d.main), Some(ScreenPpi::Unread), "the display is being read"); + assert_eq!(rig.reads.get(), 3); + rig.finish(sizes(3)); + let sharper = rig.tick(6.1, true).and_then(|d| d.main.ppi()); + assert!(sharper.zip(right).is_some_and(|(s, r)| s > r), "more pixels on the same glass: {sharper:?}, {right:?}"); + // winit still gives the window's display at its old resolution: it is found by its name. + let mut old = rig.displays[1].clone(); + old.size = PhysicalSize::new(1920, 1080); + rig.lagging = Some(old); + rig.window_scale = 1.25; + let lagging = rig.tick(7.2, true).and_then(|d| d.main.ppi()); + assert!(lagging.zip(sharper).is_some_and(|(l, s)| (l * 1.25 - s).abs() < 1e-9), "{lagging:?} from {sharper:?}"); + rig.lagging = None; + // It changes again and this time the reading fails: its density is unread. + rig.displays[1].size = PhysicalSize::new(3840, 2160); + let reading = rig.tick(8.5, true).unwrap_or_else(|| panic!("a report")); + assert_eq!(reading.main, ScreenPpi::Unread, "the display is being read: {reading:?}"); + assert!(reading.screens.iter().any(|s| s.rect[2] == 3840 && s.ppi == ScreenPpi::Unread), "listed where it is now, unread: {reading:?}"); + rig.finish(Err("the display server went away".into())); + assert_eq!(rig.tick(8.6, true), None, "the failed reading leaves it unread"); + } + + /// A display that changes while a reading runs is read as soon as that reading ends. + #[test] + fn a_change_during_a_reading_is_read_when_it_ends() { + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.displays[1].size = PhysicalSize::new(2560, 1440); + rig.tick(1.0, true); + assert_eq!(rig.reads.get(), 1, "one reading at a time"); + rig.finish(sizes(2)); + rig.tick(1.2, true); + assert_eq!(rig.reads.get(), 2, "the changed display is read at once"); + } + + /// A display whose size could not be read does not hold back the others, and the displays are + /// read again after a while. + #[test] + fn one_display_that_fails_leaves_the_others() { + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.finish(Ok(vec![Ok(Some(SIZES[0])), Err("no answer".into())])); + let got = rig.tick(0.1, true).unwrap_or_else(|| panic!("the densities")); + assert!(got.main.ppi().is_some() && got.screens[1].ppi == ScreenPpi::Unread, "the display that did not answer is unread: {got:?}"); + rig.tick(5.0, true); + assert_eq!(rig.reads.get(), 1, "not again at once"); + rig.tick(0.1 + RETRY_AFTER, true); + assert_eq!(rig.reads.get(), 2, "tried again"); + rig.finish(sizes(2)); + let full = rig.tick(11.0, true).unwrap_or_else(|| panic!("the densities")); + assert!(full.screens.iter().all(|s| s.ppi.ppi().is_some()), "{full:?}"); + rig.tick(30.0, true); + assert_eq!(rig.reads.get(), 2, "and left alone once every display was read"); + // A display joins, and the window's display, unchanged, fails to answer: it keeps its size. + rig.displays.push(display("third", 3840)); + rig.tick(32.0, true); + rig.finish(Ok(vec![Err("no answer".into()), Ok(Some(SIZES[1])), Ok(Some(SIZES[0]))])); + let kept = rig.tick(32.1, true).unwrap_or_else(|| panic!("the densities")); + assert!(kept.main.ppi().is_some() && kept.main == full.main, "{kept:?}"); + // A window on no display has its density unread. + rig.current = 9; + assert_eq!(rig.tick(34.0, true).map(|d| d.main), Some(ScreenPpi::Unread)); + // The window's display fails to answer the first reading: its density is unread, not a + // display without a size. + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.finish(Ok(vec![Err("no answer".into()), Ok(Some(SIZES[1]))])); + let first = rig.tick(0.1, true).unwrap_or_else(|| panic!("the densities")); + assert_eq!((first.main, first.screens[0].ppi), (ScreenPpi::Unread, ScreenPpi::Unread), "{first:?}"); + } + + /// A reading that fails, or a thread that cannot start, is tried again after a while; the + /// same displays are not read on every listing until then. + #[test] + fn a_failed_reading_is_tried_again() { + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.finish(Err("the display server went away".into())); + assert_eq!(rig.tick(1.0, true), None); + assert_eq!(rig.reads.get(), 1, "not again at once"); + rig.tick(5.0, true); + assert_eq!(rig.reads.get(), 1); + rig.tick(1.0 + RETRY_AFTER, true); + assert_eq!(rig.reads.get(), 2, "tried again"); + rig.finish(sizes(2)); + assert!(rig.tick(12.0, true).is_some_and(|d| d.main.ppi().is_some()), "and read"); + let mut rig = Rig::new(); + rig.fail_to_start = true; + rig.tick(0.0, true); + rig.tick(1.0 + RETRY_AFTER, true); + assert_eq!(rig.reads.get(), 2, "a thread that did not start is tried again too"); + } + + /// Displays that list the same are read again a while after the last reading, so a display + /// replaced by one on the same connector at the same resolution and scale gets its own size. + #[test] + fn displays_that_list_the_same_are_read_again_after_a_while() { + let mut rig = Rig::new(); + rig.tick(0.0, true); + rig.finish(sizes(2)); + let first = rig.tick(0.1, true).unwrap_or_else(|| panic!("the densities")); + rig.tick(0.1 + READ_AGAIN_AFTER - 1.0, true); + assert_eq!(rig.reads.get(), 1, "not before the time is up"); + rig.tick(0.1 + READ_AGAIN_AFTER, true); + assert_eq!(rig.reads.get(), 2, "read again"); + rig.finish(Ok(vec![Ok(Some(SIZES[1])), Ok(Some(SIZES[0]))])); + let replaced = rig.tick(0.2 + READ_AGAIN_AFTER, true).unwrap_or_else(|| panic!("the densities")); + assert!(replaced.main.ppi().is_some() && replaced.main != first.main, "the new panel's density: {first:?} then {replaced:?}"); + } } diff --git a/apps/vectorcraft/src/windows_display_size.rs b/apps/vectorcraft/src/windows_display_size.rs index a46c7989b2..fc7041ebd6 100644 --- a/apps/vectorcraft/src/windows_display_size.rs +++ b/apps/vectorcraft/src/windows_display_size.rs @@ -7,13 +7,14 @@ use windows::Win32::Graphics::Gdi::HMONITOR; use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_RAW_DPI}; -/// The horizontal and vertical pixels per inch of the monitor winit's handle `monitor` names, or -/// `None` when Windows reports none for it. -pub(crate) fn raw_dpi(monitor: isize) -> Option<[f64; 2]> { +/// The horizontal and vertical pixels per inch of the monitor winit's handle `monitor` names: +/// `None` when Windows reports no density for it, an error when the call fails. +pub(crate) fn raw_dpi(monitor: isize) -> Result, String> { let (mut x, mut y) = (0u32, 0u32); // SAFETY: `monitor` is a handle winit got from Windows for a connected monitor; a handle that - // has gone stale makes the call fail, which returns `None`. Both pointers point at live `u32`s - // for the length of the call. - unsafe { GetDpiForMonitor(HMONITOR(monitor as *mut core::ffi::c_void), MDT_RAW_DPI, &mut x, &mut y) }.ok()?; - (x > 0 && y > 0).then(|| [f64::from(x), f64::from(y)]) + // has gone stale makes the call fail, which returns an error. Both pointers point at live + // `u32`s for the length of the call. + unsafe { GetDpiForMonitor(HMONITOR(monitor as *mut core::ffi::c_void), MDT_RAW_DPI, &mut x, &mut y) } + .map_err(|e| format!("couldn't read a monitor's density: {e}"))?; + Ok((x > 0 && y > 0).then(|| [f64::from(x), f64::from(y)])) } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 2e0d0f9fe4..3abe86edee 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -84,6 +84,8 @@ pub struct Prefs { /// Artboard Options › Update While Dragging: the area outside the artboards stays darker while /// the Artboard tool moves or resizes an artboard; off, it draws as usual until the drag ends. pub artboard_update_while_dragging: bool, + /// General › Display Print Size at 100% Zoom (on by default): 100% shows an inch of the + /// document in an inch of the display. A preferences file without the key reads as on. pub display_print_size: bool, pub double_click_to_isolate: bool, pub transform_pattern_tiles: bool, @@ -477,7 +479,7 @@ impl Default for Prefs { type_glyph_bounds: false, fade_region_outside_artboard: true, artboard_update_while_dragging: true, - display_print_size: false, + display_print_size: true, double_click_to_isolate: true, transform_pattern_tiles: false, scale_corners: false, diff --git a/crates/engine/src/tests/prefs_file.rs b/crates/engine/src/tests/prefs_file.rs index bfe98b901b..98a756b1f7 100644 --- a/crates/engine/src/tests/prefs_file.rs +++ b/crates/engine/src/tests/prefs_file.rs @@ -197,3 +197,14 @@ fn hold_shortcut_preferences() { assert_eq!(restored.key_hold_delay(), 1.0); assert!(!restored.hold_shortcuts); } + +/// Display Print Size at 100% Zoom is on by default, also for saved preferences that predate the +/// key; a saved choice to turn it off stays off. +#[test] +fn display_print_size_is_on_unless_turned_off() { + assert!(Session::new().prefs.display_print_size); + let older: Prefs = serde_json::from_value(json!({"showToolTips": true})).unwrap(); + assert!(older.display_print_size); + let off: Prefs = serde_json::from_value(json!({"displayPrintSize": false})).unwrap(); + assert!(!off.display_print_size); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 47358b5842..e8c9b13b50 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -333,6 +333,9 @@ impl VectorcraftApp { let now = now_secs(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); + // A document that moved between the main window and a floating OS window, or opened, takes + // the density of the display that shows it. + self.settle_screen_ppi_if_changed(); self.refresh_replace_font_warning(false); updates_ui::tick(self, ctx); // Read the system clipboard only when that alone decides whether Paste is enabled. A diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index ae107769e6..383504b49c 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -22,8 +22,11 @@ impl VectorcraftApp { } self.views.truncate(docs.len()); self.views.extend(docs.iter().skip(self.views.len()).map(View::of)); + // A new view counts its zoom from the main window's display, where it is first shown. + let main = self.main_ppi(); for (view, doc) in self.views.iter_mut().zip(docs) { view.artboard = view.artboard.min(doc.doc.artboards.len().saturating_sub(1)); + view.shown_ppi.get_or_insert(main); } self.view_uids = docs.iter().map(|d| d.uid).collect(); panels::layers::retain_open_thumbs(&self.view_uids); @@ -105,33 +108,150 @@ impl VectorcraftApp { } /// The screen points an inch takes at 100% zoom with Display Print Size at 100% Zoom on, for - /// the display that shows the window; `None` with it off ([`crate::state::print_ppi`]). + /// the current window's display; `None` with it off ([`crate::state::print_ppi`]). pub(crate) fn print_ppi(&self) -> Option { - crate::state::print_ppi(self.session.prefs.display_print_size, self.services.screen_ppi) + self.print_ppi_of(crate::doc_windows::current(self)) } - /// Takes `ppi` as the measured density of the main window's display - /// ([`crate::Services::screen_ppi`]). With Display Print Size at 100% Zoom on, every document - /// window's view keeps its zoom percentage, so the art keeps its physical size on the new - /// display. Returns whether the density changed. + /// [`Self::print_ppi`] for window `w`: the density its view's zoom counts from, which is the + /// density of the display that shows it once [`Self::settle_screen_ppi`] has run. + pub(crate) fn print_ppi_of(&self, w: Option) -> Option { + let counted = w.and_then(|w| crate::doc_windows::view(self, w)?.shown_ppi); + let ppi = counted.unwrap_or_else(|| w.map_or(self.main_ppi(), |w| self.window_ppi(w))); + crate::state::print_ppi(self.session.prefs.display_print_size, ppi.ppi()) + } + + /// The density of the display that shows window `w`: its own OS window's when it floats in one + /// that the host found on a display, else the main window's ([`Self::main_ppi`]). + fn window_ppi(&self, w: crate::doc_windows::Win) -> crate::ScreenPpi { + crate::doc_windows::screen_ppi(self, w).unwrap_or(self.main_ppi()) + } + + /// The density the main window's views count from: the host's reading, or while the main + /// window's display has not answered, the last reading, so every view there counts from the + /// same density. + fn main_ppi(&self) -> crate::ScreenPpi { + match self.services.screen_ppi { + crate::ScreenPpi::Unread => self.canvas.windows.main_read.unwrap_or(crate::ScreenPpi::Unread), + read => read, + } + } + + /// Takes `ppi` as the density the host read for the main window's display, `None` for a + /// display that reports no size ([`crate::Services::screen_ppi`]), and settles the views + /// ([`Self::settle_screen_ppi`]). Returns whether the density changed. pub fn set_screen_ppi(&mut self, ppi: Option) -> bool { + self.set_screen_reading(crate::ScreenPpi::Read(ppi)) + } + + /// [`Self::set_screen_ppi`] with the host's reading, [`crate::ScreenPpi::Unread`] while the + /// main window's display is unknown or has not answered. + pub fn set_screen_reading(&mut self, ppi: crate::ScreenPpi) -> bool { if self.services.screen_ppi == ppi { return false; } - let before = self.print_ppi(); + // A switch of the preference made since the last frame applies before the reading does. + self.follow_print_size_switch(); self.services.screen_ppi = ppi; - if let (Some(before), Some(after)) = (before, self.print_ppi()) - && before != after - { - let k = after / before; - for v in &mut self.views { - v.zoom = (v.zoom * k).clamp(0.0313, 640.0); - } - self.canvas.windows.views.scale_zooms(k); + if ppi != crate::ScreenPpi::Unread && self.session.prefs.display_print_size { + self.canvas.windows.main_read = Some(ppi); } + self.settle_screen_ppi(); true } + /// Gives each window's view the density of the display that shows it. With Display Print Size + /// at 100% Zoom on, a view moved between two displays the host has read keeps its zoom + /// percentage (a display that reports no size counts 96 points to an inch), so the art keeps + /// its physical size on the new display; the views of other displays keep their zoom. At the + /// first reading of a view's display, a view that still has the zoom a fit or the document's + /// saved view gave it keeps that zoom, and any other view keeps its percentage, counted from + /// 96 points to an inch until then. + pub(crate) fn settle_screen_ppi(&mut self) { + for w in crate::doc_windows::windows(self) { + self.settle_window_ppi(w, true); + } + } + + /// [`Self::settle_screen_ppi`] for window `w` alone. With `keep` false (a fit made for the + /// window), the view counts from the display's reading, or from its first reading still to + /// come, without a change of zoom. + pub(crate) fn settle_window_ppi(&mut self, w: crate::doc_windows::Win, keep: bool) { + let on = self.session.prefs.display_print_size; + let now = self.window_ppi(w); + let reading = crate::doc_windows::screen_ppi(self, w).unwrap_or(self.services.screen_ppi); + let Some(v) = crate::doc_windows::view_mut(self, w) else { return }; + // Off, a view counts from no reading, so the first one after the preference is turned on + // keeps the zoom chosen meanwhile. + if !on { + v.shown_ppi = Some(crate::ScreenPpi::Unread); + return; + } + if !keep { + v.shown_ppi = Some(reading); + return; + } + // A display that has not answered yet leaves the view counting from the last one read, so + // the answer, when it comes, keeps the zoom percentage. + let crate::ScreenPpi::Read(after) = now else { + v.shown_ppi.get_or_insert(now); + return; + }; + let before = match v.shown_ppi { + Some(crate::ScreenPpi::Read(before)) => Some(before), + _ if v.fit_zoom == Some(v.zoom) => None, + _ => Some(None), + }; + if let Some(before) = before + && before != after + && let (Some(b), Some(a)) = (crate::state::print_ppi(on, before), crate::state::print_ppi(on, after)) + { + v.zoom = (v.zoom * a / b).clamp(0.0313, 640.0); + } + v.shown_ppi = Some(now); + } + + /// [`Self::settle_screen_ppi`] when the main window's density or a floating window's changed + /// since it last ran from here, or a window started or stopped floating, or Presentation Mode + /// started or ended. With Display Print Size at 100% Zoom off, the desktop host does not read + /// the displays: every density read before is forgotten, so the readings after the preference + /// is turned on again count as first readings. + pub(crate) fn settle_screen_ppi_if_changed(&mut self) { + self.follow_print_size_switch(); + let key = (self.services.screen_ppi, crate::doc_windows::floating_ppi(self)); + if self.canvas.windows.settled.as_ref() != Some(&key) { + self.settle_screen_ppi(); + self.canvas.windows.settled = Some(key); + } + } + + /// Takes in a change of Display Print Size at 100% Zoom since this last ran: turned off, every + /// density read before is forgotten; turned on, every view's zoom counts as the one its first + /// reading keeps. + fn follow_print_size_switch(&mut self) { + let off = !self.session.prefs.display_print_size; + let was_off = std::mem::replace(&mut self.canvas.windows.print_size_off, off); + if off && !was_off { + crate::doc_windows::forget_ppi(self); + self.services.screen_ppi = crate::ScreenPpi::Unread; + self.canvas.windows.main_read = None; + self.services.screens.clear(); + for w in crate::doc_windows::windows(self) { + if let Some(v) = crate::doc_windows::view_mut(self, w) { + v.shown_ppi = Some(crate::ScreenPpi::Unread); + } + } + } + if was_off && !off { + // The zoom chosen while it was off stays when the displays are read. + for w in crate::doc_windows::windows(self) { + if let Some(v) = crate::doc_windows::view_mut(self, w) { + v.fit_zoom = Some(v.zoom); + } + } + } + } + pub fn view_mut(&mut self) -> Option<&mut View> { self.sync_views(); let i = self.session.active_index()?; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b366665d4..f0a3402f38 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -51,8 +51,10 @@ use fill::fill_uncovered; #[cfg(test)] use fill::{fill_view, polygon_area}; #[cfg(test)] +use grid::PIXEL_GRID; +#[cfg(test)] use grid::ruler_rects; -use grid::{LineLook, PIXEL_GRID, PIXEL_GRID_ZOOM, checker, clip_segment, grid, ruler_input, rulers, rulers_hidden, textured_quad, view_bounds}; +use grid::{LineLook, PIXEL_GRID_ZOOM, checker, clip_segment, grid, pixel_grid, ruler_input, rulers, rulers_hidden, textured_quad, view_bounds}; pub(crate) use grid::{RulerScale, checker_texture, checker_tile, ruler_label, ruler_origin_dragging}; #[cfg(test)] pub(crate) use grid::{TRANSPARENCY_GRID, vertical_label_height}; @@ -410,12 +412,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { grid(&painter, &xf, doc.grid.spacing, doc.grid.subdivisions, look); } // The pixel grid (Guides & Grid › Show Pixel Grid (Above 600% Zoom)): in Pixel Preview from - // 600% zoom, a line at every document pixel over the art, so the pixels it rasterizes to show. + // 600% zoom as the zoom field counts it, 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(); 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 }); + let shown = crate::state::zoom_display_percent(v.zoom, app.print_ppi()) / 100.0; + if app.ui.view.pixel_preview && shown >= PIXEL_GRID_ZOOM - 1e-9 && app.session.prefs.show_pixel_grid { + pixel_grid(&painter, &xf); } artboard_outlines(app, ui, &painter, &xf, &t); if app.ui.view.guides_shown() { diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 97c68269fb..34107eb455 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -127,12 +127,23 @@ pub(super) fn clip_segment(a: Pos2, b: Pos2, r: egui::Rect) -> Option<(Pos2, Pos /// (left out when they would crowd). In the Dots style, a dot where gridlines cross the /// subdivisions instead. pub(super) fn grid(p: &egui::Painter, xf: &Xf, spacing: f64, subdiv: u32, look: LineLook) { + grid_lines(p, xf, spacing, subdiv, look, 4.0); +} + +/// The pixel grid (Guides & Grid › Show Pixel Grid (Above 600% Zoom)): a line at every document +/// pixel, however close the lines are; the caller shows it from 600%. +pub(super) fn pixel_grid(p: &egui::Painter, xf: &Xf) { + grid_lines(p, xf, 1.0, 1, LineLook { color: PIXEL_GRID, dots: false }, 0.0); +} + +/// [`grid`], left out when its lines would be less than `crowd` screen points apart. +fn grid_lines(p: &egui::Painter, xf: &Xf, spacing: f64, subdiv: u32, look: LineLook, crowd: f64) { // The painter clips to the canvas. let view = view_bounds(xf); let sub = spacing / subdiv.max(1) as f64; let step = if sub * xf.zoom >= 6.0 { sub } else { spacing }; // Dots crowd sooner than lines. - if step * xf.zoom < 4.0 || (look.dots && spacing * xf.zoom < 8.0) { + if step * xf.zoom < crowd || (look.dots && spacing * xf.zoom < 8.0) { return; } let major = |v: f64| (v / spacing - (v / spacing).round()).abs() < 1e-6; diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 63d89f2be2..8f4361f04c 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -522,6 +522,7 @@ fn fit_pane(v: &mut View, doc: &vectorcraft_doc::Document, rect: egui::Rect, ui_ v.zoom = fit_zoom(rect, target, v.rotation, ui_zoom); v.center = target.center(); v.fitted = true; + v.fit_zoom = Some(v.zoom); } } @@ -545,8 +546,12 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo let Some(st) = app.session.documents().get(w.0) else { return false }; let doc = st.doc.clone(); let ui_zoom = ui.ctx().zoom_factor(); - if let Some(v) = crate::doc_windows::view_mut(app, w).filter(|v| !v.fitted) { - fit_pane(v, &doc, rect, ui_zoom); + if crate::doc_windows::view(app, w).is_some_and(|v| !v.fitted) { + // The fit is made for the display the pane is on (Display Print Size at 100% Zoom). + app.settle_window_ppi(w, false); + if let Some(v) = crate::doc_windows::view_mut(app, w) { + fit_pane(v, &doc, rect, ui_zoom); + } } let v = crate::doc_windows::view(app, w).copied().unwrap_or_default(); let Some(st) = app.session.documents().get(w.0) else { return false }; diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3cbe57eefd..b72980e082 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4822,6 +4822,8 @@ fn pixel_grid_shows_in_pixel_preview_from_600_percent() { (lines.len(), lines.first().is_some_and(|&i| i > image)) }; app.ui.view.pixel_preview = true; + // One document point per screen point at 100%, so 600% is a zoom of 6. + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); app.view_mut().unwrap().zoom = 8.0; let (n, over) = pixel_lines(&mut app); assert!(n >= 150, "a line every 8 px across the 800 × 600 canvas: {n}"); @@ -4830,6 +4832,20 @@ fn pixel_grid_shows_in_pixel_preview_from_600_percent() { assert_eq!(pixel_lines(&mut app).0, 0, "below 600%: none"); app.view_mut().unwrap().zoom = 6.0; assert!(pixel_lines(&mut app).0 >= 200, "from 600%"); + // With Display Print Size at 100% Zoom on, 600% counts from Actual Size, as the zoom field + // shows it: 96 points to an inch make a zoom of 6 show as 450%, and 8 as 600%. + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + assert_eq!(pixel_lines(&mut app).0, 0, "450%: none"); + app.view_mut().unwrap().zoom = 8.0; + assert!(pixel_lines(&mut app).0 >= 150, "600%"); + // At 2.5× UI Scaling the lines are 3.2 interface points apart, and still drawn. + ctx.set_zoom_factor(2.5); + pixel_lines(&mut app); + assert!(pixel_lines(&mut app).0 > 0, "600% at 2.5× UI Scaling"); + ctx.set_zoom_factor(1.0); + pixel_lines(&mut app); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + app.view_mut().unwrap().zoom = 6.0; app.ui.view.pixel_preview = false; assert_eq!(pixel_lines(&mut app).0, 0, "out of Pixel Preview: none"); app.ui.view.pixel_preview = true; @@ -6035,7 +6051,7 @@ fn scrolls_and_pans_move_a_lowered_frame_by_whole_pixels() { /// another document, or when the device pixels a point changed. #[test] fn a_scrolls_leftover_pixel_part_carries_only_to_the_same_view() { - let view = View { zoom: 1.0, center: Point::new(100.0, 100.0), fitted: true, rotation: 0.0, artboard: 0, outline: false }; + let view = View { zoom: 1.0, center: Point::new(100.0, 100.0), fitted: true, ..View::default() }; let mut v = view; let rest = scroll_by(&mut v, 1, (1.0, 1.0), vec2(0.4, -0.3), ScrollRest::default()); assert_eq!(v.center, view.center, "less than half a pixel does not move the view"); @@ -8535,8 +8551,9 @@ fn a_rotation_with_fingers_on_a_touch_screen_turns_nothing() { assert_eq!(app.view().unwrap().rotation, before, "the view does not turn"); } -/// General › Display Print Size at 100% Zoom (#394): `view.actualSize` is one document point per -/// screen point with it off, and 96 screen points per document inch with it on. +/// General › Display Print Size at 100% Zoom (#394, #9051): on by default, `view.actualSize` shows +/// a document inch in 96 screen points where no display was measured; off, one document point +/// per screen point. #[test] fn view_actual_size_follows_display_print_size() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -8544,10 +8561,10 @@ fn view_actual_size_follows_display_print_size() { app.canvas_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(460.0, 260.0))); app.run("view.setZoom", json!({"zoom": 250})).unwrap(); app.run("view.actualSize", json!({})).unwrap(); - assert!((app.view().unwrap().zoom - 1.0).abs() < 1e-12, "off by default: 100% is 1:1"); - app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + assert!((app.view().unwrap().zoom - 96.0 / 72.0).abs() < 1e-12, "on by default: an inch is 96 screen points"); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); app.run("view.actualSize", json!({})).unwrap(); - assert!((app.view().unwrap().zoom - 96.0 / 72.0).abs() < 1e-12, "an inch is 96 screen points"); + assert!((app.view().unwrap().zoom - 1.0).abs() < 1e-12, "off, 100% is 1:1"); } /// #9051: with Display Print Size on, Actual Size shows a document inch in an inch of the display @@ -8561,7 +8578,10 @@ fn view_actual_size_fills_an_inch_of_the_measured_display() { let rect = egui::Rect::from_min_size(Pos2::ZERO, vec2(460.0, 260.0)); app.canvas_rect = Some(rect); app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + app.run("view.fitArtboard", json!({})).unwrap(); + let fitted = app.view().unwrap().zoom; assert!(app.set_screen_ppi(Some(127.0))); + assert_eq!(app.view().unwrap().zoom, fitted, "the first measurement leaves a fitted view alone"); let inch = |v: &View| { let xf = Xf::new(rect, v); f64::from(xf.to_screen(Point::new(72.0, 0.0)).x - xf.to_screen(Point::new(0.0, 0.0)).x) @@ -8577,12 +8597,56 @@ fn view_actual_size_fills_an_inch_of_the_measured_display() { assert!((inch(&first) - 91.0).abs() < 1e-3, "the other window's 100% still fills an inch"); assert_eq!(crate::state::zoom_label(first.zoom, app.print_ppi()), "100%"); assert_eq!(crate::state::zoom_label(app.view().unwrap().zoom, app.print_ppi()), "150%"); + assert!(app.set_screen_ppi(None), "the window moved to a display that reports no size"); + let first = *crate::doc_windows::view(&app, (0, 1)).unwrap(); + assert!((first.zoom * 72.0 - 96.0).abs() < 1e-9, "100% there is 96 points to an inch: {}", first.zoom * 72.0); + assert!(app.set_screen_ppi(Some(91.0)), "and back"); + let first = *crate::doc_windows::view(&app, (0, 1)).unwrap(); + assert!((first.zoom * 72.0 - 91.0).abs() < 1e-9, "100% fills an inch again: {}", first.zoom * 72.0); + assert!(app.set_screen_reading(crate::ScreenPpi::Unread), "the window moved to a display that has not answered"); + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + app.run("view.actualSize", json!({})).unwrap(); + assert!((app.view().unwrap().zoom * 72.0 - 91.0).abs() < 1e-9, "a document opened meanwhile counts from the same density"); + assert!(app.set_screen_ppi(Some(127.0)), "and it answers"); + assert!((app.view().unwrap().zoom * 72.0 - 127.0).abs() < 1e-9, "both keep 100%"); + let first = *crate::doc_windows::view(&app, (0, 1)).unwrap(); + assert!((first.zoom * 72.0 - 127.0).abs() < 1e-9, "100% fills an inch there: {}", first.zoom * 72.0); app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); let zoom = app.view().unwrap().zoom; - assert!(app.set_screen_ppi(Some(127.0))); + assert!(app.set_screen_ppi(Some(110.0))); assert_eq!(app.view().unwrap().zoom, zoom, "off, a move leaves the zoom alone"); app.run("view.actualSize", json!({})).unwrap(); assert!((app.view().unwrap().zoom - 1.0).abs() < 1e-12, "and 100% stays one point per point"); + // Off, the densities read before are forgotten: the first reading after it is turned on again + // leaves the zoom chosen meanwhile alone. + app.settle_screen_ppi_if_changed(); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + assert!(app.set_screen_ppi(Some(91.0))); + assert!((app.view().unwrap().zoom - 1.0).abs() < 1e-12, "the first reading after turning it on keeps the zoom"); +} + +/// #9051: Actual Size chosen before the window's display is first read keeps 100% when the +/// reading arrives, and a fit made while the window's new display is being read stays the fit +/// when that reading arrives. +#[test] +fn actual_size_and_fits_made_before_a_reading_keep_their_meaning() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(460.0, 260.0))); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + app.run("view.actualSize", json!({})).unwrap(); + assert!((app.view().unwrap().zoom * 72.0 - 96.0).abs() < 1e-9, "unread, an inch is 96 points"); + assert!(app.set_screen_ppi(Some(127.0))); + assert!((app.view().unwrap().zoom * 72.0 - 127.0).abs() < 1e-9, "the reading keeps 100%: {}", app.view().unwrap().zoom * 72.0); + assert!(app.set_screen_reading(crate::ScreenPpi::Unread), "the window moved to a display being read"); + app.run("view.fitArtboard", json!({})).unwrap(); + let fitted = app.view().unwrap().zoom; + assert!(app.set_screen_ppi(Some(190.0))); + assert_eq!(app.view().unwrap().zoom, fitted, "the fit was made for this display"); + assert!(app.set_screen_reading(crate::ScreenPpi::Unread), "and to another display being read"); + app.run("view.actualSize", json!({})).unwrap(); + assert!(app.set_screen_ppi(Some(110.0))); + assert!((app.view().unwrap().zoom * 72.0 - 110.0).abs() < 1e-9, "Actual Size there is 100%: {}", app.view().unwrap().zoom * 72.0); } /// Fit Artboard in Window fits the artboard as a rotated view shows it: at 45° every corner is @@ -8639,7 +8703,7 @@ fn animated_zoom_scrubs_and_holds_else_the_zoom_tool_zooms_to_an_area() { press(&mut app, vec2(-100.0, 0.0), 0); assert!((app.view().unwrap().zoom - z0).abs() < 1e-6, "and back to the left"); press(&mut app, vec2(0.0, 0.0), 0); - assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(z0, true, None), "a click steps"); + assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(z0, true, app.print_ppi()), "a click steps"); let z2 = app.view().unwrap().zoom; press(&mut app, vec2(0.0, 0.0), 40); assert!(app.view().unwrap().zoom > z2 * 1.2, "held, it zooms on"); @@ -8994,9 +9058,9 @@ fn cmd_space_zooms_and_space_pans_whatever_the_tool() { let z0 = app.view().unwrap().zoom; drag(&mut app, Modifiers::COMMAND, at); let z1 = app.view().unwrap().zoom; - assert_eq!(z1, crate::state::next_zoom(z0, true, None), "Cmd+Space click zooms in"); + assert_eq!(z1, crate::state::next_zoom(z0, true, app.print_ppi()), "Cmd+Space click zooms in"); drag(&mut app, Modifiers::COMMAND | Modifiers::ALT, at); - assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(z1, false, None), "Cmd+Alt+Space click zooms out"); + assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(z1, false, app.print_ppi()), "Cmd+Alt+Space click zooms out"); assert_eq!(app.session.active().unwrap().doc.art_bounds(), None, "the Rectangle tool drew nothing"); // Space alone pans, with the Zoom tool too. app.select_tool("zoom"); @@ -9044,7 +9108,7 @@ fn space_types_a_space_while_editing_text_and_does_not_pan() { assert_eq!(shown(&mut app), CursorIcon::ZoomIn, "Cmd+Space shows the magnifier"); typing_frame(&mut app, &ctx, vec![button(at, true, Modifiers::COMMAND)]); typing_frame(&mut app, &ctx, vec![button(at, false, Modifiers::COMMAND)]); - assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(before.zoom, true, None), "Cmd+Space click zooms in"); + assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(before.zoom, true, app.print_ppi()), "Cmd+Space click zooms in"); typing_frame(&mut app, &ctx, vec![space(false, Modifiers::COMMAND), Event::ModifiersChanged(Modifiers::NONE)]); assert_eq!(plain(&app, id), "a ", "the text is as typed"); } @@ -9154,7 +9218,7 @@ fn space_shift_drag_rotates_the_view_whatever_the_tool() { assert_eq!((panned.rotation, panned.zoom), (v.rotation, v.zoom)); assert_ne!(panned.center, v.center, "Space pans"); drag(&mut app, Modifiers::COMMAND | Modifiers::SHIFT, true, c, c); - assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(v.zoom, true, None), "Cmd+Shift+Space click zooms in"); + assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(v.zoom, true, app.print_ppi()), "Cmd+Shift+Space click zooms in"); assert_eq!(app.view().unwrap().rotation, v.rotation); // The Rotate View tool's Shift still rounds to 15°. app.select_tool("rotateView"); diff --git a/crates/ui-egui/src/canvas/tests_ui_scaling.rs b/crates/ui-egui/src/canvas/tests_ui_scaling.rs index 335f332529..1874fef69b 100644 --- a/crates/ui-egui/src/canvas/tests_ui_scaling.rs +++ b/crates/ui-egui/src/canvas/tests_ui_scaling.rs @@ -25,11 +25,13 @@ fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, (native, ui_zoom): (f32, } /// A 512 × 512 pt document shown at `native` device pixels a point and UI Scaling `ui_zoom`, with a -/// controlled render worker, and the receiver of the frames it is asked to render. +/// controlled render worker, and the receiver of the frames it is asked to render. Display Print +/// Size at 100% Zoom is off, so 100% is one document point per screen point. fn shown(native: f32, ui_zoom: f32) -> (VectorcraftApp, egui::Context, std::sync::mpsc::Receiver) { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); app.run("file.new", json!({"width": 512, "height": 512})).unwrap(); app.canvas.worker_started = true; let (worker, jobs, _done) = crate::render_worker::Worker::test_channel(); diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index 825db3940d..b2714f2645 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -30,6 +30,12 @@ pub fn fit(app: &mut VectorcraftApp, how: &str) { _ => st.doc.artboards.get(current).or(st.doc.artboards.first()).map(|a| a.rect), }; let Some(target) = target else { return }; + // A fit to the window is made for the display the window is on now; Actual Size counts from + // the density the view counts from, which a reading still to come rescales (Display Print + // Size at 100% Zoom). + if let Some(w) = crate::doc_windows::current(app) { + app.settle_window_ppi(w, how == "view.actualSize"); + } let zoom = if how == "view.actualSize" { actual_size_zoom(app.print_ppi()) } else { @@ -39,6 +45,8 @@ pub fn fit(app: &mut VectorcraftApp, how: &str) { v.center = target.center(); v.fitted = true; v.zoom = zoom; + // Actual Size is a percentage; the other fits are made for the window. + v.fit_zoom = (how != "view.actualSize").then_some(zoom); } /// The zoom at which `target`, turned `rotation` degrees with the view, fits in `rect` (points of diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 8149c3cb5a..693fcac30d 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -17,7 +17,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { .selected_text(egui::RichText::new(zoom_label(zoom, print)).size(11.5)) .width(76.0) .show_ui(ui, |ui| { - for z in ZOOM_STOPS.iter().rev() { + // The stops the zoom range reaches, which counts from Actual Size. + let (lo, hi) = (crate::state::zoom_display_percent(0.0313, print), crate::state::zoom_display_percent(640.0, print)); + for z in ZOOM_STOPS.iter().rev().filter(|z| (lo - 1e-6..=hi + 1e-6).contains(*z)) { if ui .selectable_label((z - shown).abs() < 0.01, zoom_label(crate::state::zoom_from_display_percent(*z, print), print)) .clicked() diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index e27877ca11..d90183551e 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -31,7 +31,7 @@ fn view_tab_name(d: &vectorcraft_engine::DocState, number: Option) -> Strin fn window_tab_title(app: &VectorcraftApp, w: crate::doc_windows::Win, d: &vectorcraft_engine::DocState) -> String { let view = crate::doc_windows::view(app, w); let zoom = view.map_or(1.0, |v| v.zoom); - view_tab_title(d, crate::doc_windows::label(app, w), zoom, view.is_some_and(|v| v.outline), app.print_ppi()) + view_tab_title(d, crate::doc_windows::label(app, w), zoom, view.is_some_and(|v| v.outline), app.print_ppi_of(Some(w))) } /// The title of window `w`'s tab and floating window ([`crate::doc_windows`]). diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index d5a5743744..273cc3484f 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1473,7 +1473,7 @@ fn the_artboard_navigator_goes_to_artboards_and_fitting_shows_the_current_one() app.run("view.fitArtboard", json!({})).unwrap(); assert_eq!(at(&app), (1, Point::new(320.0, 50.0))); app.run("view.actualSize", json!({})).unwrap(); - assert_eq!((at(&app).1, app.view().unwrap().zoom), (Point::new(320.0, 50.0), 1.0)); + assert_eq!((at(&app).1, app.view().unwrap().zoom), (Point::new(320.0, 50.0), crate::state::zoom_baseline(app.print_ppi()))); click(&mut app, buttons[0]); assert_eq!(at(&app), (0, Point::new(100.0, 50.0)), "first"); // The command also takes an index, clamped to the last artboard. diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 218312750d..5b0475a168 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -280,6 +280,12 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { // The display profile the canvas is drawn through, or why none (Preferences › // Performance › Use Monitor Profile for Canvas). "displayProfile": app.display_profile.status(app.session.prefs.monitor_profile_display), + // With Preferences › General › Display Print Size at 100% Zoom on, the measured density of + // the main window's display in points per inch (null where none was measured), and the + // points an inch takes at 100% in the current window. Both are null with it off, when the + // desktop app does not measure the displays. + "screenPpi": app.session.prefs.display_print_size.then(|| app.services.screen_ppi.ppi()).flatten(), + "printPpi": app.print_ppi(), // Window › Arrange › Tile and its layout (not saved, so not in `ui`) and the panes the // last frame drew: each one's document index, view number (Window › New Window) and rect. // Canvas coordinates map to the current window's pane, inside its rulers and scroll bars diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 96ffd47261..c7655913f4 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -2,7 +2,7 @@ use serde_json::{Value, json}; use vectorcraft_engine::Session; use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; -use super::{ControlRequest, MAX_DIALOG_FIELDS, Outcome, handle}; +use super::{ControlRequest, MAX_DIALOG_FIELDS, Outcome, handle, inspect}; use crate::state::Dialog; use crate::{Services, VectorcraftApp}; @@ -977,6 +977,23 @@ fn ui_commands_refuse_params_of_the_wrong_type() { assert_eq!(app.view().map(|v| v.zoom), Some(crate::state::zoom_from_display_percent(100.0, app.print_ppi()))); } +/// `ui.inspect` gives the measured density of the main window's display and the points an inch +/// takes at 100% while Display Print Size at 100% Zoom is on, and neither with it off (#9051). +#[test] +fn inspect_reports_the_display_density() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let ctx = egui::Context::default(); + let got = inspect(&app, &ctx); + assert_eq!((got["screenPpi"].clone(), got["printPpi"].as_f64()), (Value::Null, Some(96.0)), "nothing measured: an inch is 96 points"); + app.set_screen_ppi(Some(127.0)); + let got = inspect(&app, &ctx); + assert_eq!((got["screenPpi"].as_f64(), got["printPpi"].as_f64()), (Some(127.0), Some(127.0))); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + let got = inspect(&app, &ctx); + assert_eq!((got["screenPpi"].clone(), got["printPpi"].clone()), (Value::Null, Value::Null)); +} + #[test] fn synthetic_pointer_backquote_keeps_solid_object_in_place() { let mut app = VectorcraftApp::new(Session::new(), Services::default()); diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index ba324558d3..f565fcb4a8 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -68,6 +68,14 @@ pub struct DocWindow { /// While its OS window's tab is dragged: where the pointer is from the window's top-left /// corner, on the screen. grab: Option, + /// The density of the display that shows its OS window ([`crate::services::screen_ppi_at`]), + /// while the window is on a display the host listed; `None` before that, while it is on none + /// of them, and inside the main window, where the window counts the main window's density. + ppi: Option, + /// The last frame drew it as an OS window of its own. + os: bool, + /// A display that shows its OS window has been read since it opened. + was_read: bool, } /// [`DocWindow::fit`]: a body size, and a view's zoom and center. @@ -75,7 +83,61 @@ type Fit = (egui::Vec2, f64, vectorcraft_geom::Point); impl DocWindow { fn new((uid, view): (u64, u32), place: egui::Rect) -> Self { - Self { uid, view, place, number: 0, generation: 0, screen: None, focused: false, body: None, fit: None, grab: None } + Self { + uid, + view, + place, + number: 0, + generation: 0, + screen: None, + focused: false, + body: None, + fit: None, + grab: None, + ppi: None, + os: false, + was_read: false, + } + } +} + +/// The density of the display that shows floating window `x`'s OS window: read once the window +/// was found on a display, unread until then; `None` for a window inside the main window, which +/// counts the main window's density, and for the window Presentation Mode shows there. +fn window_ppi(app: &VectorcraftApp, x: &DocWindow) -> Option { + if presenting(app) && current(app).and_then(|w| key(app, w)) == Some((x.uid, x.view)) { + return None; + } + x.ppi.or(x.os.then_some(crate::ScreenPpi::Unread)) +} + +/// [`window_ppi`] for window `w`; `None` for a window that does not float. +pub(crate) fn screen_ppi(app: &VectorcraftApp, w: Win) -> Option { + let (u, n) = key(app, w)?; + window_ppi(app, app.ui.floating.iter().find(|x| x.uid == u && x.view == n)?) +} + +/// A floating window ([`views::key`]) with the density of the display that shows it +/// ([`window_ppi`]). +pub(crate) type FloatingPpi = ((u64, u32), Option); + +/// Each floating window with the density of the display that shows it. +pub(crate) fn floating_ppi(app: &VectorcraftApp) -> Vec { + app.ui.floating.iter().map(|x| ((x.uid, x.view), window_ppi(app, x))).collect() +} + +/// Forgets the densities found for the floating windows' displays. +pub(crate) fn forget_ppi(app: &mut VectorcraftApp) { + for x in &mut app.ui.floating { + x.ppi = None; + } +} + +/// Sets the density of the display that shows floating window `key`'s ([`views::key`]) OS window. +#[cfg(test)] +pub(crate) fn set_window_ppi(app: &mut VectorcraftApp, (uid, view): (u64, u32), ppi: Option) { + if let Some(x) = app.ui.floating.iter_mut().find(|x| x.uid == uid && x.view == view) { + x.ppi = Some(crate::ScreenPpi::Read(ppi)); } } @@ -101,6 +163,14 @@ pub struct Windows { /// in ([`crate::canvas::note_drop`]): each window's view ([`views::key`]), the part of its pane /// inside its rulers and scroll bars in the main window's points, and the layer it drew in. pub(crate) drops: Vec<((u64, u32), egui::Rect, egui::LayerId)>, + /// The main window's density and the floating windows' ([`floating_ppi`]) when the views were + /// last settled each frame ([`VectorcraftApp::settle_screen_ppi_if_changed`]). + pub(crate) settled: Option<(crate::ScreenPpi, Vec)>, + /// Display Print Size at 100% Zoom was off when the views were last settled each frame. + pub(crate) print_size_off: bool, + /// The last density the host read for the main window's display; the main window's views + /// count from it while its display has not answered. + pub(crate) main_read: Option, } impl Windows { @@ -382,6 +452,8 @@ struct Shown { body: Option, /// [`DocWindow::fit`] after this frame. fit: Option, + /// The density of the display that shows its OS window, when it was found on one. + ppi: Option, } /// Draw the floating document windows, after the main window's canvas. Call once per frame from @@ -452,7 +524,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { for w in app.ui.floating.clone() { let Some(win) = find(app, (w.uid, w.view)) else { continue }; let raised = raise == Some((w.uid, w.view)); - let shown = if native { os_window(app, ctx, &w, (win, blocked), raised) } else { app_window(app, ctx, &w, (win, blocked), raised) }; + let mut shown = if native { os_window(app, ctx, &w, (win, blocked), raised) } else { app_window(app, ctx, &w, (win, blocked), raised) }; + take_window_ppi(app, ctx, ((w.uid, w.view), native), win, &mut shown); if blocked { continue; } @@ -540,6 +613,46 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (win, blocked): (Win, bool) (pressed, rect, fit) } +/// Takes the density of the display that `shown`, floating window `key`'s ([`views::key`]) window +/// `win`, was found on, and whether it is an OS window of its own (`os`), and settles the views +/// when the density changed ([`VectorcraftApp::settle_window_ppi`]). A view that still has the +/// zoom its window fitted it to at the window's present size keeps that zoom, and keeps fitting +/// the window. +fn take_window_ppi(app: &mut VectorcraftApp, ctx: &egui::Context, ((uid, number), os): ((u64, u32), bool), win: Win, shown: &mut Shown) { + let Some(x) = app.ui.floating.iter_mut().find(|x| x.uid == uid && x.view == number) else { return }; + x.os = os; + // Drawn inside the main window, it counts the main window's density. + if !os { + shown.ppi = None; + if x.ppi.take().is_some() { + app.settle_window_ppi(win, true); + } + return; + } + // Off every display the host listed (moved past their edges, or its display went), it is + // unread: its view counts from the density it was shown at until a display is found again. + if shown.ppi.is_none() { + if x.ppi.take().is_some() { + app.settle_window_ppi(win, true); + ctx.request_repaint(); + } + return; + } + if x.ppi == shown.ppi { + return; + } + // Its first reading, or a fit made this frame, is a baseline; a move from a display read + // before keeps the zoom percentage. + let first = !x.was_read; + let fitted_now = shown.fit.is_some() && shown.fit != x.fit; + x.ppi = shown.ppi; + x.was_read |= matches!(shown.ppi, Some(crate::ScreenPpi::Read(_))); + let size = shown.body.map(|b| b.size()); + let following = view(app, win).is_some_and(|v| v.fitted && shown.fit.is_some_and(|(s, z, c)| Some(s) == size && z == v.zoom && c == v.center)); + app.settle_window_ppi(win, !(following && (first || fitted_now))); + ctx.request_repaint(); +} + /// Window `win`'s floating window `w` as an OS window of its own, `blocked` by a modal or not; /// `raise` brings it to the front. Its tab is at the top of the window, above its body. fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (win, blocked): (Win, bool), raise: bool) -> Shown { @@ -595,7 +708,8 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (win, (events, Some(inp.modifiers)) }); } - Shown { close, activate, over_strip, dock, focused, body: Some(rect), fit } + let ppi = crate::services::screen_ppi_at(&app.services.screens, ui.ctx()); + Shown { close, activate, over_strip, dock, focused, body: Some(rect), fit, ppi } }); if !forwarded.0.is_empty() { crate::panel_docking::forward_keys(app, ctx, forwarded.0, forwarded.1); @@ -676,7 +790,7 @@ fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (win let moved = mover.map_or((false, false), |r| (r.dragged(), r.drag_stopped())); let pointer = ctx.input(|inp| inp.pointer.latest_pos()); let over_strip = !blocked && (moved.0 || moved.1) && app.canvas.windows.strip.zip(pointer).is_some_and(|(strip, p)| strip.contains(p)); - Shown { close: !open, activate, over_strip, dock: over_strip && moved.1, focused: false, body: rect, fit } + Shown { close: !open, activate, over_strip, dock: over_strip && moved.1, focused: false, body: rect, fit, ppi: None } } /// The host's rewrites of raw input ([`crate::services::Services::native_input_hook`]) for the diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 7fede442da..d4f280267b 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -1226,3 +1226,71 @@ fn an_os_windows_pane_is_not_a_place_to_release_art_in_the_main_windows_points() app_frame(&mut app, &ctx, vec![]); assert!(app.canvas.windows.drops.is_empty(), "nor is the main window's pane while an OS window holds the canvas"); } + +/// #9051: an OS window's display is the one at the window's scale factor that covers most of it. A +/// 1× display to the right of a 2× one on macOS starts, in pixels, inside the 2× display's pixels. +#[test] +fn an_os_window_finds_the_display_at_its_own_scale() { + use crate::ScreenPpi::Read; + use crate::services::{ScreenDensity, screen_ppi_at}; + let screens = [ + ScreenDensity { rect: [0, 0, 3024, 1964], scale: 2.0, ppi: Read(Some(127.0)) }, + ScreenDensity { rect: [1512, 0, 1920, 1080], scale: 1.0, ppi: Read(Some(92.0)) }, + ]; + let at = |center: Pos2, native: f32| { + let ctx = egui::Context::default(); + let mut input = egui::RawInput::default(); + let info = input.viewports.entry(egui::ViewportId::ROOT).or_default(); + info.native_pixels_per_point = Some(native); + info.outer_rect = Some(egui::Rect::from_center_size(center, vec2(200.0, 100.0))); + let mut found = None; + let mut out = ctx.run_ui(input, |ui| found = screen_ppi_at(&screens, ui.ctx())); + out.textures_delta.clear(); + found + }; + assert_eq!(at(pos2(1800.0, 300.0), 1.0), Some(Read(Some(92.0))), "on the 1× display"); + assert_eq!(at(pos2(700.0, 300.0), 2.0), Some(Read(Some(127.0))), "on the 2× display"); + assert_eq!(at(pos2(2000.0, 1100.0), 1.0), Some(Read(Some(92.0))), "partly below the 1× display, its center off it"); + assert_eq!(at(pos2(9000.0, 300.0), 1.0), None, "off every display"); +} + +/// #9051: with Display Print Size at 100% Zoom on, a document floating in an OS window of its own +/// counts 100% from the display that shows that window. A move of its window to a display of +/// another density keeps its zoom percentage; a move of the main window leaves its zoom alone and +/// keeps the percentage of the documents under the tabs. +#[test] +fn a_floating_window_counts_100_percent_from_its_own_display() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + app.set_screen_ppi(Some(127.0)); + app.run("view.actualSize", json!({})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + let pct = |app: &VectorcraftApp, i: usize| crate::state::zoom_display_percent(app.views[i].zoom, app.print_ppi_of(Some((i, 1)))); + let uid = app.session.documents()[1].uid; + set_window_ppi(&mut app, (uid, 1), Some(91.0)); + app.settle_screen_ppi(); + assert!((pct(&app, 1) - 100.0).abs() < 1e-9, "the floating document stays at 100%: {}", pct(&app, 1)); + assert!((app.views[1].zoom * 72.0 - 91.0).abs() < 1e-9, "an inch of the document fills an inch of its display"); + let (floating, tabbed, tabbed_pct) = (app.views[1].zoom, app.views[0].zoom, pct(&app, 0)); + assert!(app.set_screen_ppi(Some(150.0)), "the main window moved to a denser display"); + assert_eq!(app.views[1].zoom, floating, "the floating window did not move"); + assert!(app.views[0].zoom > tabbed, "the tabbed document zooms with the denser display"); + assert!((pct(&app, 0) - tabbed_pct).abs() < 1e-9, "and keeps its percentage"); + // Presentation Mode shows the floating document in the main window, on the main window's + // display, and it keeps its 100% there. + app.settle_screen_ppi_if_changed(); + app.ui.screen_mode = 3; + app.settle_screen_ppi_if_changed(); + assert!((app.views[1].zoom * 72.0 - 150.0).abs() < 1e-9, "presented on the main window's display: {}", app.views[1].zoom * 72.0); + assert!((pct(&app, 1) - 100.0).abs() < 1e-9); + // Back from its own display under the tabs, a fit made there is kept. + app.ui.screen_mode = 0; + app.settle_screen_ppi_if_changed(); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + app.run("view.fitArtboard", json!({})).unwrap(); + let fitted = app.views[1].zoom; + app.settle_screen_ppi_if_changed(); + assert_eq!(app.views[1].zoom, fitted, "the fit is made for the main window's display"); +} diff --git a/crates/ui-egui/src/doc_windows/views.rs b/crates/ui-egui/src/doc_windows/views.rs index 885e91fbee..dda76952ee 100644 --- a/crates/ui-egui/src/doc_windows/views.rs +++ b/crates/ui-egui/src/doc_windows/views.rs @@ -36,15 +36,6 @@ pub struct Views { shown: HashMap, } -impl Views { - /// Multiplies the zoom of every view kept here by `k`, within the zoom range. - pub(crate) fn scale_zooms(&mut self, k: f64) { - for o in &mut self.others { - o.view.zoom = (o.view.zoom * k).clamp(0.0313, 640.0); - } - } -} - fn uid(app: &VectorcraftApp, i: usize) -> Option { app.session.documents().get(i).map(|d| d.uid) } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..a547a5de48 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3209,7 +3209,7 @@ digits Malayalam Малаялам Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. „Селекция › Същото › Цвят на запълване“, „Цвят на щриха“ и „Запълване и щрих“ намират само същия нюанс на глобална или плътна мостра, а не всеки неин нюанс. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Показва началния екран, когато няма отворен документ; ако е изключено, прозорецът остава празен, докато не щракнете „Начало“. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Измерва обектите заедно с щрихите и ефектите, които променят формата, за размер, позиция и подравняване; сенките, сиянията и замъгляванията не се измерват. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. При мащаб 100 % един инч от документа заема 96 екранни точки вместо 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. При мащаб 100 % един инч от документа запълва един инч от дисплея или 96 екранни точки, когато системата не съобщава размера на дисплея. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Двойно щракване върху група, контур или изображение с инструмента „Селекция“ ги отваря в режим на изолация. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Запълванията и щрихите с мостра се трансформират заедно с графиката, освен ако трансформацията или менюто на панела „Трансформиране“ не избере друго. Live corner radii scale with the art, unless the scale chooses otherwise. Радиусите на динамичните ъгли се мащабират заедно с графиката, освен ако мащабирането не избере друго. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..9204190552 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4696,7 +4696,7 @@ font-technology Variable Varijabilni Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Odabir › Isto › Boja ispune, Boja poteza i Ispuna i potez pronalaze samo istu nijansu globalnog ili spot uzorka, a ne bilo koju njegovu nijansu. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Prikazuje početni ekran kada nijedan dokument nije otvoren; kada je isključeno, prozor ostaje prazan dok ne kliknete Početna. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mjeri objekte zajedno s potezima i efektima koji mijenjaju oblik za veličinu, položaj i poravnanje; sjene, sjaj i zamućenja se ne mjere. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Pri zumu od 100% jedan inč dokumenta zauzima 96 tačaka ekrana umjesto 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Pri zumu od 100% jedan inč dokumenta ispunjava jedan inč ekrana, ili 96 tačaka ekrana kada sistem ne javlja veličinu ekrana. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dvostruki klik na grupu, putanju ili sliku alatom Odabir otvara ih u načinu izolacije. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Ispune i potezi s uzorkom transformišu se zajedno s grafikom, osim ako transformacija ili meni panela Transformiši ne odabere drugačije. Live corner radii scale with the art, unless the scale chooses otherwise. Poluprečnici dinamičnih uglova skaliraju se zajedno s grafikom, osim ako skaliranje ne odabere drugačije. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..d9fe0a739a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4067,7 +4067,7 @@ digits Malayalam Malaiàlam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selecció › Igual › Color de farciment, Color del traç i Farciment i traç només coincideixen amb el mateix matís d’una mostra global o de tinta plana, no amb qualsevol matís seu. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Mostra la pantalla d’inici quan no hi ha cap document obert; desactivada, la finestra queda buida fins que feu clic a Inici. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mesura els objectes amb els traços i els efectes que en canvien la forma per a la mida, la posició i l’alineació; les ombres, les lluïsors i els desenfocaments no es mesuren. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Amb un zoom del 100 %, una polzada del document ocupa 96 punts de pantalla en lloc de 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Amb un zoom del 100 %, una polzada del document omple una polzada de la pantalla, o 96 punts de pantalla quan el sistema no n’indica la mida. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Fer doble clic en un grup, traçat o imatge amb l’eina Selecció l’obre en mode d’aïllament. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Els farciments i traços de motiu es transformen amb la il·lustració, tret que una transformació o el menú del panell Transforma triï una altra cosa. Live corner radii scale with the art, unless the scale chooses otherwise. Els radis de cantonada dinàmics s’escalen amb la il·lustració, tret que l’escalat triï una altra cosa. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..bb1e2f34ab 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4805,7 +4805,7 @@ font-technology Variable Variabilní Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Výběr › Stejné › Barva výplně, Barva tahu a Výplň a tah najdou jen stejný odstín globálního nebo přímého vzorku, ne libovolný jeho odstín. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Zobrazí domovskou obrazovku, když není otevřený žádný dokument; když je vypnuto, okno zůstane prázdné, dokud neklepnete na Domů. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Měří objekty včetně tahů a efektů měnících tvar pro velikost, polohu a zarovnání; stíny, záře a rozostření se neměří. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Při zvětšení 100 % zabere jeden palec dokumentu 96 obrazovkových bodů místo 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Při zvětšení 100 % vyplní jeden palec dokumentu jeden palec displeje, nebo 96 obrazovkových bodů, pokud systém velikost displeje neudává. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Poklepání na skupinu, cestu nebo obraz nástrojem Výběr je otevře v izolačním režimu. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Výplně a tahy se vzorkem se transformují s kresbou, pokud transformace nebo nabídka panelu Transformace nezvolí jinak. Live corner radii scale with the art, unless the scale chooses otherwise. Poloměry živých rohů se mění s velikostí kresby, pokud změna velikosti nezvolí jinak. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..d3978bfddf 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7253,7 +7253,7 @@ font-technology Variable Variable Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Markér › Samme › Fyldfarve, Stregfarve og Fyld og streg finder kun samme nuance af en global farveprøve eller staffagefarve, ikke en hvilken som helst nuance af den. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Viser startskærmen, når intet dokument er åbent; når den er slået fra, forbliver vinduet tomt, indtil du klikker på Home. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Måler objekter med deres streger og formændrende effekter til størrelse, position og justering; skygger, glød og sløringer måles ikke. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Ved 100 % zoom fylder en tomme af dokumentet 96 skærmpunkter i stedet for 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Ved 100 % zoom fylder en tomme af dokumentet en tomme af skærmen, eller 96 skærmpunkter, hvis systemet ikke oplyser skærmens størrelse. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dobbeltklik på en gruppe, en sti eller et billede med værktøjet Markering åbner det i isolationstilstand. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Mønsterfyld og -streger transformeres med grafikken, medmindre en transformation eller menuen i panelet Transformér vælger andet. Live corner radii scale with the art, unless the scale chooses otherwise. Live-hjørneradier skaleres med grafikken, medmindre skaleringen vælger andet. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..2663967128 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3279,7 +3279,7 @@ digits Malayalam Malayalam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. „Auswahl › Gleich › Flächenfarbe“, „Konturfarbe“ und „Fläche und Kontur“ finden nur denselben Farbton eines globalen oder Volltonfarbfelds, nicht jeden Farbton davon. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Zeigt den Startbildschirm, wenn kein Dokument geöffnet ist; ist die Option aus, bleibt das Fenster leer, bis Sie auf „Start“ klicken. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Misst Objekte für Größe, Position und Ausrichtung mit ihren Konturen und formverändernden Effekten; Schatten, Schein und Weichzeichnungen werden nicht gemessen. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Bei 100 % Zoom nimmt ein Zoll des Dokuments 96 statt 72 Bildschirmpunkte ein. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Bei 100 % Zoom füllt ein Zoll des Dokuments einen Zoll des Bildschirms, oder 96 Bildschirmpunkte, wenn das System keine Bildschirmgröße meldet. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Ein Doppelklick mit dem Auswahl-Werkzeug auf eine Gruppe, einen Pfad oder ein Bild öffnet sie im Isolationsmodus. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Musterflächen und -konturen werden mit dem Bildmaterial transformiert, sofern die Transformation oder das Menü des Bedienfelds „Transformieren“ nichts anderes wählt. Live corner radii scale with the art, unless the scale chooses otherwise. Live-Eckenradien skalieren mit dem Bildmaterial, sofern die Skalierung nichts anderes wählt. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..579174fce7 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4132,7 +4132,7 @@ digits Malayalam Μαλαγιάλαμ Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Τα Επιλογή › Ίδιο › Χρώμα γεμίσματος, Χρώμα περιγράμματος και Γέμισμα και περίγραμμα βρίσκουν μόνο την ίδια απόχρωση ενός καθολικού ή σημειακού δείγματος, όχι οποιαδήποτε απόχρωσή του. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Εμφανίζει την αρχική οθόνη όταν δεν είναι ανοιχτό κανένα έγγραφο· όταν είναι ανενεργό, το παράθυρο μένει κενό μέχρι να κάνετε κλικ στην Αρχική οθόνη. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Μετρά τα αντικείμενα μαζί με τα περιγράμματα και τα εφέ που αλλάζουν το σχήμα τους για μέγεθος, θέση και στοίχιση· οι σκιές, οι λάμψεις και οι θολώσεις δεν μετρώνται. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Σε ζουμ 100%, μία ίντσα του εγγράφου καταλαμβάνει 96 στιγμές οθόνης αντί για 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Σε ζουμ 100%, μία ίντσα του εγγράφου γεμίζει μία ίντσα της οθόνης, ή 96 στιγμές οθόνης όταν το σύστημα δεν αναφέρει το μέγεθος της οθόνης. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Το διπλό κλικ σε ομάδα, διαδρομή ή εικόνα με το εργαλείο Επιλογή την ανοίγει σε λειτουργία απομόνωσης. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Τα γεμίσματα και τα περιγράμματα μοτίβου μετασχηματίζονται μαζί με το γραφικό, εκτός αν ένας μετασχηματισμός ή το μενού του πλαισίου Μετασχηματισμός επιλέξει κάτι άλλο. Live corner radii scale with the art, unless the scale chooses otherwise. Οι ακτίνες των δυναμικών γωνιών κλιμακώνονται μαζί με το γραφικό, εκτός αν η κλιμάκωση επιλέξει κάτι άλλο. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..08b4fc2693 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3315,7 +3315,7 @@ digits Malayalam Malayálam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selección › Igual › Color de relleno, Color de trazo y Relleno y trazo solo coinciden con el mismo matiz de una muestra global o de tinta plana, no con cualquier matiz de ella. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Muestra la pantalla de inicio cuando no hay ningún documento abierto; desactivada, la ventana queda vacía hasta que hace clic en Inicio. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mide los objetos con sus trazos y los efectos que cambian su forma para el tamaño, la posición y la alineación; las sombras, los resplandores y los desenfoques no se miden. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Con un zoom del 100 %, una pulgada del documento ocupa 96 puntos de pantalla en lugar de 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Con un zoom del 100 %, una pulgada del documento ocupa una pulgada de la pantalla, o 96 puntos de pantalla si el sistema no indica su tamaño. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Al hacer doble clic en un grupo, trazado o imagen con la herramienta Selección, se abre en modo de aislamiento. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Los rellenos y trazos de motivo se transforman con la ilustración, salvo que una transformación o el menú del panel Transformar indique otra cosa. Live corner radii scale with the art, unless the scale chooses otherwise. Los radios de esquina dinámicos se escalan con la ilustración, salvo que el escalado indique otra cosa. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..c712366c71 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4715,7 +4715,7 @@ font-technology Variable Muuttuvat Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Valinta › Sama › Täyttöväri, Viivan väri sekä Täyttö ja viiva löytävät vain globaalin tai spottivärimallin saman sävyn, eivät mitä tahansa sen sävyä. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Näyttää aloitusnäytön, kun yhtään asiakirjaa ei ole auki; kun asetus ei ole käytössä, ikkuna pysyy tyhjänä, kunnes napsautat Aloitus. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mittaa objektit viivoineen ja muotoa muuttavine tehosteineen kokoa, sijaintia ja tasausta varten; varjoja, hehkuja ja sumennuksia ei mitata. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100 %:n zoomauksella asiakirjan tuuma vie 96 näyttöpistettä 72:n sijaan. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100 %:n zoomauksella asiakirjan tuuma täyttää näytön tuuman, tai 96 näyttöpistettä, jos järjestelmä ei ilmoita näytön kokoa. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Ryhmän, polun tai kuvan kaksoisnapsautus Valinta-työkalulla avaa sen eristystilaan. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Kuviotäytöt ja -viivat muuntuvat grafiikan mukana, ellei muunnos tai Muunna-paneelin valikko valitse toisin. Live corner radii scale with the art, unless the scale chooses otherwise. Dynaamisten kulmien säteet skaalautuvat grafiikan mukana, ellei skaalaus valitse toisin. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..384add6e6f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3303,7 +3303,7 @@ digits Malayalam Malayalam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Sélection › Identique › Couleur de fond, Couleur du contour et Fond et contour ne retiennent que la même teinte d’une nuance globale ou d’une couleur d’accompagnement, et non toutes ses teintes. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Affiche l’écran d’accueil quand aucun document n’est ouvert. Désactivée, la fenêtre reste vide jusqu’à ce que vous cliquiez sur Accueil. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mesure les objets avec leurs contours et leurs effets qui modifient la forme pour la taille, la position et l’alignement. Les ombres, lueurs et flous ne sont pas mesurés. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. À 100 % de zoom, un pouce du document occupe 96 points d’écran au lieu de 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. À 100 % de zoom, un pouce du document occupe un pouce de l’écran, ou 96 points d’écran si le système n’indique pas la taille de l’écran. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Un double-clic sur un groupe, un tracé ou une image avec l’outil Sélection l’ouvre en mode Isolation. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Les fonds et contours de motif se transforment avec l’illustration, sauf si une transformation ou le menu du panneau Transformation en décide autrement. Live corner radii scale with the art, unless the scale chooses otherwise. Les rayons d’angle dynamiques se mettent à l’échelle avec l’illustration, sauf si la mise à l’échelle en décide autrement. diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..c9b4e617f7 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3370,7 +3370,7 @@ arrowhead Feather પીંછું Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. પસંદ કરો › સમાન › ભરવાનો રંગ, સ્ટ્રોક રંગ અને ભરો અને સ્ટ્રોક ફક્ત ગ્લોબલ કે સ્પોટ સ્વૉચના એ જ ટિન્ટ સાથે મેળ ખાય છે, તેના કોઈપણ ટિન્ટ સાથે નહીં. Shows the Home screen when no document is open; off, the window stays empty until you click Home. કોઈ દસ્તાવેજ ખુલ્લો ન હોય ત્યારે હોમ સ્ક્રીન બતાવે છે; બંધ હોય ત્યારે તમે હોમ પર ક્લિક ન કરો ત્યાં સુધી વિન્ડો ખાલી રહે છે. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. કદ, સ્થાન અને ગોઠવણી માટે ઑબ્જેક્ટને તેમના સ્ટ્રોક અને આકાર બદલતી ઇફેક્ટ્સ સાથે માપે છે; છાયા, ગ્લો અને બ્લર માપવામાં આવતા નથી. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100% ઝૂમ પર દસ્તાવેજનો એક ઇંચ 72 ને બદલે 96 સ્ક્રીન પોઇન્ટ લે છે. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100% ઝૂમ પર દસ્તાવેજનો એક ઇંચ ડિસ્પ્લેનો એક ઇંચ ભરે છે, અથવા સિસ્ટમ ડિસ્પ્લેનું કદ ન જણાવે ત્યારે 96 સ્ક્રીન પોઇન્ટ લે છે. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. પસંદગી ટૂલથી ગ્રુપ, પાથ કે છબી પર ડબલ-ક્લિક કરવાથી તે આઇસોલેશન મોડમાં ખુલે છે. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. પૅટર્ન ભરણ અને સ્ટ્રોક આર્ટવર્ક સાથે ટ્રાન્સફોર્મ થાય છે, સિવાય કે કોઈ ટ્રાન્સફોર્મ કે ટ્રાન્સફોર્મ પેનલનું મેનૂ બીજું પસંદ કરે. Live corner radii scale with the art, unless the scale chooses otherwise. લાઇવ ખૂણાઓની ત્રિજ્યાઓ આર્ટવર્ક સાથે સ્કેલ થાય છે, સિવાય કે સ્કેલિંગ બીજું પસંદ કરે. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..4f875c707c 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4698,7 +4698,7 @@ arrowhead Feather पंख Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. सिलेक्ट › समान › फ़िल रंग, स्ट्रोक रंग और फ़िल व स्ट्रोक केवल ग्लोबल या स्पॉट स्वॉच के उसी टिंट से मेल खाते हैं, उसके किसी भी टिंट से नहीं। Shows the Home screen when no document is open; off, the window stays empty until you click Home. कोई डॉक्यूमेंट खुला न होने पर होम स्क्रीन दिखाता है; बंद होने पर विंडो तब तक खाली रहती है जब तक आप होम पर क्लिक नहीं करते। Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. साइज़, स्थिति और संरेखण के लिए ऑब्जेक्ट को उनके स्ट्रोक और आकार बदलने वाले इफ़ेक्ट के साथ मापता है; छाया, ग्लो और ब्लर नहीं मापे जाते। - At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100% ज़ूम पर डॉक्यूमेंट का एक इंच 72 की जगह 96 स्क्रीन पॉइंट लेता है। + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100% ज़ूम पर डॉक्यूमेंट का एक इंच डिस्प्ले का एक इंच घेरता है, या सिस्टम डिस्प्ले का आकार न बताए तो 96 स्क्रीन पॉइंट लेता है। Double-clicking a group, path or image with the Selection tool opens it in isolation mode. सिलेक्शन टूल से किसी ग्रुप, पाथ या इमेज पर डबल-क्लिक करने से वह आइसोलेशन मोड में खुलता है। Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. पैटर्न वाले फ़िल और स्ट्रोक आर्टवर्क के साथ रूपांतरित होते हैं, जब तक कोई रूपांतरण या रूपांतरण पैनल का मेनू कुछ और न चुने। Live corner radii scale with the art, unless the scale chooses otherwise. लाइव कोनों की त्रिज्याएँ आर्टवर्क के साथ स्केल होती हैं, जब तक स्केलिंग कुछ और न चुने। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..d14fb0bced 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3903,7 +3903,7 @@ mark-style Japanese Japán Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. A Kijelölés › Azonos › Kitöltőszín, Körvonalszín és Kitöltés és körvonal csak egy globális vagy direkt színminta azonos árnyalatát találja meg, nem bármely árnyalatát. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Megjeleníti a kezdőképernyőt, ha nincs megnyitott dokumentum; kikapcsolva az ablak üres marad, amíg a Kezdőképernyő gombra nem kattint. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Az objektumokat körvonalaikkal és alakmódosító effektusaikkal együtt méri a mérethez, a pozícióhoz és az igazításhoz; az árnyékokat, ragyogásokat és elmosásokat nem méri. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100%-os nagyításnál a dokumentum egy hüvelyke 72 helyett 96 képernyőpontot foglal el. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100%-os nagyításnál a dokumentum egy hüvelyke a kijelző egy hüvelykét tölti ki, vagy 96 képernyőpontot, ha a rendszer nem adja meg a kijelző méretét. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Ha a Kijelölés eszközzel duplán kattint egy csoportra, útvonalra vagy képre, az elkülönítő módban nyílik meg. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. A mintázatos kitöltések és körvonalak a grafikával együtt alakulnak át, hacsak egy átalakítás vagy az Átalakítás panel menüje mást nem választ. Live corner radii scale with the art, unless the scale chooses otherwise. Az élő sarkok sugara a grafikával együtt méreteződik, hacsak a méretezés mást nem választ. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..ec6c655037 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5119,7 +5119,7 @@ font-technology Variable Variabel Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Seleksi › Sama › Warna isian, Warna stroke, dan Isian & stroke hanya mencocokkan tint yang sama dari swatch global atau spot, bukan sembarang tint-nya. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Menampilkan layar Home saat tidak ada dokumen yang terbuka; saat nonaktif, jendela tetap kosong sampai Anda mengklik Home. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mengukur objek beserta stroke dan efek yang mengubah bentuknya untuk ukuran, posisi, dan perataan; bayangan, cahaya, dan kekaburan tidak diukur. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Pada zum 100%, satu inci dokumen memakai 96 titik layar, bukan 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Pada zum 100%, satu inci dokumen mengisi satu inci layar, atau 96 titik layar bila sistem tidak melaporkan ukuran layar. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Mengklik ganda grup, jalur, atau gambar dengan alat Seleksi membukanya dalam mode isolasi. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Isian dan stroke pola ikut bertransformasi dengan karya seni, kecuali transformasi atau menu panel Transformasi memilih lain. Live corner radii scale with the art, unless the scale chooses otherwise. Radius sudut dinamis ikut diskalakan dengan karya seni, kecuali penskalaan memilih lain. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..451efa2381 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3364,7 +3364,7 @@ digits Malayalam Malayalam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selezione › Uguale › Colore riempimento, Colore traccia e Riempimento e traccia trovano solo la stessa tinta di un campione globale o di un colore spot, non qualsiasi sua tinta. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Mostra la schermata Home quando nessun documento è aperto; se disattivata, la finestra resta vuota finché non fai clic su Home. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Misura gli oggetti con le tracce e gli effetti che ne cambiano la forma per dimensioni, posizione e allineamento; ombre, bagliori e sfocature non vengono misurati. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Allo zoom del 100%, un pollice del documento occupa 96 punti dello schermo invece di 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Allo zoom del 100%, un pollice del documento occupa un pollice dello schermo, o 96 punti dello schermo se il sistema non ne indica le dimensioni. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Un doppio clic su un gruppo, un tracciato o un'immagine con lo strumento Selezione lo apre in modalità isolamento. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. I riempimenti e le tracce con motivo si trasformano con la grafica, a meno che una trasformazione o il menu del pannello Trasforma scelga diversamente. Live corner radii scale with the art, unless the scale chooses otherwise. I raggi degli angoli dinamici si ridimensionano con la grafica, a meno che il ridimensionamento scelga diversamente. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..e1e9cf8bc4 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3332,7 +3332,7 @@ mark-style Japanese 日本式 Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 選択 › 共通 › カラー (塗り)、カラー (線)、塗りと線は、グローバルスウォッチまたは特色スウォッチの同じ濃度だけを選び、ほかの濃度は選びません。 Shows the Home screen when no document is open; off, the window stays empty until you click Home. ドキュメントが開いていないときにホーム画面を表示します。オフのときは、ホームをクリックするまでウィンドウは空のままです。 Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. サイズ、位置、整列のために、線と形を変える効果を含めてオブジェクトを測ります。ドロップシャドウ、光彩、ぼかしは含めません。 - At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100% 表示のとき、ドキュメントの 1 インチを 72 ではなく 96 スクリーンポイントで表示します。 + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100% 表示のとき、ドキュメントの 1 インチをディスプレイの 1 インチで表示します。システムがディスプレイのサイズを報告しない場合は 96 スクリーンポイントで表示します。 Double-clicking a group, path or image with the Selection tool opens it in isolation mode. 選択ツールでグループ、パス、画像をダブルクリックすると、編集モードで開きます。 Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. 変形コマンドや変形パネルのメニューで別の指定をしない限り、パターンの塗りと線をアートワークと一緒に変形します。 Live corner radii scale with the art, unless the scale chooses otherwise. 拡大・縮小で別の指定をしない限り、ライブコーナーの半径をアートワークと一緒に拡大・縮小します。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..513b6ff533 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6506,7 +6506,7 @@ font-technology Variable ცვლადი Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. მონიშვნა › იგივე › შევსების ფერი, კონტურის ფერი და შევსება და კონტური პოულობს გლობალური ან სპოტ-ფერის ნიმუშის მხოლოდ იმავე ტონირებას და არა მის ნებისმიერ ტონირებას. Shows the Home screen when no document is open; off, the window stays empty until you click Home. აჩვენებს საწყის ეკრანს, როცა არცერთი დოკუმენტი არ არის გახსნილი; გამორთვისას ფანჯარა ცარიელი რჩება, „საწყის ეკრანზე“ დაწკაპუნებამდე. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. ზომის, პოზიციისა და სწორების დროს ობიექტებს ზომავს კონტურებითა და ფორმის შემცვლელი ეფექტებით; ჩრდილები, ნათება და გაბუნდოვნება არ იზომება. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100%-იან მასშტაბზე დოკუმენტის ერთი დუიმი 72-ის ნაცვლად 96 ეკრანის პუნქტს იკავებს. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100%-იან მასშტაბზე დოკუმენტის ერთი დუიმი ეკრანის ერთ დუიმს ავსებს, ან 96 ეკრანის პუნქტს, როცა სისტემა ეკრანის ზომას არ აცნობებს. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. მონიშვნის ხელსაწყოთი ჯგუფზე, ტრაექტორიაზე ან გამოსახულებაზე ორჯერ დაწკაპუნება მას იზოლაციის რეჟიმში ხსნის. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. პატერნის შევსებები და კონტურები ნახატთან ერთად გარდაიქმნება, თუ გარდაქმნა ან გარდაქმნის პანელის მენიუ სხვას არ აირჩევს. Live corner radii scale with the art, unless the scale chooses otherwise. ცოცხალი კუთხეების რადიუსები ნახატთან ერთად მასშტაბირდება, თუ მასშტაბირება სხვას არ აირჩევს. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..84e309e056 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3321,7 +3321,7 @@ mark-style Japanese 일본식 Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 선택 › 동일 › 칠 색상, 선 색상, 칠 및 선은 전역 또는 별색 견본의 같은 색조만 찾고, 다른 색조는 찾지 않습니다. Shows the Home screen when no document is open; off, the window stays empty until you click Home. 열린 문서가 없을 때 홈 화면을 표시합니다. 끄면 홈을 클릭할 때까지 창이 비어 있습니다. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. 크기, 위치, 정렬을 위해 선과 모양을 바꾸는 효과를 포함하여 개체를 측정합니다. 그림자, 광선, 흐림 효과는 측정하지 않습니다. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. 100% 확대/축소에서 문서의 1인치가 72가 아닌 96 화면 포인트를 차지합니다. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100% 확대/축소에서 문서의 1인치가 디스플레이의 1인치를 채우며, 시스템이 디스플레이 크기를 알려 주지 않으면 96 화면 포인트를 차지합니다. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. 선택 도구로 그룹, 패스 또는 이미지를 두 번 클릭하면 격리 모드로 엽니다. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. 변형 명령이나 변형 패널의 메뉴에서 달리 선택하지 않는 한, 패턴 칠과 선이 아트웍과 함께 변형됩니다. Live corner radii scale with the art, unless the scale chooses otherwise. 크기 조정에서 달리 선택하지 않는 한, 라이브 모퉁이 반지름이 아트웍과 함께 크기 조정됩니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..4dbafaa5a5 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5119,7 +5119,7 @@ font-technology Variable Variabel Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selecteren › Zelfde › Vulkleur, Contourkleur en Vulling en contour vinden alleen dezelfde tint van een globaal of steunkleurstaal, niet elke tint ervan. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Toont het startscherm wanneer er geen document open is; uitgeschakeld blijft het venster leeg totdat u op Home klikt. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Meet objecten met hun contouren en vormveranderende effecten voor grootte, positie en uitlijning; schaduwen, gloed en vervagingen worden niet gemeten. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Bij 100% zoom neemt één inch van het document 96 schermpunten in beslag in plaats van 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Bij 100% zoom vult één inch van het document één inch van het scherm, of 96 schermpunten als het systeem geen schermgrootte doorgeeft. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dubbelklikken op een groep, pad of afbeelding met het gereedschap Selectie opent die in de isolatiemodus. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Patroonvullingen en -contouren transformeren mee met de illustratie, tenzij een transformatie of het menu van het deelvenster Transformeren anders kiest. Live corner radii scale with the art, unless the scale chooses otherwise. Dynamische hoekradii schalen mee met de illustratie, tenzij het schalen anders kiest. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..46d2cc120b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4648,7 +4648,7 @@ font-technology Variable Zmienne Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Zaznacz › Taki sam › Kolor wypełnienia, Kolor obrysu oraz Wypełnienie i obrys dopasowują tylko ten sam odcień globalnej lub dodatkowej próbki, a nie dowolny jej odcień. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Pokazuje stronę startową, gdy nie jest otwarty żaden dokument; po wyłączeniu okno pozostaje puste, dopóki nie klikniesz Strona startowa. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mierzy obiekty razem z obrysami i efektami zmieniającymi kształt na potrzeby rozmiaru, położenia i wyrównania; cienie, poświaty i rozmycia nie są mierzone. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Przy powiększeniu 100% jeden cal dokumentu zajmuje 96 punktów ekranu zamiast 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Przy powiększeniu 100% jeden cal dokumentu wypełnia jeden cal ekranu albo 96 punktów ekranu, gdy system nie podaje rozmiaru ekranu. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dwukrotne kliknięcie grupy, ścieżki lub obrazu narzędziem Zaznaczanie otwiera je w trybie izolacji. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Wypełnienia i obrysy wzorkiem przekształcają się razem z kompozycją, chyba że przekształcenie lub menu panelu Przekształć wybierze inaczej. Live corner radii scale with the art, unless the scale chooses otherwise. Promienie narożników dynamicznych skalują się razem z kompozycją, chyba że skalowanie wybierze inaczej. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..7e03fc77f0 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2770,7 +2770,7 @@ digits Malayalam Malaiala Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Seleção › Igual › Cor de Preenchimento, Cor do Traçado e Preenchimento e Traçado encontram apenas o mesmo tom de uma amostra global ou de cor especial, não qualquer tom dela. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Mostra a tela Início quando nenhum documento está aberto; desativada, a janela fica vazia até você clicar em Início. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mede os objetos com seus traçados e efeitos que mudam a forma para tamanho, posição e alinhamento; sombras, brilhos e desfoques não são medidos. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Com zoom de 100%, uma polegada do documento ocupa 96 pontos de tela em vez de 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Com zoom de 100%, uma polegada do documento ocupa uma polegada da tela, ou 96 pontos de tela quando o sistema não informa o tamanho da tela. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Clicar duas vezes em um grupo, demarcador ou imagem com a ferramenta Seleção o abre no modo de isolamento. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Preenchimentos e traçados de padrão se transformam com a arte, a menos que uma transformação ou o menu do painel Transformar escolha outra coisa. Live corner radii scale with the art, unless the scale chooses otherwise. Os raios de canto dinâmicos mudam de escala com a arte, a menos que a escala escolha outra coisa. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..731d09bd06 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3346,7 +3346,7 @@ digits Malayalam Малаялам Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. «Выделение › То же › Цвет заливки», «Цвет обводки» и «Заливка и обводка» находят только тот же оттенок глобального или плашечного образца, а не любой его оттенок. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Показывает начальный экран, когда нет открытых документов; если выключено, окно остаётся пустым, пока вы не нажмёте «Домой». Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Измеряет объекты с обводками и эффектами, меняющими форму, для размера, положения и выравнивания; тени, свечения и размытия не учитываются. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. При масштабе 100 % один дюйм документа занимает 96 экранных пунктов вместо 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. При масштабе 100 % один дюйм документа занимает один дюйм дисплея или 96 экранных пунктов, если система не сообщает размер дисплея. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Двойной щелчок по группе, контуру или изображению инструментом «Выделение» открывает их в режиме изоляции. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Заливки и обводки узором трансформируются вместе с графикой, если трансформирование или меню панели «Трансформировать» не задаёт иное. Live corner radii scale with the art, unless the scale chooses otherwise. Радиусы динамических углов масштабируются вместе с графикой, если масштабирование не задаёт иное. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..597a5dbc1e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3235,7 +3235,7 @@ digits Malayalam Malayalam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Markera › Samma › Fyllnadsfärg, Konturfärg och Fyllning och kontur hittar bara samma nyans av ett globalt färgprov eller en dekorfärg, inte vilken nyans som helst av det. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Visar startskärmen när inget dokument är öppet; när det är av förblir fönstret tomt tills du klickar på Start. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mäter objekt med deras konturer och formändrande effekter för storlek, position och justering; skuggor, glöd och oskärpa mäts inte. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Vid 100 % zoom tar en tum av dokumentet upp 96 skärmpunkter i stället för 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Vid 100 % zoom fyller en tum av dokumentet en tum av skärmen, eller 96 skärmpunkter om systemet inte anger skärmens storlek. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dubbelklick på en grupp, en bana eller en bild med verktyget Markering öppnar den i isoleringsläge. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Mönsterfyllningar och -konturer transformeras med grafiken, om inte en transformering eller menyn i panelen Transformera väljer annat. Live corner radii scale with the art, unless the scale chooses otherwise. Dynamiska hörnradier skalas med grafiken, om inte skalningen väljer annat. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..b4b8af414f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3080,7 +3080,7 @@ digits Malayalam Malayalam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Seçim › Aynı › Dolgu Rengi, Kontur Rengi ve Doldur ve Konturla yalnızca genel veya spot renk örneğinin aynı tonunu bulur, herhangi bir tonunu değil. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Hiçbir belge açık değilken Ana Sayfa ekranını gösterir; kapalıyken siz Ana Sayfa'ya tıklayana kadar pencere boş kalır. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Nesneleri boyut, konum ve hizalama için konturları ve şekil değiştiren efektleriyle birlikte ölçer; gölgeler, parlamalar ve bulanıklaştırmalar ölçülmez. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. %100 yakınlaştırmada belgenin bir inçi 72 yerine 96 ekran noktası kaplar. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. %100 yakınlaştırmada belgenin bir inçi ekranın bir inçini kaplar; sistem ekran boyutunu bildirmezse 96 ekran noktası kaplar. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Seçim aracıyla bir gruba, yola veya görüntüye çift tıklamak onu yalıtım modunda açar. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Desen dolguları ve konturları, bir dönüşüm veya Dönüştür panelinin menüsü başka bir seçim yapmadıkça resimle birlikte dönüşür. Live corner radii scale with the art, unless the scale chooses otherwise. Canlı köşe yarıçapları, ölçekleme başka bir seçim yapmadıkça resimle birlikte ölçeklenir. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..1be9d21a56 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3356,7 +3356,7 @@ digits Malayalam Малаялам Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. «Виділення › Те саме › Колір заливки», «Колір обведення» та «Заливка та обведення» знаходять лише той самий відтінок глобального або плашкового зразка, а не будь-який його відтінок. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Показує початковий екран, коли немає відкритих документів; якщо вимкнено, вікно лишається порожнім, доки ви не натиснете «Додому». Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Вимірює об’єкти з обведеннями та ефектами, що змінюють форму, для розміру, положення й вирівнювання; тіні, світіння та розмиття не враховуються. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. За масштабу 100 % один дюйм документа займає 96 екранних пунктів замість 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. За масштабу 100 % один дюйм документа займає один дюйм дисплея або 96 екранних пунктів, якщо система не повідомляє розмір дисплея. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Подвійне клацання на групі, контурі або зображенні інструментом «Виділення» відкриває їх у режимі ізоляції. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Заливки й обведення візерунком трансформуються разом із графікою, якщо трансформування або меню панелі «Трансформувати» не задає іншого. Live corner radii scale with the art, unless the scale chooses otherwise. Радіуси динамічних кутів масштабуються разом із графікою, якщо масштабування не задає іншого. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..5bc97afbae 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3676,7 +3676,7 @@ mark-style Japanese Kiểu Nhật Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Vùng chọn › Giống nhau › Màu tô, Màu nét và Tô & Nét chỉ khớp với cùng sắc độ của một mẫu màu toàn cục hoặc màu pha, không phải mọi sắc độ của nó. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Hiển thị màn hình Trang chủ khi không có tài liệu nào mở; khi tắt, cửa sổ để trống cho đến khi bạn nhấp vào Trang chủ. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Đo đối tượng cùng với nét và các hiệu ứng thay đổi hình dạng cho kích thước, vị trí và căn chỉnh; bóng đổ, ánh sáng và làm mờ không được đo. - At 100% zoom, one inch of the document takes 96 screen points instead of 72. Ở mức thu phóng 100%, một inch của tài liệu chiếm 96 điểm màn hình thay vì 72. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Ở mức thu phóng 100%, một inch của tài liệu chiếm một inch trên màn hình, hoặc 96 điểm màn hình khi hệ thống không báo kích thước màn hình. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Nhấp đúp vào một nhóm, đường dẫn hoặc hình ảnh bằng công cụ Vùng chọn sẽ mở nó trong chế độ cô lập. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Phần tô và nét họa tiết biến đổi cùng hình minh họa, trừ khi phép biến đổi hoặc menu của bảng Biến đổi chọn khác. Live corner radii scale with the art, unless the scale chooses otherwise. Bán kính góc động co giãn cùng hình minh họa, trừ khi phép co giãn chọn khác. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..fd591e2ff4 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3205,7 +3205,7 @@ digits Malayalam 马拉雅拉姆数字 Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 选择 › 相同 › 填色、描边颜色和填色和描边只匹配全局色板或专色色板的相同色调,而不是其任意色调。 Shows the Home screen when no document is open; off, the window stays empty until you click Home. 没有打开文档时显示主页屏幕;关闭时,窗口保持空白,直到你点击主页。 Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. 在尺寸、位置和对齐中按对象的描边和改变形状的效果测量对象;阴影、发光和模糊不计入测量。 - At 100% zoom, one inch of the document takes 96 screen points instead of 72. 缩放为 100% 时,文档的一英寸占 96 个屏幕点,而不是 72 个。 + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 缩放为 100% 时,文档的一英寸占显示器上的一英寸;系统未报告显示器尺寸时占 96 个屏幕点。 Double-clicking a group, path or image with the Selection tool opens it in isolation mode. 用选择工具双击编组、路径或图像时,会在隔离模式中打开它。 Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. 图案填色和描边随图稿一起变换,除非变换命令或变换面板的菜单另有选择。 Live corner radii scale with the art, unless the scale chooses otherwise. 实时转角半径随图稿一起缩放,除非缩放命令另有选择。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..a7136b8c76 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4654,7 +4654,7 @@ digits Malayalam 馬來亞拉姆數字 Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 選取 › 相同 › 填色顏色、筆畫顏色和填色與筆畫只符合全域色票或特別色色票的相同色調,而不是其任意色調。 Shows the Home screen when no document is open; off, the window stays empty until you click Home. 沒有開啟文件時顯示首頁畫面;關閉時,視窗保持空白,直到你按下首頁。 Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. 在尺寸、位置和對齊中依物件的筆畫和改變形狀的效果測量物件;陰影、光暈和模糊不計入測量。 - At 100% zoom, one inch of the document takes 96 screen points instead of 72. 縮放為 100% 時,文件的一英吋佔 96 個螢幕點,而不是 72 個。 + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 縮放為 100% 時,文件的一英吋佔顯示器上的一英吋;系統未回報顯示器尺寸時佔 96 個螢幕點。 Double-clicking a group, path or image with the Selection tool opens it in isolation mode. 用選取工具按兩下群組、路徑或影像時,會在隔離模式中開啟它。 Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. 圖樣填色和筆畫隨圖稿一起變形,除非變形指令或變形面板的選單另有選擇。 Live corner radii scale with the art, unless the scale chooses otherwise. 即時轉角半徑隨圖稿一起縮放,除非縮放指令另有選擇。 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a50527cede..40889e76ae 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -129,7 +129,7 @@ pub use craft_ui::docking::Monitor as DockMonitor; pub(crate) use services::browsable_url; pub use services::{ DownloadFn, ExistsFn, FileFilter, FilePick, Inbox, NativeInputHook, OpenUrlFn, PickOpen, PickSave, PickedInbox, ReadFn, RevealFn, SaveStreamFn, - SaveWriteFn, Services, WriteFn, + SaveWriteFn, ScreenDensity, ScreenPpi, Services, WriteFn, }; use state::{GeometryStamp, InputGeneration, PendingScreenshot, QueuedScreenshot}; pub(crate) use state::{InputFrame, take_frame_once}; diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index c1307871db..89df32b658 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -298,12 +298,19 @@ fn view_box(region: DRect, thumb: Rect, canvas: Rect, v: &crate::state::View, ui pts } -/// Slider position (0..1) ↔ zoom percent on a log range, 3.13 %–64 000 %. -pub fn zoom_to_slider(z: f64) -> f64 { - ((z.clamp(3.13, 64000.0)).ln() - 3.13f64.ln()) / (64000f64.ln() - 3.13f64.ln()) +/// Slider position (0..1) ↔ zoom percent on a log range from `lo` % to `hi` % ([`zoom_range`]). +pub fn zoom_to_slider(z: f64, (lo, hi): (f64, f64)) -> f64 { + ((z.clamp(lo, hi)).ln() - lo.ln()) / (hi.ln() - lo.ln()) } -pub fn slider_to_zoom(t: f64) -> f64 { - (3.13f64.ln() + t.clamp(0.0, 1.0) * (64000f64.ln() - 3.13f64.ln())).exp() +pub fn slider_to_zoom(t: f64, (lo, hi): (f64, f64)) -> f64 { + (lo.ln() + t.clamp(0.0, 1.0) * (hi.ln() - lo.ln())).exp() +} + +/// The zoom range in the percentages the zoom field shows, with 100% at Actual Size: 3.13 %–64 000 % +/// at one document point per screen point. +fn zoom_range(print: Option) -> (f64, f64) { + let baseline = crate::state::zoom_baseline(print); + (3.13 / baseline, 64000.0 / baseline) } pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -346,6 +353,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } // The view box: the canvas's corners in the document, turned with the view, cut to the thumbnail. let view = app.view().copied(); + // The zoom as the zoom field and `view.setZoom` count it, with 100% at Actual Size. + let print = app.print_ppi(); + let zoom = view.map_or(100.0, |v| crate::state::zoom_display_percent(v.zoom, print)); if let (Some(v), Some(cr)) = (view, app.canvas_rect) { let box_points = view_box(region, thumb, cr, &v, app.canvas_ui_zoom); if box_points.len() > 2 { @@ -356,12 +366,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { && let Some(p) = resp.interact_pointer_pos() { let c = thumb_to_doc(region, thumb, p); - app.run("view.setZoom", json!({"zoom": v.zoom * 100.0, "center": [c.x, c.y]})).ok(); + app.run("view.setZoom", json!({"zoom": zoom, "center": [c.x, c.y]})).ok(); } } ui.painter().rect_stroke(thumb, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside); // Zoom controls. - let zoom = view.map(|v| v.zoom * 100.0).unwrap_or(100.0); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 4.0; let mut z = None; @@ -373,17 +382,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } let sw = (ui.available_width() - 30.0).max(40.0); let track = |_: f32| t.input_border; - let shown = widgets::SliderValue::field(zoom, 3.13..=64000.0, "%", 2); - if let (Some(v), phase) = widgets::color_slider_valued(ui, "nav-slider", tl!("Zoom"), Some(shown), zoom_to_slider(zoom) as f32, sw, &track) + let range = zoom_range(print); + let shown = widgets::SliderValue::field(zoom, range.0..=range.1, "%", 2); + if let (Some(v), phase) = + widgets::color_slider_valued(ui, "nav-slider", tl!("Zoom"), Some(shown), zoom_to_slider(zoom, range) as f32, sw, &track) && phase != widgets::Live::Idle { - z = Some(slider_to_zoom(v as f64)); + z = Some(slider_to_zoom(v as f64, range)); } if widgets::icon_button(ui, "dc-zoom-large", tl!("Zoom In"), false, 22.0).clicked() { app.run("view.zoomIn", json!({})).ok(); } if let Some(z) = z { - app.run("view.setZoom", json!({"zoom": z.clamp(3.13, 64000.0)})).ok(); + app.run("view.setZoom", json!({"zoom": z.clamp(range.0, range.1)})).ok(); } }); } @@ -402,16 +413,28 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { mod tests { use super::*; - /// Screen readers get the Zoom slider's percent as the zoom field beside it shows it, on the - /// slider's 3.13% to 64000% range. + /// Screen readers get the Zoom slider's percent as the zoom field beside it shows it, counted + /// from Actual Size as `view.setZoom` counts it, on the zoom range: 3.13% to 64000% with + /// Display Print Size at 100% Zoom off, and the same zooms counted from 100% with it on, here + /// on a display of 127 points to an inch. #[test] fn screen_readers_get_the_zoom_the_field_shows() { use crate::widgets::accessibility_tests::{slider_value, tree}; let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); app.run("view.setZoom", json!({"zoom": 250})).unwrap(); let shown = tree(|ui| show(&mut app, ui)); assert_eq!(slider_value(&shown, "Zoom"), (Some(250.0), Some(3.13), Some(64000.0), Some("250%".to_string()))); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + app.set_screen_ppi(Some(127.0)); + app.run("view.setZoom", json!({"zoom": 250})).unwrap(); + let (lo, hi) = zoom_range(app.print_ppi()); + assert!(lo < 3.13 && hi < 64000.0, "a denser display than one point per point reaches less far in: {lo} to {hi}"); + let shown = tree(|ui| show(&mut app, ui)); + let (value, min, max, _) = slider_value(&shown, "Zoom"); + assert!(value.is_some_and(|v| (v - 250.0).abs() < 1e-9), "{value:?}"); + assert!(min.is_some_and(|m| (m - lo).abs() < 1e-6) && max.is_some_and(|m| (m - hi).abs() < 1e-6), "{min:?} to {max:?}"); } #[test] @@ -503,8 +526,8 @@ mod tests { let [points] = &drawn[..] else { panic!("UI Scaling {ui_zoom}×: one view box: {drawn:?}") }; let region = CACHE.with(|c| c.borrow().region.unwrap().1); // Each canvas corner is (its offset from the canvas's center) × UI Scaling / zoom - // document points from the view's center. - let k = f64::from(ui_zoom) / 4.0; + // document points from the view's center, with 400% counted from Actual Size. + let k = f64::from(ui_zoom) / (4.0 * crate::state::zoom_baseline(app.print_ppi())); let want = [canvas.left_top(), canvas.right_top(), canvas.right_bottom(), canvas.left_bottom()].map(|c| { let d = c - canvas.center(); doc_to_thumb(region, thumb, Point::new(200.0 + f64::from(d.x) * k, 150.0 + f64::from(d.y) * k)) @@ -729,9 +752,11 @@ mod tests { #[test] fn zoom_slider_roundtrip() { - assert!((zoom_to_slider(3.13)).abs() < 1e-9); - assert!((zoom_to_slider(64000.0) - 1.0).abs() < 1e-9); - assert!((slider_to_zoom(zoom_to_slider(100.0)) - 100.0).abs() < 1e-6); + let range = zoom_range(None); + assert_eq!(range, (3.13, 64000.0)); + assert!((zoom_to_slider(3.13, range)).abs() < 1e-9); + assert!((zoom_to_slider(64000.0, range) - 1.0).abs() < 1e-9); + assert!((slider_to_zoom(zoom_to_slider(100.0, range), range) - 100.0).abs() < 1e-6); } /// The navigator images made on this thread so far. diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 0fdf34b526..5160b2a222 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -224,13 +224,73 @@ pub struct Services { /// (before UI Scaling) per inch, from the physical size the system reports for that display. /// The desktop host keeps it current as the window moves between displays. With Display Print /// Size at 100% Zoom, 100% shows one document inch in this many points ([`crate::state::print_ppi`]). - /// `None` on the web and where the system reports no size, and then an inch takes 96 points. - pub screen_ppi: Option, + /// [`ScreenPpi::Unread`] on the web and until the host's first reading; a display that + /// reports no size reads as `Read(None)`. Either way an inch then takes 96 points. The views + /// the main window shows count from it; a document floating in an OS window of its own counts + /// from the display that shows that window ([`Self::screens`]). + pub screen_ppi: ScreenPpi, + /// The connected displays with their densities, kept current by the desktop host while + /// Display Print Size at 100% Zoom is on, for the document windows floating in OS windows of + /// their own ([`screen_ppi_at`]). Empty on the web. + pub screens: Vec, /// The text Help › Copy Troubleshooting Info copies (desktop: the platform, the graphics /// processor, recent commands and frame times, and the hang reports of this session and the /// one before). Without it the command copies the version only ([`crate::troubleshooting`]). pub troubleshooting: Option String>>, } +/// The density of a display as far as the host has read it ([`Services::screen_ppi`]). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum ScreenPpi { + /// Not read yet. + #[default] + Unread, + /// Read: its points to an inch, `None` for a display that reports no physical size. + Read(Option), +} + +impl ScreenPpi { + /// The points to an inch, when the display was read and reports a size. + pub fn ppi(self) -> Option { + match self { + Self::Read(ppi) => ppi, + Self::Unread => None, + } + } +} + +/// A connected display ([`Services::screens`]): where it is on the desktop, in the physical pixels +/// winit gives its position and size in, its scale factor, and its density in points (at that +/// scale factor) per inch: `Read(None)` where the system reports no physical size for it, and +/// unread while it has not answered. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ScreenDensity { + /// Left, top, width and height in physical pixels. + pub rect: [i32; 4], + pub scale: f64, + pub ppi: ScreenPpi, +} + +/// The density of the display that shows most of the viewport `ctx` draws, from `screens`: of the +/// displays at the viewport's scale factor, the one whose rect covers the largest part of the +/// viewport, in the physical pixels of that scale factor. On macOS each display's pixels are its +/// points times its own scale factor, so displays of different scales can overlap in those pixels +/// and the scale tells them apart. `None` when the viewport reports no position (Wayland, the web) +/// or covers no display. +pub fn screen_ppi_at(screens: &[ScreenDensity], ctx: &egui::Context) -> Option { + let (rect, ppp, native) = ctx.input(|i| (i.viewport().outer_rect, i.pixels_per_point(), i.viewport().native_pixels_per_point)); + let (rect, ppp, native) = (rect?, f64::from(ppp), f64::from(native?)); + let [l, t, r, b] = [rect.left(), rect.top(), rect.right(), rect.bottom()].map(|v| f64::from(v) * ppp); + if ![l, t, r, b].iter().all(|v| v.is_finite()) { + return None; + } + let covered = |s: &ScreenDensity| { + let [x, y, w, h] = s.rect.map(f64::from); + ((r.min(x + w) - l.max(x)).max(0.0)) * ((b.min(y + h) - t.max(y)).max(0.0)) + }; + let best = screens.iter().filter(|s| (s.scale - native).abs() < 1e-3).map(|s| (covered(s), s)).max_by(|a, b| a.0.total_cmp(&b.0))?; + (best.0 > 0.0).then_some(best.1.ppi) +} + /// Rewrites one window's raw input before egui reads it ([`Services::native_input_hook`]). pub type NativeInputHook = std::sync::Arc; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index fe30649b14..5a2681e7e7 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -44,11 +44,30 @@ pub struct View { /// document opens in Preview. #[serde(default)] pub outline: bool, + /// The density of the display the view was last shown on ([`crate::Services::screen_ppi`]), + /// which its zoom percentage counts from with Display Print Size at 100% Zoom; `None` until + /// the view was first shown ([`crate::VectorcraftApp::settle_screen_ppi`]). + #[serde(skip)] + pub(crate) shown_ppi: Option, + /// The zoom a fit to the window, or the document's saved view, gave the view. While the view + /// still has it, the first reading of its display leaves the zoom alone; a zoom chosen as a + /// percentage keeps its percentage then ([`crate::VectorcraftApp::settle_screen_ppi`]). + #[serde(skip)] + pub(crate) fit_zoom: Option, } impl Default for View { fn default() -> Self { - Self { zoom: 1.0, center: Point::new(306.0, 396.0), fitted: false, rotation: 0.0, artboard: 0, outline: false } + Self { + zoom: 1.0, + center: Point::new(306.0, 396.0), + fitted: false, + rotation: 0.0, + artboard: 0, + outline: false, + shown_ppi: None, + fit_zoom: None, + } } } @@ -65,13 +84,16 @@ impl View { /// the zoom range; `None` when the canvas can't show it (a zoom or centre that isn't finite, a /// zoom of 0 or less). pub fn saved(v: &vectorcraft_engine::doc::SavedView) -> Option { + let zoom = v.zoom.clamp(0.0313, 640.0); v.is_usable().then(|| Self { - zoom: v.zoom.clamp(0.0313, 640.0), + zoom, + fit_zoom: Some(zoom), center: v.center, fitted: true, rotation: if v.rotation.is_finite() { v.rotation } else { 0.0 }, artboard: 0, outline: false, + shown_ppi: None, }) } @@ -146,13 +168,14 @@ pub fn zoom_from_display_percent(pct: f64, print: Option) -> f64 { } /// The preset zoom stop after zoom `z` (`up`) or before it, counted in the percentages the zoom -/// field shows with 100% at [`zoom_baseline`]`(print)`, kept in the zoom range. +/// field shows with 100% at [`zoom_baseline`]`(print)`, kept in the zoom range. Past the last stop +/// in that direction, the end of the zoom range. pub fn next_zoom(z: f64, up: bool, print: Option) -> f64 { let pct = zoom_display_percent(z, print); let stop = if up { - ZOOM_STOPS.iter().find(|s| **s > pct + 0.01).copied().unwrap_or(64000.0) + ZOOM_STOPS.iter().find(|s| **s > pct + 0.01).copied().unwrap_or_else(|| zoom_display_percent(640.0, print)) } else { - ZOOM_STOPS.iter().rev().find(|s| **s < pct - 0.01).copied().unwrap_or(3.13) + ZOOM_STOPS.iter().rev().find(|s| **s < pct - 0.01).copied().unwrap_or_else(|| zoom_display_percent(0.0313, print)) }; zoom_from_display_percent(stop, print).clamp(0.0313, 640.0) } @@ -1629,8 +1652,11 @@ mod tests { } assert_eq!(zoom_label(zoom_from_display_percent(100.0, dense), dense), "100%"); let thin = print_ppi(true, Some(40.0)); - assert!(next_zoom(0.04, false, thin) >= 0.0313, "the last stop down stays in the zoom range"); + assert!(next_zoom(0.0313, false, thin) >= 0.0313, "the last stop down stays in the zoom range"); assert!(next_zoom(600.0, true, print_ppi(true, Some(900.0))) <= 640.0, "and the last stop up"); + let reference = print_ppi(true, None); + assert!(next_zoom(0.0313, false, reference) <= 0.0313, "past the last stop, zooming out does not zoom in"); + assert!(next_zoom(640.0, true, thin) >= 640.0, "nor zooming in out"); } #[test] diff --git a/crates/ui-egui/src/tests/tab_overflow.rs b/crates/ui-egui/src/tests/tab_overflow.rs index 59af211e17..b2aab999a9 100644 --- a/crates/ui-egui/src/tests/tab_overflow.rs +++ b/crates/ui-egui/src/tests/tab_overflow.rs @@ -91,6 +91,8 @@ fn the_tab_that_does_not_fit_whole_fills_the_rest_of_the_strip() { #[test] fn inactive_tabs_show_the_name_alone_so_more_tabs_fit() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); + // The titles' widths are measured at 100% with one document point per screen point. + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); for i in 0..12 { app.run("file.new", json!({"width": 100, "height": 100, "name": format!("Tab test {i}")})).unwrap(); } diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 4c8c25392d..771411b53a 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -401,7 +401,7 @@ fn double_clicking_the_hand_zoom_and_transform_tools() { let v = *app.view().unwrap(); assert_eq!((v.center.x, v.center.y, v.zoom), (150.0, 100.0, 2.0)); app.run("tool.options", json!({"tool": "zoom"})).unwrap(); - assert_eq!(app.view().unwrap().zoom, 1.0); + assert_eq!(app.view().unwrap().zoom, crate::state::zoom_baseline(app.print_ppi())); // The transform tools open their dialogs, like Object › Transform: not with nothing selected. assert_eq!(app.run("tool.options", json!({"tool": "rotate"})), Err("nothing selected".into())); assert!(app.ui.dialog.is_none()); diff --git a/docs/mcp.md b/docs/mcp.md index bdafc83ef8..8f48dde8d0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8286,13 +8286,17 @@ their own Anti-aliasing option), `scrubNumericFields` (on: a horizontal drag on a numeric field's label steps the field, one undo step per drag; the control channel's `ui.drag` scrubs), `showHomeScreen` (on by default: the Home screen while no document is open; off, an empty window, and the Home button or `app.home` still shows the screen), `autoCollapseIconPanels` (off by -default: on, a click away from a panel popped out of the icon column puts it away), `displayPrintSize` (off by -default: View › Actual Size / `view.actualSize` is one document point per screen point; on, one document inch fills -an inch of the display that shows the main window, measured from the physical size macOS, Windows, X11 or the -Wayland compositor reports for it and measured again when the window moves to another display, where every -document window keeps its zoom percentage; where the system -reports no size, as on the web, or a size no display has, an inch is 96 screen points). `uiScaling` scales the -interface and not the art: a zoom shows the art at the same size at every UI Scaling. The tool shortcut +default: on, a click away from a panel popped out of the icon column puts it away), `displayPrintSize` (on by +default, also for saved preferences without the key: View › Actual Size / `view.actualSize` shows one document inch +in an inch of the display that shows the document's window, measured from the physical size macOS, Windows, X11 or +the Wayland compositor reports for that display. A document under the tabs counts from the main window's display, +and a document floating in an OS window of its own counts from that window's display. A window that moves to a +display of another density keeps its zoom percentage. Where the system reports no size, as on the web, or a size no +display has, an inch is 96 screen points. A view whose zoom counted from 96 points keeps its zoom when the first +measurement arrives. Off, 100% is one document point per screen point, and the desktop app does not measure the +displays. While it is on, `ui.inspect` gives `screenPpi`, the measured density of the main window's display, and +`printPpi`, the points an inch takes at 100% in the current window; both are null while it is off). `uiScaling` +scales the interface and not the art: a zoom shows the art at the same size at every UI Scaling. The tool shortcut preference `holdToolKeys` also needs the desktop app. It is on by default: a single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses the tool until the key is let go and then returns to the tool active before, after any drag in progress; a quicker press chooses the tool for good. With it off, every press and every key diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 15ad6a5160..f252db9314 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1292,7 +1292,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen rubber band after a smooth anchor:** the preview segment to the pointer is the curve a click there adds, leaving the last anchor along its outgoing handle and arriving at the new corner anchor without a handle, so the segment keeps its shape when the anchor is placed, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes. Before, the preview was a different curve, and the segment changed shape at the click (#8296, in part; `pen::tests::rubber_band_is_the_segment_a_click_adds`); scores and estimates unchanged. - **Pen rubber band over an anchor a click ends on:** over the path's first anchor, the preview segment ends on that anchor, as the closing segment does; over an end of another open path, it ends on that end and arrives along the end's own handle, as the joining segment does. The preview picks these anchors at the pointer before snapping, as a press does. Before, the preview ended at the pointer and arrived without a handle, so the segment moved by up to the pick tolerance at the click, and changed shape when the other end was smooth (#8296, in part; the `pen_rubber_band` tests in `engine/tests/it`); scores and estimates unchanged. - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills an inch of the display that shows the main window, measured from the physical size the system reports for it, or 96 screen points where it reports none; `view.actualSize` / `prefs.set`, #394, #9051). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). + - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (on by default, as [the help page](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes; in VectorCraft, View › Actual Size shows one document inch in an inch of the display that shows the document's window, measured from the physical size the system reports for that display, or 96 screen points where it reports none; off, one document point per screen point; `view.actualSize` / `prefs.set`, #394, #9051). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). - Preferences › General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default; dimmed while Zoom with Mouse Wheel is on): while Zoom with Mouse Wheel is off, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer, and once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. Under either wheel preference, Cmd/Ctrl with a touchpad zooms about the pointer. - Preferences › Type › Highlight Substituted Fonts (on by default) paints pink behind text drawn in a substitute for a missing font in every document, and turning it off removes that highlight everywhere (`prefs.set highlightSubstitutedFonts`); Document Setup keeps Highlight Substituted Glyphs ([help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/edit-text-without-replacing-missing-fonts.html)). - Preferences › User Interface › UI Scaling scales the interface ([help](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/modify-workspaces.html)). VectorCraft's own rule is that it leaves the art's size alone: at a given zoom a document point covers the same device pixels at every UI Scaling, so View › Actual Size shows the art at the same size whatever the UI Scaling. A click, a pinch or wheel zoom about the pointer, a pan, the Zoom tool's marquee, Fit, tiled panes, Pixel Preview and the Navigator's view box use the same mapping. Evidence: `canvas::tests_ui_scaling`, `tiled_documents_fit_their_panes_at_every_ui_scaling`, `the_view_box_outlines_the_canvas_at_every_ui_scaling`. Scores unchanged. From 341f7644587d578512f454cfb3b169ce72dad98b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:26:18 -0800 Subject: [PATCH 037/101] Scripts: editable is false on a locked artboard, page item lists kept for several documents - PageItem.editable is false for art on a locked artboard, as remove() refuses it. A group on a locked artboard is measured once for all its members. - The lists of page items are kept for the last four documents read, so a script that reads two documents in turn does not walk each one again on every index. --- crates/engine/Cargo.toml | 5 +- crates/engine/src/script/dom.rs | 103 +++++++++++++++++++++++--- crates/engine/src/tests/script_dom.rs | 23 ++++++ docs/mcp.md | 3 +- 4 files changed, 119 insertions(+), 15 deletions(-) diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 075211dc1a..460893a7c8 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -104,8 +104,9 @@ proptest = { workspace = true } vectorcraft-text = { workspace = true, features = ["test-fonts"] } # How many times an open reads a PDF. vectorcraft-pdf = { workspace = true, features = ["read-count"] } -# How many times the symbol list is read to find symbols by name. -vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } +# How many times the symbol list is read to find symbols by name, and how many objects are +# measured against locked artboards. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count", "locked-artboard-count"] } wat = { workspace = true } # Zstandard streams for the Illustrator editing data fuzz tests. ruzstd = { workspace = true } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 675ab3fb5a..830351f375 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -28,6 +28,7 @@ //! - Members the help pages list that are not here yet throw an error that says so. use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::sync::Arc; @@ -84,13 +85,15 @@ pub(super) enum Coords { const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; -/// What the object model keeps for one run: its coordinate system, the last list of a document's -/// page items, kept while that document is unchanged, whether a call's own savepoint -/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. +/// What the object model keeps for one run: its coordinate system, the lists of page items and the +/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read, +/// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is +/// open, and the settings of each `DocumentPreset` the run made. #[derive(Default)] pub(super) struct State { coords: Cell, - items: RefCell>, + items: RefCell>, + locked: RefCell>, saving: Cell, presets: RefCell>>, } @@ -125,6 +128,57 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result, Rc>); +/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for +/// each object of a layer or sublayer asked about then, whether it was on a locked artboard. +type LockedList = (u64, Arc, Arc>, HashMap); + +/// How many documents' lists [`State`] keeps at once, of each kind. +const ITEM_LISTS: usize = 4; + +/// The kept list of the document `uid` as `doc` is, if there is one. +fn kept_items(lists: &[ItemList], uid: u64, doc: &Arc) -> Option>> { + lists.iter().find(|(u, d, _)| *u == uid && Arc::ptr_eq(d, doc)).map(|(_, _, ids)| ids.clone()) +} + +/// Keeps `list` in place of any earlier list of the same document, dropping the least recently +/// kept list beyond [`ITEM_LISTS`]. +fn keep_items(lists: &mut Vec, list: ItemList) { + lists.retain(|(u, _, _)| *u != list.0); + if lists.len() >= ITEM_LISTS { + lists.remove(0); + } + lists.push(list); +} + +/// Whether node `id` of `st` is on a locked artboard ([`Document::on_locked_artboard`]). Each +/// object of a layer or sublayer is measured once while the document and its new art stay as they +/// are, so the members of a group are answered with one measurement of the group. +fn on_locked_artboard(h: &Host, st: &DocState, id: NodeId) -> bool { + if !st.doc.artboards.iter().any(|a| a.locked) { + return false; + } + let Some(object) = st.doc.layer_object(id).map(|n| n.id) else { + return false; + }; + let new_art = st.doc.new_art.get(); + let mut lists = h.dom.locked.borrow_mut(); + let at = match lists.iter().position(|(u, d, n, _)| *u == st.uid && Arc::ptr_eq(d, &st.doc) && Arc::ptr_eq(n, &new_art)) { + Some(at) => at, + None => { + lists.retain(|(u, ..)| *u != st.uid); + if lists.len() >= ITEM_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), new_art, HashMap::new())); + lists.len() - 1 + } + }; + match lists.get_mut(at) { + Some((.., held)) => *held.entry(object).or_insert_with(|| st.doc.on_locked_artboard(object)), + None => st.doc.on_locked_artboard(object), + } +} + type Answer = std::result::Result; /// A member function: the run's host and the call's arguments, `this` first. @@ -332,13 +386,11 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { } } -/// The ids of a document's page items in paint order ([`State`] keeps the last list). +/// The ids of a document's page items in paint order ([`State`] keeps the lists of the last +/// documents read). fn page_items(h: &Host, st: &DocState) -> Rc> { - if let Some((uid, doc, ids)) = &*h.dom.items.borrow() - && *uid == st.uid - && Arc::ptr_eq(doc, &st.doc) - { - return ids.clone(); + if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) { + return ids; } fn walk(nodes: &[Arc], out: &mut Vec) { for n in nodes { @@ -356,7 +408,7 @@ fn page_items(h: &Host, st: &DocState) -> Rc> { let mut ids = Vec::new(); walk(&st.doc.layers, &mut ids); let ids = Rc::new(ids); - *h.dom.items.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); + keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone())); ids } @@ -1518,9 +1570,11 @@ fn item_set_height(h: &Host, a: &[Data]) -> Answer { resize(h, a, false) } +/// `editable`: false for an object that is hidden or locked, in a hidden or locked layer or group, +/// or on a locked artboard. fn item_editable(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)))) + Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && !on_locked_artboard(h, st, item.id)))) } /// The item's place in its parent's stacking order, from 1 at the bottom. @@ -1950,4 +2004,29 @@ mod tests { assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into()))); assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); } + + #[test] + fn page_item_lists_are_kept_for_several_documents() { + let docs: Vec> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect(); + let ids = |n: u64| Rc::new(vec![NodeId(n)]); + let mut lists = Vec::new(); + keep_items(&mut lists, (1, docs[0].clone(), ids(1))); + keep_items(&mut lists, (2, docs[1].clone(), ids(2))); + // Reading two documents in turn keeps both lists. + assert_eq!(kept_items(&lists, 1, &docs[0]), Some(ids(1))); + assert_eq!(kept_items(&lists, 2, &docs[1]), Some(ids(2))); + // A changed document has no kept list, and its new list replaces the old one. + let changed = Arc::new(Document::new(100.0, 100.0)); + assert_eq!(kept_items(&lists, 1, &changed), None); + keep_items(&mut lists, (1, changed.clone(), ids(3))); + assert_eq!(lists.len(), 2); + assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3))); + // Past the limit, the list kept longest ago goes. + for (uid, d) in (10..).zip(&docs[2..]) { + keep_items(&mut lists, (uid, d.clone(), ids(uid))); + } + assert_eq!(lists.len(), ITEM_LISTS); + assert_eq!(kept_items(&lists, 2, &docs[1]), None); + assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3))); + } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index bb283e7dab..7ebad8e3f2 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1016,11 +1016,34 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { let doc = &s.active().unwrap().doc; assert!(doc.node(a).is_some() && doc.node(b).is_some() && doc.node(c).is_some()); assert_eq!(undo_steps(&s), steps); + // `editable` is false for art on the locked artboard and true for art on the unlocked one. + let editable = "var p = app.activeDocument.pageItems; vc.log([p[0].editable, p[1].editable, p[2].editable]);"; + assert_eq!(log(&mut s, editable), vec![json!([false, false, true])]); lock(&mut s, false); + assert_eq!(log(&mut s, editable), vec![json!([true, true, true])]); let out = log(&mut s, "var p = app.activeDocument.pageItems; p[1].remove(); p.removeAll(); vc.log(p.length);"); assert_eq!(out, vec![json!(0)]); } +/// Reading `editable` on every member of a group on a locked artboard measures the group once. +#[test] +fn editable_measures_a_group_on_a_locked_artboard_once() { + let (mut s, a, b) = doc(); + let mut ids = vec![a.0, b.0]; + ids.extend((0..20).map(|i| rect(&mut s, 10.0 + f64::from(i), 200.0, 5.0, 5.0).0)); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let before = vectorcraft_doc::locked_artboard_measures(); + let out = log(&mut s, "var p = app.activeDocument.pageItems, n = 0; for (var i = 0; i < p.length; i++) if (!p[i].editable) n++; vc.log(n);"); + assert_eq!(out, vec![json!(23)], "the group and its 22 members are on the locked artboard"); + assert_eq!(vectorcraft_doc::locked_artboard_measures() - before, 1); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 095975a485..90591ae2ea 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2648,7 +2648,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + visible bounds), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, + or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same From 1a48bd827bb5d8bd46e79c1bf0d90290ce6e2bd4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 04:45:52 -0800 Subject: [PATCH 038/101] Display Print Size: a fit made during a reading counts from the last one A fit made in the main window while its display was being read counted from 96 points to an inch until the reading arrived, so the zoom field, the tab title and the zoom stops counted from a different density than the window's other views. The fit now counts from the last reading, and the reading, when it comes, keeps the fit's zoom, also when the views are settled again before it arrives. An app that draws no frames now still reads the displays again a minute after the last reading: it asks for a frame then. Tests now cover Actual Size after a fit that gave the same zoom, a Navigator thumbnail click, and a floating OS window's display readings (first display, a move, off every display, a fit, and docking back). docs/mcp.md now states which views keep their zoom at the first reading, that X11 and Wayland are read on Linux only, that headless sessions and the CLI count 96 points to an inch, and that the preference also applies in Pixel Preview. The progress line names the two rules that differ from the help page. --- apps/vectorcraft/src/screen_density.rs | 14 ++++++++-- crates/ui-egui/src/app/view.rs | 20 ++++++++++--- crates/ui-egui/src/canvas/tests.rs | 25 +++++++++++++++++ crates/ui-egui/src/doc_windows/tests.rs | 37 +++++++++++++++++++++++++ crates/ui-egui/src/panels/navigator.rs | 36 ++++++++++++++++++++++++ crates/ui-egui/src/state.rs | 7 +++++ docs/mcp.md | 18 +++++++----- docs/target-app-parity.md | 2 +- 8 files changed, 144 insertions(+), 15 deletions(-) diff --git a/apps/vectorcraft/src/screen_density.rs b/apps/vectorcraft/src/screen_density.rs index c89934a3c7..70ba069684 100644 --- a/apps/vectorcraft/src/screen_density.rs +++ b/apps/vectorcraft/src/screen_density.rs @@ -5,13 +5,16 @@ //! //! - macOS: `CGDisplayScreenSize`. //! - Windows: `GetDpiForMonitor`'s raw density (`windows_display_size`). -//! - X11, XWayland included: the RandR output's width and height in millimeters. -//! - Wayland: the physical width and height of the compositor's `wl_output` for the display. +//! - X11 on Linux, XWayland included: the RandR output's width and height in millimeters. +//! - Wayland on Linux: the physical width and height of the compositor's `wl_output` for the display. +//! - Other systems: no size, so an inch takes 96 points. //! //! A display that reports no size, or a size no display has, gives `None`, and an inch then takes //! 96 points. While the preference is on, the displays are listed once a second while the app //! draws. When the list changes, a background thread reads every display's size, and a later -//! frame takes the result. A reading that fails is tried again after [`RETRY_AFTER`] seconds. +//! frame takes the result. A reading that fails is tried again after [`RETRY_AFTER`] seconds, and +//! the displays are read again [`READ_AGAIN_AFTER`] seconds after the last reading; the app draws a +//! frame for each of these when nothing else makes it draw. use std::sync::mpsc::{Receiver, TryRecvError}; @@ -140,6 +143,11 @@ impl Tracker { { let due = (at + RETRY_AFTER).max(self.looked.map_or(0.0, |l| l + LOOK_EVERY)); ctx.request_repaint_after(std::time::Duration::from_secs_f64((due - now).clamp(0.0, RETRY_AFTER))); + } else if enabled && self.running.is_none() && self.read.is_some() { + // An app that is not drawing still lists and reads the displays READ_AGAIN_AFTER seconds + // after the last reading. + let due = (self.read_at + READ_AGAIN_AFTER).max(self.looked.map_or(0.0, |l| l + LOOK_EVERY)); + ctx.request_repaint_after(std::time::Duration::from_secs_f64((due - now).clamp(0.0, READ_AGAIN_AFTER))); } densities } diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 383504b49c..f20ad4758f 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -174,8 +174,9 @@ impl VectorcraftApp { } /// [`Self::settle_screen_ppi`] for window `w` alone. With `keep` false (a fit made for the - /// window), the view counts from the display's reading, or from its first reading still to - /// come, without a change of zoom. + /// window), the view counts from the display's reading, without a change of zoom; while the + /// display is being read, it counts from the last reading, and the reading still to come + /// leaves its zoom alone. pub(crate) fn settle_window_ppi(&mut self, w: crate::doc_windows::Win, keep: bool) { let on = self.session.prefs.display_print_size; let now = self.window_ppi(w); @@ -185,10 +186,18 @@ impl VectorcraftApp { // keeps the zoom chosen meanwhile. if !on { v.shown_ppi = Some(crate::ScreenPpi::Unread); + v.fit_unread = false; return; } if !keep { - v.shown_ppi = Some(reading); + // While the display is being read, the fit counts from the last reading, as the other + // views there do, and the reading keeps its zoom. + v.shown_ppi = Some(now); + v.fit_unread = reading == crate::ScreenPpi::Unread; + return; + } + // A fit made while its display is being read waits for that reading. + if v.fit_unread && reading == crate::ScreenPpi::Unread { return; } // A display that has not answered yet leaves the view counting from the last one read, so @@ -197,11 +206,14 @@ impl VectorcraftApp { v.shown_ppi.get_or_insert(now); return; }; + let fitted = v.fit_zoom == Some(v.zoom); let before = match v.shown_ppi { + _ if fitted && v.fit_unread => None, Some(crate::ScreenPpi::Read(before)) => Some(before), - _ if v.fit_zoom == Some(v.zoom) => None, + _ if fitted => None, _ => Some(None), }; + v.fit_unread = false; if let Some(before) = before && before != after && let (Some(b), Some(a)) = (crate::state::print_ppi(on, before), crate::state::print_ppi(on, after)) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index b72980e082..2576980464 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -8641,6 +8641,8 @@ fn actual_size_and_fits_made_before_a_reading_keep_their_meaning() { assert!(app.set_screen_reading(crate::ScreenPpi::Unread), "the window moved to a display being read"); app.run("view.fitArtboard", json!({})).unwrap(); let fitted = app.view().unwrap().zoom; + assert_eq!(app.print_ppi(), Some(127.0), "meanwhile the fit counts from the last reading, as the window's other views do"); + app.settle_screen_ppi(); assert!(app.set_screen_ppi(Some(190.0))); assert_eq!(app.view().unwrap().zoom, fitted, "the fit was made for this display"); assert!(app.set_screen_reading(crate::ScreenPpi::Unread), "and to another display being read"); @@ -8649,6 +8651,29 @@ fn actual_size_and_fits_made_before_a_reading_keep_their_meaning() { assert!((app.view().unwrap().zoom * 72.0 - 110.0).abs() < 1e-9, "Actual Size there is 100%: {}", app.view().unwrap().zoom * 72.0); } +/// Actual Size chosen before the first reading is still 100% when the reading arrives, also when a +/// fit made before it gave the view the same zoom. A zoom chosen after a fit made while the display +/// is being read keeps its percentage when the reading arrives. +#[test] +fn actual_size_after_a_fit_of_the_same_zoom_stays_at_100_percent() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 300, "height": 100})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(460.0, 260.0))); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + app.run("view.fitArtboard", json!({})).unwrap(); + assert!((app.view().unwrap().zoom * 72.0 - 96.0).abs() < 1e-9, "the fit has Actual Size's zoom before any reading"); + app.run("view.actualSize", json!({})).unwrap(); + assert!(app.set_screen_ppi(Some(127.0))); + assert!((app.view().unwrap().zoom * 72.0 - 127.0).abs() < 1e-9, "Actual Size keeps 100%: {}", app.view().unwrap().zoom * 72.0); + assert!(app.set_screen_reading(crate::ScreenPpi::Unread), "the window moved to a display being read"); + app.run("view.fitArtboard", json!({})).unwrap(); + app.run("view.zoomIn", json!({})).unwrap(); + let shown = crate::state::zoom_display_percent(app.view().unwrap().zoom, app.print_ppi()); + assert!(app.set_screen_ppi(Some(150.0))); + let now = crate::state::zoom_display_percent(app.view().unwrap().zoom, app.print_ppi()); + assert!((now - shown).abs() < 1e-9, "a zoom chosen after the fit keeps its percentage: {shown} → {now}"); +} + /// Fit Artboard in Window fits the artboard as a rotated view shows it: at 45° every corner is /// on the canvas and one is within the 30-point margin of an edge. At 0° the zoom is unchanged. #[test] diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index d4f280267b..8a001a3748 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -1294,3 +1294,40 @@ fn a_floating_window_counts_100_percent_from_its_own_display() { app.settle_screen_ppi_if_changed(); assert_eq!(app.views[1].zoom, fitted, "the fit is made for the main window's display"); } + +/// What the host found for a floating OS window's display reaches its view: its first display and +/// a move to another keep 100%, a window off every display is unread and keeps its zoom, a fit made +/// in the frame its window reached a new display stays the fit, and the window drawn in the main +/// window again counts from the main window's display. +#[test] +fn a_floating_os_window_takes_the_density_of_the_display_it_is_found_on() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + app.set_screen_ppi(Some(127.0)); + app.run("view.actualSize", json!({})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + let uid = app.session.documents()[1].uid; + let win = (1, 1); + let found = |ppi: Option| Shown { ppi, ..Default::default() }; + let inch = |app: &VectorcraftApp| app.views[1].zoom * 72.0; + take_window_ppi(&mut app, &ctx, ((uid, 1), true), win, &mut found(Some(crate::ScreenPpi::Read(Some(91.0))))); + assert!((inch(&app) - 91.0).abs() < 1e-9, "its first display keeps 100%: {}", inch(&app)); + take_window_ppi(&mut app, &ctx, ((uid, 1), true), win, &mut found(Some(crate::ScreenPpi::Read(Some(150.0))))); + assert!((inch(&app) - 150.0).abs() < 1e-9, "and so does a move to a denser one: {}", inch(&app)); + take_window_ppi(&mut app, &ctx, ((uid, 1), true), win, &mut found(None)); + assert_eq!(screen_ppi(&app, win), Some(crate::ScreenPpi::Unread), "off every display it is unread"); + assert!((inch(&app) - 150.0).abs() < 1e-9, "and keeps its zoom"); + // A fit made in the frame the window reaches a display of another density stays the fit. + app.run("view.fitArtboard", json!({})).unwrap(); + let (zoom, center) = (app.views[1].zoom, app.views[1].center); + let body = egui::Rect::from_min_size(Pos2::ZERO, vec2(500.0, 400.0)); + let mut fitted = + Shown { ppi: Some(crate::ScreenPpi::Read(Some(110.0))), body: Some(body), fit: Some((body.size(), zoom, center)), ..Default::default() }; + take_window_ppi(&mut app, &ctx, ((uid, 1), true), win, &mut fitted); + assert_eq!(app.views[1].zoom, zoom, "the fit was made for that display"); + app.run("view.setZoom", json!({"zoom": 100})).unwrap(); + take_window_ppi(&mut app, &ctx, ((uid, 1), false), win, &mut found(Some(crate::ScreenPpi::Read(Some(110.0))))); + assert!((inch(&app) - 127.0).abs() < 1e-9, "drawn in the main window, 100% counts from the main window's display: {}", inch(&app)); +} diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index 89df32b658..a41445ae80 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -437,6 +437,42 @@ mod tests { assert!(min.is_some_and(|m| (m - lo).abs() < 1e-6) && max.is_some_and(|m| (m - hi).abs() < 1e-6), "{min:?} to {max:?}"); } + /// A click on the thumbnail moves the view there and keeps the zoom percentage, here with + /// Display Print Size at 100% Zoom on a display of 127 points to an inch. + #[test] + fn a_click_on_the_thumbnail_keeps_the_zoom() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + app.set_screen_ppi(Some(127.0)); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.canvas_rect = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 400.0))); + app.run("view.setZoom", json!({"zoom": 250, "center": [200, 150]})).unwrap(); + let percent = |app: &VectorcraftApp| crate::state::zoom_display_percent(app.view().unwrap().zoom, app.print_ppi()); + let before = (app.view().unwrap().center, percent(&app)); + let ctx = egui::Context::default(); + let run = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out + }; + let pasteboard = Tokens::get(&ctx).pasteboard; + let thumb = run(&mut app, vec![]) + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Rect(r) if r.fill == pasteboard => Some(r.rect), + _ => None, + }) + .expect("the thumbnail"); + let at = thumb.left_top() + thumb.size() * 0.25; + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![egui::Event::PointerMoved(at)]); + run(&mut app, vec![button(true)]); + run(&mut app, vec![button(false)]); + assert_ne!(app.view().unwrap().center, before.0, "the click moved the view"); + assert!((percent(&app) - before.1).abs() < 1e-9, "and kept {}%: {}%", before.1, percent(&app)); + } + #[test] fn thumb_mapping_roundtrip() { let region = DRect::new(0.0, 0.0, 200.0, 100.0); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 5a2681e7e7..751cd87584 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -54,6 +54,11 @@ pub struct View { /// percentage keeps its percentage then ([`crate::VectorcraftApp::settle_screen_ppi`]). #[serde(skip)] pub(crate) fit_zoom: Option, + /// The fit that gave [`Self::fit_zoom`] was made while the view's display was being read: the + /// view counts from the last reading meanwhile, and the reading, when it comes, leaves the zoom + /// alone while the view still has it. + #[serde(skip)] + pub(crate) fit_unread: bool, } impl Default for View { @@ -67,6 +72,7 @@ impl Default for View { outline: false, shown_ppi: None, fit_zoom: None, + fit_unread: false, } } } @@ -94,6 +100,7 @@ impl View { artboard: 0, outline: false, shown_ppi: None, + fit_unread: false, }) } diff --git a/docs/mcp.md b/docs/mcp.md index 8f48dde8d0..38640c6e77 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8288,13 +8288,17 @@ control channel's `ui.drag` scrubs), `showHomeScreen` (on by default: the Home s off, an empty window, and the Home button or `app.home` still shows the screen), `autoCollapseIconPanels` (off by default: on, a click away from a panel popped out of the icon column puts it away), `displayPrintSize` (on by default, also for saved preferences without the key: View › Actual Size / `view.actualSize` shows one document inch -in an inch of the display that shows the document's window, measured from the physical size macOS, Windows, X11 or -the Wayland compositor reports for that display. A document under the tabs counts from the main window's display, -and a document floating in an OS window of its own counts from that window's display. A window that moves to a -display of another density keeps its zoom percentage. Where the system reports no size, as on the web, or a size no -display has, an inch is 96 screen points. A view whose zoom counted from 96 points keeps its zoom when the first -measurement arrives. Off, 100% is one document point per screen point, and the desktop app does not measure the -displays. While it is on, `ui.inspect` gives `screenPpi`, the measured density of the main window's display, and +in an inch of the display that shows the document's window, measured from the physical size macOS, Windows, or on +Linux X11 or the Wayland compositor reports for that display. A document under the tabs counts from the main +window's display, and a document floating in an OS window of its own counts from that window's display. It also +applies in Pixel Preview. A window that moves to a display of another density keeps its zoom percentage. Where no +display is measured (the web build, the headless backend, `vectorcraft-cli`, and the desktop app on other systems), +where the system reports no size, or where it reports a size no display has, an inch is 96 screen points, so Actual +Size there shows 4/3 screen points per document point. When the first measurement of a display +arrives, a view that still has the zoom a fit or the document's saved view gave it keeps that zoom, and any other +view keeps its zoom percentage. Off, 100% is one document point per screen point, and the desktop app does not +measure the displays. While it is on, `ui.inspect` gives `screenPpi`, the measured density of the main window's +display, and `printPpi`, the points an inch takes at 100% in the current window; both are null while it is off). `uiScaling` scales the interface and not the art: a zoom shows the art at the same size at every UI Scaling. The tool shortcut preference `holdToolKeys` also needs the desktop app. It is on by default: a single-key tool shortcut held for 0.25 s diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f252db9314..e32dc77d7e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1292,7 +1292,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen rubber band after a smooth anchor:** the preview segment to the pointer is the curve a click there adds, leaving the last anchor along its outgoing handle and arriving at the new corner anchor without a handle, so the segment keeps its shape when the anchor is placed, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes. Before, the preview was a different curve, and the segment changed shape at the click (#8296, in part; `pen::tests::rubber_band_is_the_segment_a_click_adds`); scores and estimates unchanged. - **Pen rubber band over an anchor a click ends on:** over the path's first anchor, the preview segment ends on that anchor, as the closing segment does; over an end of another open path, it ends on that end and arrives along the end's own handle, as the joining segment does. The preview picks these anchors at the pointer before snapping, as a press does. Before, the preview ended at the pointer and arrived without a handle, so the segment moved by up to the pick tolerance at the click, and changed shape when the other end was smooth (#8296, in part; the `pen_rubber_band` tests in `engine/tests/it`); scores and estimates unchanged. - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (on by default, as [the help page](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes; in VectorCraft, View › Actual Size shows one document inch in an inch of the display that shows the document's window, measured from the physical size the system reports for that display, or 96 screen points where it reports none; off, one document point per screen point; `view.actualSize` / `prefs.set`, #394, #9051). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). + - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (on by default, as [the help page](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes; in VectorCraft, View › Actual Size shows one document inch in an inch of the display that shows the document's window, measured from the physical size the system reports for that display, or 96 screen points where it reports none; VectorCraft's own rules: a document in a floating window counts from that window's display, where the help page names only the primary monitor, and the preference also applies in Pixel Preview, which the help page leaves out; off, one document point per screen point; `view.actualSize` / `prefs.set`, #394, #9051). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). - Preferences › General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default; dimmed while Zoom with Mouse Wheel is on): while Zoom with Mouse Wheel is off, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer, and once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. Under either wheel preference, Cmd/Ctrl with a touchpad zooms about the pointer. - Preferences › Type › Highlight Substituted Fonts (on by default) paints pink behind text drawn in a substitute for a missing font in every document, and turning it off removes that highlight everywhere (`prefs.set highlightSubstitutedFonts`); Document Setup keeps Highlight Substituted Glyphs ([help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/edit-text-without-replacing-missing-fonts.html)). - Preferences › User Interface › UI Scaling scales the interface ([help](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/modify-workspaces.html)). VectorCraft's own rule is that it leaves the art's size alone: at a given zoom a document point covers the same device pixels at every UI Scaling, so View › Actual Size shows the art at the same size whatever the UI Scaling. A click, a pinch or wheel zoom about the pointer, a pan, the Zoom tool's marquee, Fit, tiled panes, Pixel Preview and the Navigator's view box use the same mapping. Evidence: `canvas::tests_ui_scaling`, `tiled_documents_fit_their_panes_at_every_ui_scaling`, `the_view_box_outlines_the_canvas_at_every_ui_scaling`. Scores unchanged. From b6bb1329cd95be72f64d6a3e8f6218fece31e5ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:58:20 -0800 Subject: [PATCH 039/101] New Document: choosing the selected Grid by Column keeps a preset's rows Clicking the layout that is already selected removed the rows of a preset made with file.new's rows and kept only the columns they showed, so Create put a different number of artboards in each column. With five artboards and rows 4, the first column got three artboards instead of four. A different layout or a new column count still replaces the rows. --- crates/ui-egui/src/dialogs/new_document.rs | 25 ++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index cf10f0035e..a36c1fb589 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -253,11 +253,14 @@ fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { } /// Sets one artboard layout field. A new layout or column count replaces the rows of a preset -/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. +/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. Choosing +/// the layout that is already selected keeps the rows. fn set_layout(d: &mut Dialog, key: &str, v: Value) { let (lay, shown, ..) = layout(d); let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); + let same = key == "layout" && v.as_str().and_then(ArtboardLayout::parse) == Some(lay); if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) + && !same && o.remove("rows").and_then(|r| r.as_f64()).is_some_and(|r| r.is_finite() && r >= 1.0) && key == "layout" && lay == ArtboardLayout::GridByColumn @@ -930,7 +933,7 @@ mod tests { app.run("file.newDialog", json!({})).unwrap(); let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; set(&mut app, "artboards", json!(9)); - for to in ["gridByRow", "gridByColumn", "row", "column"] { + for to in ["gridByRow", "row", "column"] { for rows in [json!(4), json!(4.0), json!(3.6)] { set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": rows})); assert_eq!(columns(&app), 3, "9 artboards in rows {rows}"); @@ -950,6 +953,24 @@ mod tests { assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow", "columns": 2})); } + /// Choosing the grid by column that is already selected keeps a preset's rows, so Create puts + /// as many artboards in each column as before. + #[test] + fn choosing_the_selected_layout_keeps_a_presets_rows() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + set(&mut app, "artboards", json!(5)); + let preset = json!({"layout": "gridByColumn", "columns": 2, "rows": 4, "spacing": 10}); + set(&mut app, "artboardLayout", preset.clone()); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByColumn")); + assert_eq!(field(&app, "artboardLayout"), preset); + crate::dialogs::confirm(&mut app).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.artboards.len(), 5); + let first: Vec<_> = st.doc.artboards.iter().filter(|a| a.rect.x0 == 0.0).map(|a| a.rect.y0).collect(); + assert_eq!(first.len(), 4, "four artboards in the first column: {first:?}"); + } + /// Columns shows what a preset's rows give the current number of artboards. #[test] fn columns_follow_a_presets_rows_as_artboards_change() { From a1bd1ba906f92e22c289d25de35338abc39c2f80 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:21:27 -0800 Subject: [PATCH 040/101] Shape Builder: a fill chosen while the tool is active leaves the selection's fills Choosing a fill while the Shape Builder was active (a swatch, the Color panel, the Fill box or a paint command) ran paint.setFill on every selected path, so all of them took the color. With Pick Color From set to Color Swatches the tool merges with the current fill, so the pick is the color for the next merge. While the Shape Builder is active, a fill chosen without ids, id or item now changes only the current fill, with either Pick Color From: with Color Swatches the next merge fills with it, and with Artwork merges still take their look from the art. A stroke chosen then still goes to the selection. Swap Fill and Stroke and Default Fill and Stroke change only the paint for new art, and Swap gives the current fill the stroke the Stroke proxy shows. This is VectorCraft's own rule; no default setting changes. - painting_tool_of says which tool paints with the chosen fill or stroke: the Live Paint Bucket with both, the Shape Builder with the fill. Session::tool_paints(stroke) replaces bucket_paints, so the paint and gradient commands, previews, the proxies, the Stroke panel and the Gradient panel's eyedropper follow it for each kind. - A new selection does not replace the tool's fill for new art, with New Art Has Basic Appearance on or off, and new art is not linked to a graphic style whose fill it does not have. - A cancel puts back a fill previewed for the tool, also after another tool was chosen during the drag. - An Eyedropper pick armed for a stop of the tool's gradient samples only into a stop of that gradient, and ends once that stop is gone. Choosing another tool drops the stop the pick was armed for, and a pick armed while the Eyedropper waits for a Cmd-drag keeps its stop. - The paint.freeform commands refuse the Shape Builder's fill as they refuse the Live Paint Bucket's colors, which lie on no object. For the gradient either tool paints with, the Color panel, the Gradient panel, the stop popover and swatch drops edit its stops instead of points, and the Gradient panel shows its Draw toggle, ramp and stop fields in place of the point controls. paint.editGradient keeps the given stops of a freeform gradient that has no points yet. - A gradient command that names no kind edits the proxy in front when the tool paints with it, else the kind the selection's active Appearance row stands for. - set_paint lists the commands that painted no object in unpainted. - Params text and docs/mcp.md describe the rule. Help (Pick Color From, Color Swatches): https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/shape-builder-tool-options.html https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=266 https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=267 --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/freeform.rs | 49 ++-- crates/engine/src/cmd/gradient.rs | 48 ++-- crates/engine/src/cmd/gradpresets.rs | 10 +- crates/engine/src/cmd/newart.rs | 24 +- crates/engine/src/cmd/paint.rs | 173 ++++++++---- crates/engine/src/cmd/stroke.rs | 8 +- crates/engine/src/cmd/xform.rs | 2 +- crates/engine/src/interaction.rs | 4 + crates/engine/src/lib.rs | 15 +- crates/engine/src/session/documents.rs | 3 +- crates/engine/src/session/edit.rs | 22 +- crates/engine/src/tests/build.rs | 297 ++++++++++++++++++++ crates/engine/src/tooling.rs | 61 +++- crates/mcp/src/tests.rs | 9 + crates/mcp/src/tools/definitions.rs | 2 +- crates/mcp/src/tools/dispatch.rs | 9 +- crates/mcp/src/tools/handlers.rs | 17 +- crates/tools/src/context.rs | 10 +- crates/tools/src/lib.rs | 1 + crates/tools/src/xform/eyedropper.rs | 49 ++-- crates/ui-egui/src/dialogs/gradient_stop.rs | 6 +- crates/ui-egui/src/panels.rs | 9 +- crates/ui-egui/src/panels/color.rs | 6 +- crates/ui-egui/src/panels/gradient.rs | 38 ++- crates/ui-egui/src/panels/gradient/tests.rs | 33 +++ crates/ui-egui/src/panels/stroke.rs | 2 +- docs/mcp.md | 24 +- 28 files changed, 750 insertions(+), 183 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..f9479a62cb 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::painting_tool_of; 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/freeform.rs b/crates/engine/src/cmd/freeform.rs index 548e5fade2..e31c21dd00 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Add Freeform Point", [], None, - "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (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 points); the points on a label's characters are not stored; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", + "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (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 points); the points on a label's characters are not stored; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {index}", has_doc, add_point ), @@ -28,7 +28,7 @@ pub fn specs() -> Vec { "Edit Freeform Point", [], None, - "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", + "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {index}", has_doc, set_point ), @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Delete Freeform Point", [], None, - "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", + "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {index}", has_doc, delete_point ), @@ -46,7 +46,7 @@ pub fn specs() -> Vec { "Add Freeform Line", [], None, - "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {line}", + "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {line}", has_doc, add_line ), @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Split Freeform Line", [], None, - "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", + "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {index}", has_doc, split_line ), @@ -64,7 +64,7 @@ pub fn specs() -> Vec { "Select Freeform Point", [], None, - "{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's; an index is an error while the proxies show the Live Paint Bucket's colors): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}", + "{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's; an index is an error while the proxy shows the colors the active tool paints with: the Live Paint Bucket's, the Shape Builder's fill): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}", has_doc, select_point ), @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Freeform Gradient", [], None, - "{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object (an error while the proxies show the Live Paint Bucket's colors) → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}", + "{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object (an error while the proxy shows the colors the active tool paints with: the Live Paint Bucket's, the Shape Builder's fill) → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}", has_doc, get ), @@ -81,13 +81,21 @@ pub fn specs() -> Vec { } const NOT_FREEFORM: &str = "the paint is not a freeform gradient (apply one with paint.editGradient {kind: \"freeform\"})"; -const BUCKET_NOT_FREEFORM: &str = "the Live Paint Bucket's colors have no freeform points (give ids, id or item to edit an object's)"; -const BUCKET_NO_POINTS: &str = "the Live Paint Bucket's colors have no freeform points"; + +/// " have no freeform points" for the tool whose colors the fill (or stroke, `stroke`) +/// proxy shows ([`Session::painting_tool`]): the Live Paint Bucket's colors, the Shape Builder's +/// fill. None when the proxy shows the selection's paint. +fn tool_no_points(s: &Session, stroke: bool) -> Option<&'static str> { + s.painting_tool(stroke).map(|id| match id { + "shapeBuilder" => "the Shape Builder's fill has no freeform points", + _ => "the Live Paint Bucket's colors have no freeform points", + }) +} /// The error of `paint.freeform.get` and `paint.freeform.selectPoint` when the active proxy shows no freeform gradient: -/// while the Live Paint Bucket paints, the proxies show its colors, which have none. -fn no_proxy_freeform(s: &Session) -> &'static str { - if s.bucket_paints() { BUCKET_NO_POINTS } else { NOT_FREEFORM } +/// while the active tool paints with the chosen colors of that kind, the proxy shows them, which have none. +fn no_proxy_freeform(s: &Session, stroke: bool) -> &'static str { + tool_no_points(s, stroke).unwrap_or(NOT_FREEFORM) } impl Session { @@ -187,13 +195,16 @@ pub(crate) fn parse_mode(m: &str) -> std::result::Result { /// as one undo step; returns what it returned for the first. An unplaced gradient gets the /// automatic points it shows first, and the stops follow the points' colours. fn edit(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freeform, Space) -> std::result::Result) -> Result { - // While the Live Paint Bucket paints, the proxies show its colors, which have no freeform points - // (paint.freeform.get finds none): an edit that names no target is refused. A bad `aligned` or - // `target` is refused first, as it is without the bucket. - if super::paint::for_bucket(s, p) { + // While the active tool paints with the chosen colors (the Live Paint Bucket's, the Shape + // Builder's fill), the proxy shows them, and they have no freeform points (paint.freeform.get + // finds none): an edit that names no target is refused. A bad `aligned`, `target` or `stroke` + // is refused first, as it is otherwise. + let kind = super::paint::tool_gradient_kind(s, p, cmd)?; + if super::paint::for_tool(s, p, kind) { super::appearance::aligned(p, cmd)?; super::appearance::targets_contents(p)?; - return Err(bad(cmd, BUCKET_NOT_FREEFORM)); + let none = tool_no_points(s, kind).unwrap_or(NOT_FREEFORM); + return Err(bad(cmd, format!("{none} (give ids, id or item to edit an object's)"))); } let item = item_target(s, p, cmd)?; let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?; @@ -347,7 +358,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result { Some(Value::Null) => None, Some(v) => { let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`index` must be a whole number or null"))?; - let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, no_proxy_freeform(s)))?; + let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, no_proxy_freeform(s, !s.fill_active)))?; check_index(&f, i).map_err(|e| bad(C, e))?; Some(i) } @@ -359,7 +370,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result { fn get(s: &mut Session, p: &Value) -> Result { const C: &str = "paint.freeform.get"; let stroke = switch_or(p, "stroke", !s.fill_active, C)?; - let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, no_proxy_freeform(s)))?; + let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, no_proxy_freeform(s, stroke)))?; let selected = if stroke != s.fill_active { s.selected_freeform_point().filter(|i| *i < f.points.len()) } else { None }; let mut v = vectorcraft_tools::params::freeform_json(&f); v["selected"] = json!(selected); diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 8cf1091492..8dacd8160f 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, the Shape Builder's fill, 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, or for a fill the Shape Builder, 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 tool paints with)", has_doc, edit_gradient ), @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Select Gradient Stop", [], None, - "{index: stop index (0 = the start) | null to clear} select a stop of the gradient behind the active proxy (the first selected object's, else the default paint; the default paint's while the Live Paint Bucket is the active tool): the stop the Gradient tool's annotator, the Gradient and Color panels and Delete/arrow keys act on; refused while an object of a symbol instance's art is selected, except while the Live Paint Bucket is the active tool → {index}", + "{index: stop index (0 = the start) | null to clear} select a stop of the gradient behind the active proxy (the first selected object's, else the default paint; the default paint's while the Live Paint Bucket, or with the Fill proxy in front the Shape Builder, is the active tool): the stop the Gradient tool's annotator, the Gradient and Color panels and Delete/arrow keys act on; refused while an object of a symbol instance's art is selected, except while the proxy in front shows the default paint that way → {index}", always, select_stop ), @@ -61,9 +61,9 @@ pub(crate) fn active_gradient(s: &Session) -> Option { fn select_stop(s: &mut Session, p: &Value) -> Result { const C: &str = "gradient.selectStop"; // No document is needed for the default paint's gradient, so this does not use `refuse_symbol_part`. - // While the Live Paint Bucket is active the proxies show the default paint, whose stops can be - // selected with a part picked. - if !s.bucket_paints() && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) { + // While the Live Paint Bucket is active the proxies show the default paint (the Shape Builder's + // Fill proxy does too), whose stops can be selected with a part picked. + if !s.tool_paints(!s.fill_active) && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) { return Err(super::brushsym::part_only()); } let index = match p.get("index") { @@ -84,10 +84,10 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { /// Whose gradient a selected stop belongs to: the active document, its first selected object /// (None: the default paint), whether a part of a symbol instance's art is picked, the proxy in -/// front, the Appearance panel's active item and whether the Live Paint Bucket is the active tool -/// (its proxies show the default paint). Selecting other art, picking a part of the instance, -/// toggling the proxy, picking another item or choosing the bucket or leaving it leaves no stop -/// selected. +/// front, the Appearance panel's active item and the tool the proxy in front shows the default +/// paint for (the Live Paint Bucket, or the Shape Builder's Fill proxy). Selecting other art, +/// picking a part of the instance, toggling the proxy, picking another item or choosing such a +/// tool or leaving it leaves no stop selected. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct StopOwner { doc: Option, @@ -98,7 +98,8 @@ pub(crate) struct StopOwner { part: bool, fill: bool, item: Option, - bucket: bool, + /// The tool whose color the proxy in front stood for ([`Session::painting_tool`]). + painter: Option<&'static str>, } impl StopOwner { @@ -111,19 +112,24 @@ impl StopOwner { part: st.is_some_and(|d| d.selection.symbol_part.is_some()), fill: s.fill_active, item: s.appearance_item(), - bucket: s.bucket_paints(), + painter: s.painting_tool(!s.fill_active), } } + + /// The tool whose gradient the stop is on; None for the selection's paint. + pub(crate) fn painter(&self) -> Option<&'static str> { + self.painter + } } impl Session { /// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not - /// while the Live Paint Bucket is active or when nothing it can paint is selected (a Live Paint group stands - /// only for its faces in a fill edit and its edges in a stroke edit): it then edits no object and takes no - /// `aspect`. + /// while the active tool paints with the chosen fill (or stroke: [`Session::tool_paints`]) or when nothing it + /// can paint is selected (a Live Paint group stands only for its faces in a fill edit and its edges in a stroke + /// edit): it then edits no object and takes no `aspect`. pub fn gradient_edit_has_objects(&self, stroke: bool) -> bool { let p = json!({ "stroke": stroke }); - !super::paint::for_bucket(self, &p) + !super::paint::for_tool(self, &p, stroke) && item_target(self, &p, "paint.editGradient") .is_ok_and(|item| item.of_kind(self, !stroke).targets_for(self, &p, !stroke).is_ok_and(|ids| !ids.is_empty())) } @@ -526,9 +532,10 @@ fn apply_gradient_edit_in_model( if let Some(b) = bounds { gp.seed_freeform(b, if switched { inside } else { &|_| true }); } + // Without points (the default gradient's, placed on no object yet) the stops are the colors. if recolor && !switched - && let Some(f) = &mut gp.freeform + && let Some(f) = gp.freeform.as_mut().filter(|f| !f.points.is_empty()) { f.recolor(&gp.gradient); gp.gradient.stops = f.stops(); @@ -546,9 +553,10 @@ fn apply_gradient_edit_in_model( fn edit_gradient(s: &mut Session, p: &Value) -> Result { const C: &str = "paint.editGradient"; - // While the Live Paint Bucket is active, the gradient it paints with changes; the selection keeps its own. - let bucket = super::paint::bucket_color_params(s, p, C)?; - let p = bucket.as_ref().unwrap_or(p); + // While the active tool paints with the chosen fill or stroke, the gradient it paints with changes; the + // selection keeps its own. + let for_tool = super::paint::tool_gradient_params(s, p, C)?; + let p = for_tool.as_ref().unwrap_or(p); let item = item_target(s, p, C)?; let stroke = edits_stroke(s, p, item, !s.fill_active, C)?; check_switches(p, &["reverse", "dither"], C)?; @@ -649,7 +657,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { })?; if let Some(m) = mode && !selected - && (bucket.is_some() || p.get("ids").is_none()) + && (for_tool.is_some() || p.get("ids").is_none()) && let Some(st) = s.new_art_stroke_mut() { st.gradient_mode = m; diff --git a/crates/engine/src/cmd/gradpresets.rs b/crates/engine/src/cmd/gradpresets.rs index c8eaa07135..0a123f239b 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?, 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, or for a fill the Shape Builder, 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)}", has_doc, apply ), @@ -207,10 +207,10 @@ fn apply(s: &mut Session, p: &Value) -> Result { const C: &str = "gradient.presets.apply"; let name = name_param(p, C)?; let preset = s.gradient_preset(name).ok_or_else(|| bad(C, format!("no gradient preset `{name}` (see gradient.presets.list)")))?; - // While the Live Paint Bucket is active, the gradient it paints with changes, chosen by the - // active proxy rather than the selection's Appearance row (as paint.editGradient chooses). - let bucket = super::paint::bucket_color_params(s, p, C)?; - let p = bucket.as_ref().unwrap_or(p); + // While the active tool paints with the chosen fill or stroke, the gradient it paints with + // changes (as paint.editGradient chooses). + let for_tool = super::paint::tool_gradient_params(s, p, C)?; + let p = for_tool.as_ref().unwrap_or(p); let stroke = edits_stroke(s, p, item_target(s, p, C)?, !s.fill_active, C)?; let g = &preset.gradient; let mut edit = p.clone(); diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index a42088e7e3..c4578f76f1 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -208,15 +208,30 @@ 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. + /// While the Shape Builder is active, the fill it paints with stays ([`Session::tool_paints`]). pub(crate) fn inherit_new_art(&mut self) { - if self.prefs.new_art_basic || self.bucket_paints() { + let (fill, stroke) = (self.tool_paints(false), self.tool_paints(true)); + if self.prefs.new_art_basic || (fill && stroke) { 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); + let kept_fill = fill.then(|| self.paint.fill.clone()); + let kept_stroke = stroke.then(|| (self.paint.stroke.clone(), self.paint.stroke_width)); self.take_new_art(ap, opacity, blend, style, true); + let p = &mut self.paint; + // New art whose kept paint differs from the selection's is not linked to its graphic style. + if kept_fill.as_ref().is_some_and(|f| *f != p.fill) || kept_stroke.as_ref().is_some_and(|(s, w)| *s != p.stroke || *w != p.stroke_width) { + p.style = None; + } + if let Some(f) = kept_fill { + p.fill = f; + } + if let Some((s, w)) = kept_stroke { + (p.stroke, p.stroke_width) = (s, w); + } } /// After a command changed the selection, with New Art Has Basic Appearance on: the fill and @@ -240,13 +255,14 @@ impl Session { let (fill, stroke) = self.proxy_paints(); let weight_mixed = self.active().is_some_and(|st| st.stroke_mixed().weight); let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width); - if !fill_mixed { + // A proxy that shows the color the active tool paints with (the Shape Builder's fill) keeps it. + if !fill_mixed && !self.tool_paints(false) { self.paint.fill = unplaced(&fill); } - if !stroke_mixed { + if !stroke_mixed && !self.tool_paints(true) { self.paint.stroke = unplaced(&stroke); } - if let Some(width) = weight { + if let Some(width) = weight.filter(|_| !self.tool_paints(true)) { self.paint.stroke_width = width; } } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 6666a1d7a3..11f58b96e3 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -20,6 +20,21 @@ use crate::{DocState, EngineError}; /// object in particular is the color it paints with ([`apply_paint`]). pub(crate) const LIVE_PAINT_BUCKET: &str = "livePaintBucket"; +/// The Shape Builder's tool id. While it is active, a fill chosen for no object in particular is +/// the current fill only, which merges fill with when Pick Color From is Color Swatches; a stroke +/// chosen then still paints the selection. +const SHAPE_BUILDER: &str = "shapeBuilder"; + +/// Tool `id`'s id when it paints with the fill (or the stroke, `stroke`) chosen while it is +/// active: the Live Paint Bucket with both, the Shape Builder with the fill. +pub(crate) fn painting_tool_of(id: &str, stroke: bool) -> Option<&'static str> { + match id { + LIVE_PAINT_BUCKET => Some(LIVE_PAINT_BUCKET), + SHAPE_BUILDER if !stroke => Some(SHAPE_BUILDER), + _ => None, + } +} + pub fn specs() -> Vec { vec![ cmd!( @@ -27,7 +42,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?, 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 or the Shape Builder 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 fill the Shape Builder's merges take with Pick Color From Color Swatches) 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) ), @@ -36,7 +51,7 @@ pub fn specs() -> Vec { "Stroke", [], None, - "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; 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, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke (while the Shape Builder is the active tool, the selection still takes the stroke); without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; 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", has_doc, |s, p| { set_paint(s, p, false) } ), @@ -45,7 +60,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?} 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 or the Shape Builder is the active tool and no ids or id are given (a null one counts as none), only the defaults change (with the Shape Builder, the default fill takes the stroke the Stroke proxy shows, the selection's)", has_doc, swap ), @@ -54,7 +69,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?} 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 or the Shape Builder is the active tool and no ids or id are given (a null one counts as none), only the defaults change", has_doc, default_paint ), @@ -75,7 +90,7 @@ 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}", + "{} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool, only the default changes) → {objects}", has_doc, |s, _| { let f = s.fill_active; @@ -102,7 +117,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?, 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, or for a fill the Shape Builder, 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}", has_doc, |s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert) ), @@ -111,7 +126,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?, 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, or for a fill the Shape Builder, 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}", has_doc, |s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model()) ), @@ -120,7 +135,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?, 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, or for a fill the Shape Builder, 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)", has_doc, |s, p| { let paint = Paint::solid(s.last_solid); @@ -132,7 +147,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?, 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, or for a fill the Shape Builder, 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)", has_doc, |s, p| { let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone()))); @@ -203,11 +218,11 @@ impl Session { /// The object whose fill (or stroke) the proxy shows, with the Appearance panel's active item /// when it stands for it (see [`Session::proxy_paints`]); None: the defaults for new art. With /// an object of a dynamic symbol instance selected ([`DocState::selected_symbol_part`]), that - /// object as the instance draws it. None while the Live Paint Bucket is the active tool (or - /// another tool works for it, [`Session::bucket_paints`]): the proxies show the colors it - /// paints with. + /// object as the instance draws it. None while the active tool paints with the chosen fill (or + /// stroke), or another tool works for it ([`Session::tool_paints`]): the proxy shows the color + /// it paints with. pub(crate) fn proxy_source(&self, stroke: bool) -> Option<(Cow<'_, Node>, Option)> { - if self.bucket_paints() { + if self.tool_paints(stroke) { return None; } let st = self.active()?; @@ -373,25 +388,40 @@ impl DocState { } } -/// Is `t` the Live Paint Bucket, or a tool armed to switch back to it after its pick? -fn works_for_bucket(t: &dyn vectorcraft_tools::Tool) -> bool { - t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET) +/// The id of tool `t`, or of the tool its armed pick switches back to, when that tool paints with +/// the chosen fill or stroke ([`painting_tool_of`]). +fn painter_of(t: &dyn vectorcraft_tools::Tool) -> Option<&'static str> { + let of = |id: &str| painting_tool_of(id, false).or_else(|| painting_tool_of(id, true)); + of(t.id()).or_else(|| t.returns_to().and_then(of)) } impl Session { - /// Did the Live Paint Bucket, or the Eyedropper armed for it, lend the active tool (a Cmd+click)? - pub(crate) fn lent_by_bucket(&self) -> bool { - self.lender.as_deref().is_some_and(works_for_bucket) + /// The tool that lent the active tool (a Cmd+click) when it paints with the chosen colors, or + /// the Eyedropper armed for such a tool did ([`painter_of`]). + pub(crate) fn lent_by_painter(&self) -> Option<&'static str> { + self.lender.as_deref().and_then(painter_of) } - /// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the - /// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while - /// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a - /// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the - /// sample its click takes before it switches back to the bucket. - pub fn bucket_paints(&self) -> bool { - // A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it. - self.back_to_bucket || works_for_bucket(self.tool.as_ref()) || self.lent_by_bucket() + /// Do the fill proxy (the stroke proxy, with `stroke`), and the fill (stroke) commands that + /// name no objects, stand for the color the active tool paints with ([`painting_tool_of`]: the + /// Live Paint Bucket's fill and stroke, the Shape Builder's fill)? They do while such a tool is + /// active, while a Cmd+click with it uses the Selection tool, and while the Eyedropper samples + /// into a stop of its gradient for the Gradient panel's eyedropper, up to and including the + /// sample its click takes before it switches back to that tool. + pub fn tool_paints(&self, stroke: bool) -> bool { + self.painting_tool(stroke).is_some() + } + + /// The id of the tool whose fill (or stroke, `stroke`) the proxy stands for + /// ([`Session::tool_paints`]); None when it stands for the selection's. + pub(crate) fn painting_tool(&self, stroke: bool) -> Option<&'static str> { + let of = + |t: &dyn vectorcraft_tools::Tool| painting_tool_of(t.id(), stroke).or_else(|| t.returns_to().and_then(|id| painting_tool_of(id, stroke))); + // A Cmd+click lends the Selection tool to such a tool, or to the Eyedropper armed for it. + self.back_to_painter + .and_then(|id| painting_tool_of(id, stroke)) + .or_else(|| of(self.tool.as_ref())) + .or_else(|| self.lender.as_deref().and_then(of)) } /// The tool the active tool's armed one-shot pick switches back to after its click @@ -402,12 +432,14 @@ impl Session { /// [`DocState::proxy_mixed`] of the active document for the Appearance panel's active item. /// A gradient mesh with points picked ([`Session::fill_mesh_points`]) counts with their colors. - /// Neither is mixed while the Live Paint Bucket is the active tool ([`Session::proxy_source`]). + /// A proxy that stands for the color the active tool paints with ([`Session::tool_paints`]) is + /// not mixed ([`Session::proxy_source`]). pub fn proxy_mixed(&self) -> (bool, bool) { - if self.bucket_paints() { + if self.tool_paints(false) && self.tool_paints(true) { return (false, false); } - self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points())) + let (fill, stroke) = self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points())); + (fill && !self.tool_paints(false), stroke && !self.tool_paints(true)) } } @@ -553,8 +585,8 @@ fn apply_to_proxy(s: &mut Session, p: &Value, paint: Paint, cmd: &str) -> Result /// 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 { let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; - let bucket = bucket_color_params(s, p, cmd)?; - let p = bucket.as_ref().unwrap_or(p); + let for_tool = tool_color_params(s, p, cmd, !fill)?; + let p = for_tool.as_ref().unwrap_or(p); let focus = switch_or(p, "focus", true, cmd)?; let span = spans_targets(p, &paint).map_err(|e| bad(cmd, e))?; // Characters selected with the Type tool take the paint, not the whole type object (#1063). @@ -759,19 +791,20 @@ 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 the active tool paint with the chosen fill (or stroke, `stroke`: [`Session::tool_paints`], +/// the Live Paint Bucket's fill and stroke, the Shape Builder's fill) while `p` names no `ids`, +/// `id` or `item`? A fill, stroke or stroke weight of that kind chosen then is what the tool +/// paints with, so it goes to the defaults and the selection keeps its paint. +pub(crate) fn for_tool(s: &Session, p: &Value, stroke: bool) -> 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() + s.tool_paints(stroke) && ["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> { - if !for_bucket(s, p) { +/// `p` with `ids: []` when [`for_tool`] for the fill (or stroke, `stroke`): the paint goes to the +/// defaults only. None otherwise. A bad `target` or `aligned` is refused first, as it is when the +/// selection takes the paint. +pub(crate) fn tool_color_params(s: &Session, p: &Value, cmd: &str, stroke: bool) -> Result> { + if !for_tool(s, p, stroke) { return Ok(None); } super::appearance::aligned(p, cmd)?; @@ -781,6 +814,39 @@ pub(crate) fn bucket_color_params(s: &Session, p: &Value, cmd: &str) -> Result Result { + check_switches(p, &["stroke"], cmd)?; + // A tool that paints with both kinds (the Live Paint Bucket), or with neither, needs no kind. + Ok(if s.tool_paints(false) == s.tool_paints(true) || p.get("stroke").is_some_and(Value::is_boolean) { + p.get("stroke").and_then(Value::as_bool).unwrap_or(!s.fill_active) + } else if s.tool_paints(!s.fill_active) { + !s.fill_active + } else { + // A null `ids` or `id` names no target, as `for_tool` reads it. + let mut q = p.clone(); + if let Some(o) = q.as_object_mut() { + o.retain(|k, v| !(matches!(k.as_str(), "ids" | "id") && v.is_null())); + } + super::appearance::edits_stroke(s, &q, item_target(s, &q, cmd)?, !s.fill_active, cmd)? + }) +} + +/// [`tool_color_params`] for `paint.editGradient` or `gradient.presets.apply` (`cmd`), for the kind +/// [`tool_gradient_kind`] gives. The params name that kind as their `stroke` when `p` gives none, +/// since the selection's Appearance row no longer picks it. +pub(crate) fn tool_gradient_params(s: &Session, p: &Value, cmd: &str) -> Result> { + let stroke = tool_gradient_kind(s, p, cmd)?; + Ok(tool_color_params(s, p, cmd, stroke)?.map(|mut v| { + if p.get("stroke").is_none_or(Value::is_null) { + v["stroke"] = json!(stroke); + } + v + })) +} + /// 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 @@ -1194,8 +1260,15 @@ fn shared_paint(d: &Document, parts: &[NodeId], fill: bool) -> Option { } fn swap(s: &mut Session, p: &Value) -> Result { - let bucket = bucket_color_params(s, p, "paint.swap")?; - let p = bucket.as_ref().unwrap_or(p); + // The swap changes a fill, so it goes to the defaults only while the active tool paints with the chosen fill. + let for_tool = tool_color_params(s, p, "paint.swap", false)?; + let p = for_tool.as_ref().unwrap_or(p); + // A tool that paints with the fill only (the Shape Builder): the Stroke proxy shows the + // selection's stroke, which the current fill takes unless the proxy shows mixed strokes. With + // nothing selected it shows the stroke for new art, which the swap moves as it is. + let shown_stroke = (for_tool.is_some() && !s.proxy_mixed().1) + .then(|| s.proxy_source(true).map(|(n, item)| super::gradient::unplaced(&proxy_paint(&n, true, item)))) + .flatten(); let targets = paint_targets(s, p)?; let given = !targets.is_empty(); // A whole Live Paint group: its faces take the stroke its edges share and its edges the fill its faces share. @@ -1259,6 +1332,9 @@ fn swap(s: &mut Session, p: &Value) -> Result { s.paint.stroke_width = 1.0; } std::mem::swap(&mut s.paint.fill, &mut s.paint.stroke); + if let Some(stroke) = shown_stroke { + s.paint.fill = stroke; + } ok() } @@ -1266,8 +1342,9 @@ fn swap(s: &mut Session, p: &Value) -> Result { const LIVE_PAINT_DEFAULT_WEIGHT: f64 = 0.5; fn default_paint(s: &mut Session, p: &Value) -> Result { - let bucket = bucket_color_params(s, p, "paint.default")?; - let p = bucket.as_ref().unwrap_or(p); + // As with paint.swap, the new fill decides whether only the defaults change. + let for_tool = tool_color_params(s, p, "paint.default", false)?; + let p = for_tool.as_ref().unwrap_or(p); let targets = paint_targets(s, p)?; let given = !targets.is_empty(); // A whole Live Paint group: its faces lose their fill and its edges take a black 0.5 pt stroke. @@ -1347,9 +1424,9 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { /// default when there are none) and remember the first target's new paint. The Appearance panel's /// active item of the proxy's kind is recoloured in each selected object's own stack instead. fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result { - let bucket = bucket_color_params(s, p, cmd)?; - let p = bucket.as_ref().unwrap_or(p); let stroke = stroke_param(s, p, cmd)?; + let for_tool = tool_color_params(s, p, cmd, stroke)?; + let p = for_tool.as_ref().unwrap_or(p); // An object of a dynamic symbol instance's art selected with Direct Selection: the solid color // it shows is recolored for this instance only. A gradient or pattern is refused, and so is type // whose characters differ in that paint, since one change holds one paint. diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index cb5d1fd374..f32385d07e 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -241,7 +241,7 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result { let change = StrokeChange::parse(p, C)?; // The stroke the Live Paint Bucket paints with changes; the selection keeps its own, and its // active Appearance row is not a target. - let bucket_p = super::paint::bucket_color_params(s, p, C)?; + let bucket_p = super::paint::tool_color_params(s, p, C, true)?; let bucket = bucket_p.is_some(); let p = bucket_p.as_ref().unwrap_or(p); let item = item_target(s, p, C)?.of_kind(s, false); @@ -397,7 +397,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result { let unit = s.stroke_unit(); // The weight the Live Paint Bucket paints with changes; the selection keeps its own, and its // active Appearance row is not a target. - let bucket_p = super::paint::bucket_color_params(s, p, c)?; + let bucket_p = super::paint::tool_color_params(s, p, c, true)?; let bucket = bucket_p.is_some(); let p = bucket_p.as_ref().unwrap_or(p); let item = item_target(s, p, c)?.of_kind(s, false); @@ -450,7 +450,7 @@ impl Session { /// selection's stroke. pub fn shown_stroke(&self) -> Option { let st = self.active()?; - if self.bucket_paints() { + if self.tool_paints(true) { return Some(self.new_art_stroke()); } if let Some(part) = st.selected_symbol_part() { @@ -619,7 +619,7 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result { } // As stroke.set: the stroke the Live Paint Bucket paints with changes; the selection keeps its own. // A brush still goes to the selection. - let bucket_p = if brush.is_none() { super::paint::bucket_color_params(s, p, C)? } else { None }; + let bucket_p = if brush.is_none() { super::paint::tool_color_params(s, p, C, true)? } else { None }; let bucket = bucket_p.is_some(); let p = bucket_p.as_ref().unwrap_or(p); let item = item_target(s, p, C)?.of_kind(s, false); diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index 006f39ac19..94655acb2e 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); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); 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?, 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, or for a fill the Shape Builder, 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); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", has_doc, sample_color ), diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 06cc86859e..5f5dd21aba 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -15,6 +15,10 @@ pub struct Interaction { /// Conversion of new-art paints waits until a color-mode preview is accepted. pub(crate) deferred_color_mode: Option, pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, + /// A preview ran while the active tool painted with the chosen fill or stroke + /// ([`crate::Session::tool_paints`]): the next preview and a cancel put back the new-art paints + /// from before the interaction, whichever tool is active then. + pub(crate) tool_paints: bool, /// Per-document state restored on cancel (current layer, highlighted Layers panel rows, /// isolation). pub active_layer: Option, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68067dc697..87cdc6dbef 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -74,11 +74,16 @@ pub struct Session { /// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes /// back as it was at the release ([`Session::pointer`]). pub(crate) lender: Option>, - /// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the - /// Eyedropper's sample into a stop of the bucket's gradient), and while a tool the bucket lent - /// is deactivated as it goes back: their paint commands change the colors the bucket paints - /// with ([`Session::bucket_paints`]). - pub(crate) back_to_bucket: bool, + /// While tool actions that end by switching back to a tool that paints with the chosen colors + /// are applied (the Eyedropper's sample into a stop of the Live Paint Bucket's gradient), and + /// while a tool such a tool lent is deactivated as it goes back, that tool's id: their paint + /// commands change the colors it paints with ([`Session::tool_paints`]). + pub(crate) back_to_painter: Option<&'static str>, + /// Whose gradient the stop was on when the Eyedropper was last armed to sample into one + /// (`tool.setOption {stop}`), when it was the gradient a tool paints with + /// ([`Session::painting_tool`]); None for a stop of the selection's paint. A pick armed for + /// such a stop samples only into a stop selected on that gradient, and otherwise ends. + pub(crate) stop_pick: Option, /// Pointer and key input that came while the tool computed an edit on another thread, each with /// its number and view, made in order once the edit is applied. held_input: std::collections::VecDeque<(u64, tooling::HeldInput, ViewInfo)>, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1685adc40f..2ed30c1386 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -59,7 +59,8 @@ impl Session { histories_seen: None, tool: vectorcraft_tools::create("selection"), lender: None, - back_to_bucket: false, + back_to_painter: None, + stop_pick: None, held_input: Default::default(), input_count: 0, edit_started_by: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index e2ba1715b9..73cec0ba8d 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -303,6 +303,7 @@ impl Session { paint, preview_paint: None, color_mode_paints: None, + tool_paints: false, deferred_color_mode: None, active_layer: st.active_layer, layer_rows: st.layer_rows.clone(), @@ -321,9 +322,11 @@ impl Session { if self.script_running() { 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. - let bucket = self.bucket_paints(); + // While the active tool paints with the chosen fill or stroke (the Live Paint Bucket, the + // Shape Builder), paint previews of that kind change only the colors it paints with, so each + // preview starts from the colors the interaction began with, as the document starts from + // its snapshot. + let tool_paints = self.tool_paints(false) || self.tool_paints(true); let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; @@ -337,7 +340,8 @@ 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. - let restore_paint = bucket + it.tool_paints |= tool_paints; + let restore_paint = it.tool_paints || cmd == "command.batch" || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some(); @@ -484,13 +488,15 @@ impl Session { self.clear_deferred_overlay_cache(); 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. - let bucket = self.bucket_paints(); + // A color previewed while the active tool painted with the chosen fill or stroke is the + // tool's color, which the cancel puts back as well, also after another tool was chosen. + let tool_paints = self.tool_paints(false) || self.tool_paints(true); 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| { + tool_paints || it.tool_paints || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some() + }) .map(|it| it.paint.clone()) { self.paint = paint; diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 32a9db4b21..d79730b57b 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1899,6 +1899,303 @@ fn shape_builder_arrow_keys_pass_swatches_of_the_same_color() { assert_eq!(s.paint.fill, after, "the swatch after Twin B"); } +/// While the Shape Builder is active, with either Pick Color From, a fill chosen without `ids`, +/// `id` or `item` (a swatch, a color, Swap, Default) changes only the current fill: the selected +/// paths keep their fills, no undo step is recorded and the Fill proxy shows the chosen fill. A +/// stroke chosen then still paints the selection, since a merge takes no stroke from it. +#[test] +fn shape_builder_fill_choice_leaves_the_selection_unpainted() { + let fills = |s: &Session, ids: [NodeId; 2]| ids.map(|id| node(s, id).appearance.fill_paint()); + for mode in ["artwork", "swatches"] { + let mut s = session(); + let (a, b) = two(&mut s); + s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00"})).unwrap(); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": mode}})).unwrap(); + let before = fills(&s, [a, b]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("paint.setFill", &json!({"swatch": "Leaf"})).unwrap(); + assert_eq!(r["objects"], 0, "{mode}"); + let leaf = s.paint.fill.clone(); + assert_eq!(leaf.color(), Some(Color::from_hex("#00ff00").unwrap()), "{mode}"); + for cmd in ["paint.swap", "paint.swap", "paint.default"] { + s.execute(cmd, &json!({})).unwrap(); + } + s.execute("paint.setFill", &json!({"swatch": "Leaf"})).unwrap(); + assert_eq!(fills(&s, [a, b]), before, "{mode}: the selected paths keep their fills"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{mode}: no undo step"); + assert_eq!(s.proxy_paints().0, leaf, "{mode}: the Fill proxy shows the chosen fill"); + // A stroke goes to the selection, and the Stroke proxy shows the selection's. + let r = s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + assert!(r["objects"].as_u64().unwrap() > 0, "{mode}: {r}"); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + assert_eq!(node(&s, a).appearance.stroke_paint(), blue, "{mode}"); + s.execute("stroke.set", &json!({"weight": 7})).unwrap(); + assert_eq!(node(&s, b).appearance.stroke_at(None).map(|l| l.width), Some(7.0), "{mode}: the selection takes the weight"); + assert_eq!(fills(&s, [a, b]), before, "{mode}"); + } +} + +/// While the Shape Builder is active, Swap Fill and Stroke gives the current fill the stroke the +/// Stroke proxy shows (the selection's), not a stroke for new art that no proxy shows, and the +/// selected path keeps its fill and stroke. With mixed strokes shown, the fill takes the stroke +/// for new art. +#[test] +fn shape_builder_swap_gives_the_fill_the_shown_stroke() { + let mut s = session(); + let (a, b) = two(&mut s); + s.execute("appearance.setNewArtBasic", &json!({"on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + s.paint.stroke = Paint::solid(Color::from_hex("#0000ff").unwrap()); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + assert_eq!(s.proxy_paints().1, green, "the Stroke proxy shows the selection's stroke"); + // No stroke for new art: the old fill becomes a 1 pt stroke for new art, as without the tool. + (s.paint.stroke, s.paint.stroke_width) = (Paint::None, 0.0); + let before = node(&s, a).appearance; + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(s.paint.fill, green, "the current fill takes the stroke the proxy showed"); + assert_eq!(s.paint.stroke_width, 1.0, "the old fill is a stroke that draws"); + assert_eq!(node(&s, a).appearance, before, "the selected path keeps its fill and stroke"); + // The Stroke proxy shows mixed strokes: the current fill takes the stroke for new art. + s.execute("paint.setStroke", &json!({"ids": [b.0], "color": "#ff00ff"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + assert!(s.proxy_mixed().1, "the selection's strokes differ"); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + s.paint.stroke = blue.clone(); + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(s.paint.fill, blue, "no stroke of the selection was shown"); + // With nothing selected, the stroke for new art (a freeform gradient drawn as lines) moves to + // the fill as it is. + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.editGradient", &json!({"stroke": true, "kind": "freeform", "mode": "lines"})).unwrap(); + let stroke = s.paint.stroke.clone(); + assert!(matches!(&stroke, Paint::Gradient(g) if g.freeform.is_some()), "{stroke:?}"); + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(s.paint.fill, stroke, "the stroke for new art, unchanged"); +} + +/// While the Shape Builder is active, the fill chosen for it stays the current fill when the +/// selection changes, with New Art Has Basic Appearance on or off (off, new art still takes the +/// rest of the new selection's appearance), and the freeform point commands refuse the fill's +/// gradient, which lies on no object, instead of editing the selection's. +#[test] +fn shape_builder_fill_stays_across_selections() { + for basic in [false, true] { + let mut s = session(); + let (a, b) = two(&mut s); + s.execute("appearance.setNewArtBasic", &json!({"on": basic})).unwrap(); + // B's own fill is a freeform gradient, whose points the commands could edit. + s.execute("paint.editGradient", &json!({"ids": [b.0], "stroke": false, "kind": "freeform"})).unwrap(); + // B is linked to a graphic style. + s.execute("graphicStyle.new", &json!({"id": b.0, "name": "Bee"})).unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Bee", "ids": [b.0]})).unwrap(); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "freeform", "mode": "lines"})).unwrap(); + // The tool's freeform gradient has no points yet: its stops take the colors given. + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + s.execute("paint.editGradient", &json!({"stroke": false, "stops": stops})).unwrap(); + let Paint::Gradient(g) = &s.paint.fill else { panic!("the tool's fill is not a gradient") }; + assert_eq!(g.gradient.stops[0].color, Color::from_hex("#ff0000").unwrap(), "{basic}: the stop color given"); + let chosen = s.paint.fill.clone(); + assert!(matches!(&chosen, Paint::Gradient(_)), "{basic}"); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + assert_eq!(s.paint.fill, chosen, "basic {basic}: the chosen fill stays"); + assert_eq!(s.paint.inherited, !basic, "basic {basic}: whether new art takes the selection's appearance"); + // New art with the chosen fill does not look like B's style, so it is not linked to it. + assert_eq!(s.paint.style, None, "basic {basic}"); + let before = [a, b].map(|id| node(&s, id)); + let e = s.execute("paint.freeform.setPoint", &json!({"index": 0, "color": "#ff0000"})).unwrap_err().to_string(); + assert!(e.contains("Shape Builder"), "{basic}: {e}"); + assert_eq!([a, b].map(|id| node(&s, id)), before, "basic {basic}: the selection keeps its paint"); + } +} + +/// While the Shape Builder is active with the Fill proxy in front, a gradient preset or edit that +/// names no kind goes to the tool's fill, also while a stroke row of the selection is the +/// Appearance panel's active row; with the Stroke proxy in front, an active fill row still keeps +/// the edit off the selection. +#[test] +fn shape_builder_gradient_edits_follow_the_proxy_in_front() { + let mut s = session(); + let (a, _) = two(&mut s); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let row = |s: &Session, fill: bool| node(s, a).appearance.items.iter().position(|it| it.is_fill() == fill).unwrap(); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + let before = node(&s, a); + s.execute("appearance.setActiveItem", &json!({"index": row(&s, false)})).unwrap(); + s.fill_active = true; + s.execute("gradient.presets.apply", &json!({"name": "vignette"})).unwrap(); + assert!(matches!(s.paint.fill, Paint::Gradient(_)), "the tool's fill takes the preset"); + assert_eq!(node(&s, a).appearance, before.appearance, "the selection keeps its paint"); + s.execute("appearance.setActiveItem", &json!({"index": row(&s, true)})).unwrap(); + s.fill_active = false; + for (kind, ids) in [("diamond", None), ("linear", Some(Value::Null))] { + let tool_fill = s.paint.fill.clone(); + let mut p = json!({ "kind": kind }); + if let Some(ids) = ids { + p["ids"] = ids; + } + s.execute("paint.editGradient", &p).unwrap(); + assert_ne!(s.paint.fill, tool_fill, "{p}: the tool's fill takes the edit"); + assert_eq!(node(&s, a).appearance, before.appearance, "{p}: the selection keeps its paint"); + } + // A freeform stroke on the selection, its row active and the Fill proxy in front: a point + // edit without `stroke` is for the tool's fill, which has no points, and changes nothing. + s.execute("paint.editGradient", &json!({"ids": [a.0], "stroke": true, "kind": "freeform"})).unwrap(); + let stroked = node(&s, a); + s.execute("appearance.setActiveItem", &json!({"index": row(&s, false)})).unwrap(); + s.fill_active = true; + assert!(s.execute("paint.freeform.setPoint", &json!({"index": 0, "color": "#ff0000"})).is_err()); + assert_eq!(node(&s, a).appearance, stroked.appearance, "the selection's stroke keeps its points"); + // A `stroke` that is not a switch is reported as such. + let e = s.execute("paint.freeform.setPoint", &json!({"index": 0, "color": "#ff0000", "stroke": "true"})).unwrap_err(); + assert!(e.to_string().contains("stroke"), "{e}"); +} + +/// A fill previewed while the Shape Builder is active (a Color panel drag) is the tool's fill, +/// which a cancel puts back, also after another tool was chosen during the drag. +#[test] +fn shape_builder_fill_preview_is_put_back_by_a_cancel() { + let mut s = session(); + two(&mut s); + s.execute("appearance.setNewArtBasic", &json!({"on": true})).unwrap(); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + let before = s.paint.fill.clone(); + s.begin_interaction("Color").unwrap(); + s.preview("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + assert_eq!(s.paint.fill.color(), Some(Color::from_hex("#ff00ff").unwrap()), "the preview sets the tool's fill"); + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, before, "the cancel puts the fill back"); +} + +/// With Pick Color From Color Swatches, a merge fills with the fill chosen while the Shape Builder +/// is active, and the Gradient panel's eyedropper samples into a stop of that fill's gradient. +#[test] +fn shape_builder_merge_fills_with_the_chosen_fill() { + let mut s = session(); + let (a, b) = two(&mut s); + s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("shapeBuilder", v).unwrap(); + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "swatches"}})).unwrap(); + let (a0, b0) = (node(&s, a), node(&s, b)); + s.execute("paint.setFill", &json!({"swatch": "Leaf"})).unwrap(); + let leaf = s.paint.fill.clone(); + assert_eq!((node(&s, a), node(&s, b)), (a0, b0), "the selected paths keep their paint"); + // The tool's merge fills with the chosen swatch. + s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 75.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 75.0, 50.0), v).unwrap(); + assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge"); + let d = &s.doc().unwrap().doc; + let fills: Vec = d.children(d.default_layer()).into_iter().flatten().map(|n| n.appearance.fill_paint()).collect(); + assert!(fills.contains(&leaf), "a merged shape filled with the swatch: {fills:?}"); + // A gradient and the Gradient panel's eyedropper sample into a stop of the gradient the tool + // paints with, and the art keeps its paint. + let art = |s: &Session| -> Vec { + let d = &s.doc().unwrap().doc; + d.children(d.default_layer()).into_iter().flatten().map(|n| Node::clone(n)).collect() + }; + let before = art(&s); + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + let Paint::Gradient(g) = &s.paint.fill else { panic!("the tool's fill is not a gradient") }; + assert_eq!(Paint::solid(g.gradient.stops[1].color), leaf, "the sampled stop"); + assert_eq!(art(&s), before, "the art keeps its paint"); + // Armed again, a pick whose stop went away when the Stroke proxy came to the front (the + // selection's stroke), also after the stop was cleared first, ends without copying an + // appearance onto the art. + for clear in [false, true] { + s.select_tool("shapeBuilder", v).unwrap(); + s.fill_active = true; + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + if clear { + s.execute("gradient.selectStop", &json!({"index": null})).unwrap(); + } + s.fill_active = false; + assert_eq!(s.selected_stop(), None); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(art(&s), before, "the art keeps its paint (cleared first: {clear})"); + } + // With the Stroke proxy in front, a stop of the selection's stroke gradient is the selection's, + // and the pick samples into it. + s.execute("paint.editGradient", &json!({"stroke": true, "kind": "linear"})).unwrap(); + assert_ne!(art(&s), before, "the selection takes the stroke gradient"); + s.execute("gradient.selectStop", &json!({"index": 0})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(s.journal.last().unwrap().0, "paint.sampleColor", "the pick samples into the selection's stop"); + // A pick armed for a stop of the tool's fill does not sample into a stop selected since on + // the selection's stroke: it ends. + s.select_tool("shapeBuilder", v).unwrap(); + s.fill_active = true; + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + s.fill_active = false; + let stops = json!([{"offset": 0, "color": "#0000ff"}, {"offset": 1, "color": "#000000"}]); + s.execute("paint.editGradient", &json!({"stroke": true, "stops": stops})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 0})).unwrap(); + let armed = art(&s); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(art(&s), armed, "the selection's stroke keeps its stops"); + s.execute("gradient.selectStop", &json!({"index": null})).unwrap(); + // A pick armed for another tool is not that stop's: with no stop selected, its click copies + // the appearance as usual. + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("selection")); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(s.journal.last().unwrap().0, "appearance.copyFrom"); + // Choosing another tool drops the stop a pick was armed for. + s.select_tool("shapeBuilder", v).unwrap(); + s.fill_active = true; + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + assert!(s.stop_pick.is_some(), "the pick is armed for the tool's stop"); + s.select_tool("selection", v).unwrap(); + assert!(s.stop_pick.is_none(), "another tool was chosen"); + // Armed while the Eyedropper waits for a Cmd-drag it lent the Selection tool to, the pick + // still ends once the Stroke proxy comes to the front. + s.select_tool("shapeBuilder", v).unwrap(); + s.fill_active = true; + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + let lent = s.make_tool("selection"); + s.lender = Some(std::mem::replace(&mut s.tool, lent)); + s.set_tool_options(Some("eyedropper"), json!({"stop": "shapeBuilder"}).as_object().unwrap()); + s.give_back_tool(v).unwrap(); + assert_eq!(s.tool_id(), "eyedropper"); + s.fill_active = false; + let (armed, journal) = (art(&s), s.journal.len()); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(art(&s), armed, "the art keeps its paint (armed during a loan)"); + let ran: Vec<&str> = s.journal.since(journal).iter().map(|j| j.0.as_str()).collect(); + assert!(!ran.contains(&"appearance.copyFrom"), "{ran:?}"); +} + /// The colors of the cursor swatch preview's chips, left to right, and which one is ringed. fn swatch_chips(s: &mut Session, v: ViewInfo) -> Vec<([u8; 4], bool)> { let mut chips: Vec<(f64, [u8; 4], bool)> = s diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index f3d615ac8d..475220cea2 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -196,6 +196,8 @@ impl Session { self.deactivate_tool(view)?; self.keep_tool_settings(); self.tool = self.make_tool(id); + // A pick is armed for a stop after its tool is chosen (`note_stop_pick`). + self.stop_pick = None; if let Some(selection) = text_selection { self.tool.set_option("textSelection", &selection); } @@ -319,7 +321,7 @@ impl Session { /// Pen goes on drawing its path), less the work the gesture ended as a command would: a /// Cmd+click that takes the type being edited out of the selection ends its edit (#3779). pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> { - let lent_by_bucket = self.lent_by_bucket(); + let lent_by_painter = self.lent_by_painter(); let Some(lender) = self.lender.take() else { return Ok(()) }; // The points the lent tool left picked go back to the tool it was lent to when that tool // picks mesh points, none when it unpicked them all (#8090). Group Selection and the @@ -329,12 +331,12 @@ impl Session { .then(|| self.tool.options().get("meshPoints").cloned()) .flatten() .filter(|p| lender.options().get("meshPoints") != Some(p)); - // The lent tool's last actions (a drag it cancels or keeps) still count as the Live Paint - // Bucket's when the bucket lent it ([`Session::bucket_paints`]). - let outer_bucket = self.back_to_bucket; - self.back_to_bucket |= lent_by_bucket; + // The lent tool's last actions (a drag it cancels or keeps) still count as those of the tool + // that lent it when that tool paints with the chosen colors ([`Session::tool_paints`]). + let outer_painter = self.back_to_painter; + self.back_to_painter = self.back_to_painter.or(lent_by_painter); let r = self.deactivate_tool(view); - self.back_to_bucket = outer_bucket; + self.back_to_painter = outer_painter; self.keep_tool_settings(); self.tool = lender; if let Some(points) = mesh_points { @@ -423,6 +425,7 @@ impl Session { let Some(st) = self.active.and_then(|i| self.docs.get(i)) else { return R::default() }; let (unit, stroke_unit) = (self.general_unit(), self.stroke_unit()); let smart_guides = view.smart_guides && !view.pixel_preview; + let (pick_stop, armed_for_tool) = self.pick_stop(); let cx = ToolContext { doc: &st.doc, ruler_origin: st.doc.ruler_origin_for(view.artboard), @@ -448,7 +451,8 @@ impl Session { corner_widgets: view.corner_widgets, shape_widgets: view.shape_widgets, fill_active: self.fill_active, - gradient_stop: self.selected_stop(), + gradient_stop: pick_stop, + tool_paints: self.tool_paints(!self.fill_active) || armed_for_tool, appearance_item: self.appearance_item(), constrain_angle: self.prefs.constrain_angle, keyboard_increment: self.prefs.keyboard_increment, @@ -1359,6 +1363,7 @@ impl Session { let before_press = self.options_before_press_set(); let sets_pressed = self.press_taken_by(self.tool.id()); self.tool.set_option(key, v); + self.note_stop_pick(key, self.tool.id() == "eyedropper"); self.tool_set_since_reset = true; self.keep_tool_settings(); self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed); @@ -1446,9 +1451,35 @@ impl Session { Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store)); } self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed); + // The Eyedropper waiting for a Cmd-drag it lent a selection tool to is armed as the active one. + if (active || lender) && values.contains_key("stop") { + let eyedropper = id.unwrap_or(self.tool.id()) == "eyedropper"; + self.note_stop_pick("stop", eyedropper); + } out } + /// After option `key` of the active tool, or of the tool waiting for a Cmd-drag it lent, is set + /// (`eyedropper`: that tool is the Eyedropper): an Eyedropper armed to sample into a stop of the + /// gradient a tool paints with (`stop`) keeps whose gradient that is ([`Session::stop_pick`]). + fn note_stop_pick(&mut self, key: &str, eyedropper: bool) { + if key == "stop" && eyedropper { + let selected = self.selected_stop().is_some(); + self.stop_pick = self.gradient_stop.map(|(_, owner)| owner).filter(|owner| selected && owner.painter().is_some()); + } + } + + /// The stop an armed Eyedropper pick samples into ([`ToolContext::gradient_stop`]): the + /// selected one, and for a pick armed for a stop of the gradient a tool paints with + /// ([`Session::stop_pick`]) only a stop still selected on that gradient. + fn pick_stop(&self) -> (Option, bool) { + let armed = self.stop_pick.filter(|owner| self.tool.returns_to().is_some_and(|id| owner.painter() == Some(id))); + match armed { + Some(owner) => (self.selected_stop().filter(|_| self.gradient_stop.is_some_and(|(_, o)| o == owner)), true), + None => (self.selected_stop(), false), + } + } + /// The tool that took the press under way: the active tool, or the tool that lent a selection /// tool for it (a Cmd-drag), which the dropped press gives its options back to. fn pressed_tool(&self) -> Option<&dyn Tool> { @@ -1612,10 +1643,16 @@ impl Session { /// Apply tool actions. Errors from previews are reported but keep the interaction alive. pub fn apply_actions(&mut self, acts: Vec) -> Result> { let outer = std::mem::replace(&mut self.in_tool_actions, true); - let outer_bucket = self.back_to_bucket; - // The Eyedropper's sample into a stop of the Live Paint Bucket's gradient, which switches back to the bucket. - self.back_to_bucket |= - self.tool.id() == "eyedropper" && acts.iter().any(|a| matches!(a, Action::SwitchTool(t) if t == crate::cmd::LIVE_PAINT_BUCKET)); + let outer_painter = self.back_to_painter; + // The Eyedropper's sample into a stop of the gradient of a tool that paints with the chosen + // colors (the Live Paint Bucket, the Shape Builder), which switches back to that tool. + if self.tool.id() == "eyedropper" { + let back = acts.iter().find_map(|a| match a { + Action::SwitchTool(t) => crate::cmd::painting_tool_of(t, false).or_else(|| crate::cmd::painting_tool_of(t, true)), + _ => None, + }); + self.back_to_painter = self.back_to_painter.or(back); + } // A preview that settling applied (typing kept as its own step before a drag begins) shows // its warning in the status bar, as the tool's own commit shows its preview's. let r = if !outer && self.depth == 0 { @@ -1625,7 +1662,7 @@ impl Session { self.apply_tool_actions(acts) }; self.in_tool_actions = outer; - self.back_to_bucket = outer_bucket; + self.back_to_painter = outer_painter; if !outer && self.depth == 0 { self.trim_histories(); } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index c8756cefc7..06d7687acf 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -776,6 +776,15 @@ fn set_paint_reports_how_many_objects_it_painted() { assert_eq!(v["objects"], 2, "{v}"); let v = paint(&mut s, 16, json!({"strokeWidth": 2})); assert_eq!(v["objects"], 2, "{v}"); + + // While the Shape Builder is the active tool, the fill goes to new art only and the stroke to + // the selection: the reply names the command that painted nothing. + let r = call(&mut s, 17, "select_tool", json!({"tool": "shapeBuilder"})); + assert_eq!(r["isError"], false, "{r}"); + let v = paint(&mut s, 18, json!({"fill": "#ff00ff", "stroke": "#00ffff"})); + assert_eq!(v["objects"], 2, "{v}"); + assert_eq!(v["unpainted"], json!(["paint.setFill"]), "{v}"); + assert!(v["note"].as_str().is_some_and(|n| n.contains("Shape Builder")), "{v}"); } /// #1003: type made on or in a path takes add_text's `color` too, over the current fill. diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index fcbc9cf708..416bbeb5e3 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -282,7 +282,7 @@ pub fn tool_definitions() -> Vec { tool( "set_paint", "Set paint", - "Set fill, stroke and/or stroke weight on the selection (or `ids`) and as the default for new art. Returns {applied, objects}: `objects` counts the objects painted, as paint.setFill, paint.setStroke and stroke.set report them (the largest of their counts); when it is 0, a `note` says that only the default for new art changed.", + "Set fill, stroke and/or stroke weight on the selection (or `ids`) and as the default for new art. Returns {applied, objects}: `objects` counts the objects painted, as paint.setFill, paint.setStroke and stroke.set report them (the largest of their counts); when it is 0, a `note` says that only the default for new art changed, and when only some of those commands painted no object, `unpainted` lists them with a `note`.", obj( json!({ "fill": paint_schema("Fill"), diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 12c3b24f37..752f72b928 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -183,11 +183,16 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result Result<(Vec>, Map), Str } /// Sets the paint `a` gives on `ids` (default: the selection) and as the default for new art. -/// Returns the paint applied and the most objects one of its edits painted (the `objects` of the -/// `paint.setFill`, `paint.setStroke` and `stroke.set` replies). -pub(super) fn apply_paint(b: &mut dyn Backend, a: &Args, ids: Option) -> Result<(Value, u64), String> { +/// Returns the paint applied, the most objects one of its edits painted (the `objects` of the +/// `paint.setFill`, `paint.setStroke` and `stroke.set` replies) and the commands among them that +/// painted no object. +pub(super) fn apply_paint(b: &mut dyn Backend, a: &Args, ids: Option) -> Result<(Value, u64, Vec<&'static str>), String> { let (steps, applied) = paint_steps(a)?; - let mut objects = 0; + let (mut objects, mut unpainted) = (0, vec![]); for (cmd, mut p) in steps { if let Some(ids) = &ids { p["ids"] = ids.clone(); } let r = exec(b, cmd, p)?; - objects = objects.max(r.get("objects").and_then(Value::as_u64).unwrap_or(0)); + let n = r.get("objects").and_then(Value::as_u64).unwrap_or(0); + if n == 0 { + unpainted.push(cmd); + } + objects = objects.max(n); } - Ok((Value::Object(applied), objects)) + Ok((Value::Object(applied), objects, unpainted)) } /// Checks `draw_path` / `draw_shape`'s `dash`, `cap`, `join`, `opacity`, `name` and `effects` diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 1a37860179..00bb747734 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -228,8 +228,16 @@ pub struct ToolContext<'a> { pub shape_widgets: bool, /// Which paint proxy is in front (true = Fill): the one the Gradient tool edits. pub fill_active: bool, - /// The selected gradient stop (`gradient.selectStop`), marked on the gradient annotator. + /// The selected gradient stop (`gradient.selectStop`), marked on the gradient annotator. For + /// an Eyedropper pick armed for a stop of the gradient a tool paints with, only a stop still + /// selected on that gradient. pub gradient_stop: Option, + /// Is [`Self::paint`]'s paint behind the proxy in front ([`Self::fill_active`]) the color the + /// active tool, or the tool an armed one-shot pick returns to, paints with (the Live Paint + /// Bucket's fill and stroke, the Shape Builder's fill), or was the pick armed for a stop of + /// that tool's paint? A pick armed for such a stop then ends once [`Self::gradient_stop`] no + /// longer names it, also after the stop was cleared or the other proxy came to the front. + pub tool_paints: bool, /// The Appearance panel's active fill/stroke (paint-order index into the first selected /// object's stack); paint tools show and edit that item. pub appearance_item: Option, diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 29bfecd4e9..708f34e0c4 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -671,6 +671,7 @@ pub(crate) mod testutil { shape_widgets: true, fill_active: true, gradient_stop: None, + tool_paints: false, appearance_item: None, constrain_angle: 0.0, keyboard_increment: 1.0, diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index d45dff84ed..5eb1b6d3cd 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -537,14 +537,17 @@ impl Tool for EyedropperTool { self.stop = None; return vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)]; } - // A pick for a stop of the Live Paint Bucket's gradient (the default paint's) ends without - // sampling once that stop is no longer selected (a Cmd-click selected another object) or no - // longer there (another paint was chosen): the click switches back. - let bucket_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke }; - let bucket_stop = cx.gradient_stop.filter(|i| matches!(bucket_paint, Paint::Gradient(g) if *i < g.gradient.stops.len())); - if self.stop.as_deref() == Some("livePaintBucket") && bucket_stop.is_none() { - self.stop = None; - return vec![Action::SwitchTool("livePaintBucket".into())]; + // A pick for a stop of the gradient of a tool that paints with the chosen colors (the + // default paint's: the Live Paint Bucket's, or the Shape Builder's fill) ends + // without sampling once that stop is no longer selected (a Cmd-click selected another + // object) or no longer there (another paint was chosen): the click switches back. + let tool_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke }; + let tool_stop = cx.gradient_stop.filter(|i| matches!(tool_paint, Paint::Gradient(g) if *i < g.gradient.stops.len())); + if cx.tool_paints + && tool_stop.is_none() + && let Some(back) = self.stop.take() + { + return vec![Action::SwitchTool(back)]; } let stop = self.stop.as_ref().zip(cx.gradient_stop); // A plain click on a selected gradient mesh gives the fill color to the point there, else @@ -852,19 +855,23 @@ mod tests { ] ); assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}), "one sample only"); - // Armed for the Live Paint Bucket with its stop no longer selected, a click ends the pick. - cx.gradient_stop = None; - t.set_option("stop", &json!("livePaintBucket")); - let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); - assert_eq!(a, vec![Action::SwitchTool("livePaintBucket".into())]); - assert_eq!(t.returns_to(), None); - // So does a click once the default paint has no such stop (here, a solid fill). - cx.gradient_stop = Some(1); - assert!(!matches!(cx.paint.fill, Paint::Gradient(_))); - t.set_option("stop", &json!("livePaintBucket")); - assert_eq!(t.returns_to(), Some("livePaintBucket")); - let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); - assert_eq!(a, vec![Action::SwitchTool("livePaintBucket".into())]); + // Armed for a tool that paints with the chosen colors (the Live Paint Bucket, or the Shape + // Builder's fill) with its stop no longer selected, a click ends the pick. + cx.tool_paints = true; + for back in ["livePaintBucket", "shapeBuilder"] { + cx.gradient_stop = None; + t.set_option("stop", &json!(back)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); + assert_eq!(a, vec![Action::SwitchTool(back.into())]); + assert_eq!(t.returns_to(), None); + // So does a click once the default paint has no such stop (here, a solid fill). + cx.gradient_stop = Some(1); + assert!(!matches!(cx.paint.fill, Paint::Gradient(_))); + t.set_option("stop", &json!(back)); + assert_eq!(t.returns_to(), Some(back)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); + assert_eq!(a, vec![Action::SwitchTool(back.into())]); + } // Neither a Key Color pick nor an Image Trace ignored-color pick is a gradient stop's. t.set_option("brushKeyColor", &json!(true)); t.set_option("stop", &json!("livePaintBucket")); diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 63dcfa916b..c02ed63f12 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -14,7 +14,7 @@ use egui::{Sense, vec2}; use serde_json::{Value, json}; use vectorcraft_color::gradient::move_stop; -use vectorcraft_color::{Color, FreeformPoint, GradientKind, GradientStop, Paint}; +use vectorcraft_color::{Color, FreeformPoint, GradientStop, Paint}; use vectorcraft_geom::Point; use vectorcraft_tools::params::color_json; @@ -22,7 +22,7 @@ use super::{DialogResult, DialogSpec}; use crate::VectorcraftApp; use crate::canvas::Xf; use crate::panels::active_paint; -use crate::panels::gradient::{edit_point, set_stops, shown_points}; +use crate::panels::gradient::{edit_point, edits_points, set_stops, shown_points}; use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets::{self, Live}; @@ -56,7 +56,7 @@ impl Target { fn selected(app: &VectorcraftApp) -> Option { let Paint::Gradient(g) = active_paint(app) else { return None }; - if g.gradient.kind == GradientKind::Freeform { + if edits_points(app, &g) { let f = shown_points(&g); let i = app.session.selected_freeform_point().filter(|i| *i < f.points.len())?; return Some(Target::Point(f.points[i], i)); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 6c4d7860e7..2e4d62b822 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -412,10 +412,11 @@ pub(crate) fn current_paints(app: &VectorcraftApp) -> (Paint, Paint) { /// document revision, Appearance panel item and picked gradient mesh points (picking points /// changes no revision). pub(crate) fn mixed_paints(app: &VectorcraftApp, ctx: &egui::Context) -> (bool, bool) { - type Key = (u64, u64, Option, Vec<(NodeId, Vec)>, bool); + type Key = (u64, u64, Option, Vec<(NodeId, Vec)>, (bool, bool)); let Some(st) = app.session.active() else { return (false, false) }; - // Whether the proxies show the Live Paint Bucket's colors too. - let key: Key = (st.uid, st.revision, app.session.appearance_item(), app.session.fill_mesh_points(), app.session.bucket_paints()); + // Whether the proxies show the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) too. + let tool = (app.session.tool_paints(false), app.session.tool_paints(true)); + let key: Key = (st.uid, st.revision, app.session.appearance_item(), app.session.fill_mesh_points(), tool); match pstate::>(ctx, "proxy-mixed") { Some((k, mixed)) if k == key => mixed, _ => { @@ -444,7 +445,7 @@ pub(crate) fn stroke_mixed(app: &VectorcraftApp, ctx: &egui::Context) -> StrokeM if character::text_editing(app).is_some() { return StrokeMixed { can_align: true, ..Default::default() }; } - if app.session.bucket_paints() { + if app.session.tool_paints(true) { return StrokeMixed { can_align: true, ..Default::default() }; } let Some(st) = app.session.active() else { return StrokeMixed::default() }; diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 42b19252bd..7ece73dbfb 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -23,7 +23,7 @@ use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::{Value, json}; use vectorcraft_color::cms; -use vectorcraft_color::{Color, GradientKind, Paint}; +use vectorcraft_color::{Color, Paint}; use super::{active_paint, color_json, live_run, pstate, set_pstate}; use crate::theme::Tokens; @@ -453,7 +453,9 @@ fn target_with(app: &VectorcraftApp, mixed: bool) -> Target { } let p = active_paint(app); match &p { - Paint::Gradient(g) if g.gradient.kind == GradientKind::Freeform => { + // A freeform gradient on art: its points. The one the active tool paints with has no points + // to edit (`paint.freeform.setPoint` refuses it), so its stops are edited below. + Paint::Gradient(g) if super::gradient::edits_points(app, g) => { // Like stops: without a selected point, the first. let f = super::gradient::shown_points(g); let index = app.session.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0); diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 945c18ea0d..15b3e41e81 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -100,7 +100,7 @@ pub(crate) fn dropped_link(app: &VectorcraftApp, params: &Value) -> Option<(Stri /// is selected. pub(crate) fn recolor_selected(app: &mut VectorcraftApp, c: Color, params: &Value) -> bool { let Paint::Gradient(g) = active_paint(app) else { return false }; - if g.gradient.kind == GradientKind::Freeform { + if edits_points(app, &g) { let Some(i) = app.session.selected_freeform_point().filter(|i| *i < shown_points(&g).points.len()) else { return false }; edit_point(app, "paint.freeform.setPoint", json!({ "index": i, "color": super::color_json(&c), "keepModel": true })); return true; @@ -163,6 +163,13 @@ pub(crate) fn draw_radios(app: &mut VectorcraftApp, ui: &mut Ui) { }); } +/// Do the panel, the stop popover and swatch drops edit the points of `g`, the gradient behind +/// the active proxy? Only for a freeform gradient on art: the one the active tool paints with +/// lies on no object, so its stops stand for its colors, as in the Color panel. +pub(crate) fn edits_points(app: &VectorcraftApp, g: &GradientPaint) -> bool { + g.gradient.kind == GradientKind::Freeform && !app.session.tool_paints(!app.session.fill_active) +} + /// The gradient behind the active proxy. fn current(app: &VectorcraftApp) -> Option { match active_paint(app) { @@ -281,8 +288,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); }); let freeform = is_grad && kind == GradientKind::Freeform; + let points = is_grad && edits_points(app, &g); if hidden { - if !freeform { + if !points { ui.add_space(6.0); ramp_row(app, ui, &g.gradient, is_grad); } @@ -310,10 +318,20 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); // Along and across, the gradient follows the path: its angle and aspect ratio don't apply. let placed = stroke_mode.is_none_or(|m| m == StrokeGradientMode::Within); - if freeform { + if points { freeform_section(app, ui, &g); return; } + // A freeform gradient the active tool paints with: the proxy and the Draw toggle, its stops and + // their fields. + if freeform { + draw_row(app, ui, shown_points(&g).mode); + ui.add_space(6.0); + ramp_row(app, ui, &g.gradient, is_grad); + ui.add_space(4.0); + stop_fields(app, ui, &g.gradient, is_grad); + return; + } method_row(app, ui, &g, is_grad); spread_row(app, ui, &g, is_grad); // The proxy beside the angle and aspect ratio fields. @@ -517,11 +535,8 @@ pub(crate) fn edit_point(app: &mut VectorcraftApp, cmd: &str, mut params: Value) live_run(app, "Gradient", cmd, params, Live::Released); } -/// The freeform section: the proxy beside the Draw toggle, then the selected point's colour, -/// opacity and spread, and Delete Point. -fn freeform_section(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint) { - let f = shown_points(g); - let mode = f.mode; +/// The proxy beside the Draw toggle of a freeform gradient, whose mode is `mode`. +fn draw_row(app: &mut VectorcraftApp, ui: &mut Ui, mode: FreeformMode) { ui.horizontal(|ui| { super::proxy(app, ui, 36.0); ui.add_space(4.0); @@ -535,6 +550,13 @@ fn freeform_section(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint) { } } }); +} + +/// The freeform section: the proxy beside the Draw toggle, then the selected point's colour, +/// opacity and spread, and Delete Point. +fn freeform_section(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint) { + let f = shown_points(g); + draw_row(app, ui, f.mode); ui.add_space(6.0); let sel = app.session.selected_freeform_point().filter(|i| *i < f.points.len()); let point = sel.map(|i| f.points[i]); diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 1a607b8f24..7f8515dcca 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -63,6 +63,39 @@ fn a_swatch_color_on_a_stop_or_a_point_keeps_its_model_in_a_cmyk_document() { assert_eq!(g.freeform.map(|f| f.points[1].color), Some(orange)); } +/// While the Shape Builder paints with a freeform fill, which lies on no object, the panel shows +/// that fill's stops, and a swatch color recolors the selected stop instead of a point. +#[test] +fn the_shape_builders_freeform_fill_is_edited_by_its_stops() { + use egui_kittest::kittest::Queryable; + let mut app = app(json!({"color": "#000000"})); + app.select_tool("shapeBuilder"); + app.run("paint.editGradient", json!({"stroke": false, "kind": "freeform"})).unwrap(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.editGradient", json!({"stroke": false, "stops": stops})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let orange = Color::rgb8(255, 128, 0); + assert!(recolor_selected(&mut app, orange, &json!({})), "the selected stop takes the color"); + let Paint::Gradient(g) = active_paint(&app) else { panic!("the tool's fill is not a gradient") }; + assert_eq!(g.gradient.kind, GradientKind::Freeform); + assert_eq!(g.gradient.stops[1].color, orange); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(280.0, 640.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + show(app, ui); + }, + app, + ); + h.run_steps(3); + let _ = h.get_by_label("Delete Stop"); + let _ = h.get_by_label("Location:"); + let _ = h.get_by_label("Draw:"); +} + /// In a CMYK document Add to Swatches and Save to Swatches keep the gradient's RGB stops RGB. #[test] fn a_gradient_saved_as_a_swatch_keeps_its_stops_models_in_a_cmyk_document() { diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 3ba5451568..624a553826 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -514,7 +514,7 @@ pub(crate) const PROFILE_DROPDOWN_WIDTH: f32 = 100.0; /// member's. pub(crate) fn brush_keeps_size(app: &VectorcraftApp, ctx: &egui::Context, shown: Option<&StrokeLayer>) -> Option { let st = app.session.active()?; - let bucket = app.session.bucket_paints(); + let bucket = app.session.tool_paints(true); if bucket || (st.selection.objects.is_empty() && st.selection.subjects().is_empty()) { let s = shown?; let name = s.brush.as_deref()?; diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..964ada161c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -742,7 +742,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,wheel?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | | `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. | | `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners; an ellipse takes `anchors`, 2–1000, default 4). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. Polygons and stars take `rotation` in degrees clockwise (0: a corner or point straight up). `line`: `x1,y1,x2,y2`. | -| `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. | +| `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. When some of those commands painted objects and others painted none (a fill while the Shape Builder is the active tool, say), `unpainted` lists the commands that painted none, with a `note`. | | `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee; `c` and `f` while dragging out an arc; `f`, `v`, `x` and `c` while dragging out a rectangular or polar grid). | | `type_text` | `{text}` | Remote only. | | `answer_dialog` | `{set?: [{field, value?}], action?}` | Remote only. Sets fields of the app's open dialog in the order given with one `ui.dialog.set {fields, action?}` (a missing `value` is `null`). The app stores all of them or none, then answers that same dialog with `action` in the same request: `confirm` (OK) or `cancel`. Another connection cannot open a dialog between the two steps. When the app refuses the `ui.dialog.set`, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. `set` cannot change a `__` field other than the dialog's controls held under a `__` name (such as Save PDF's `__section` or the Preferences `__search`): the `__command` and `__params` of a `confirm` or `command` dialog, and every other `__` field that holds what OK acts on, are refused with "the `` dialog cannot set protected field ``", so OK runs what the dialog was opened for. `action` alone is sent as `ui.dialog.confirm` or `ui.dialog.cancel`. Give `set`, `action` or both; `set` holds at most 256 fields. `inspect_ui` shows the open dialog and its fields as `ui.dialog`. Returns `{dialog, result}`: the dialog after the fields were set (or `null`) and the reply to `confirm` or `cancel` (or `null`). After `invoke_menu` `app.quit`, `file.close` or `file.closeAll` replies `{"pending": "saveChanges"}`, `{action: "confirm"}` saves, `{set: [{field: "discard", value: true}], action: "confirm"}` closes without saving and `{action: "cancel"}` cancels the close or quit. | @@ -4042,9 +4042,10 @@ already walks Image Trace. Short agent entry points: moving and transforming, `path.moveAnchors`, `file.place` with `replace`, Puppet Warp, Delete and Cut, Group, Hide, Lock, Arrange, Expand, Recolor Artwork, plug-in filters, effects, the gradient commands, `gradient.selectStop`, the Appearance panel's rows and - `symbol.instance.setAppearance`. While the Live Paint Bucket is the active tool, `paint.editGradient` and - `gradient.presets.apply` without `ids`, `id` or `item` change the bucket's gradient instead, and - `gradient.selectStop` selects a stop of it. A Cmd-drag that lends the Selection or Group Selection tool selects the + `symbol.instance.setAppearance`. While the Live Paint Bucket, or for a fill the Shape Builder, is the active tool, + `paint.editGradient` and `gradient.presets.apply` without `ids`, `id` or `item` change the gradient the tool paints + with instead, and `gradient.selectStop` selects a stop of it. + A Cmd-drag that lends the Selection or Group Selection tool selects the instance whole first and moves it. `swatch.unused` and `recolor.colors` count the fills and strokes an instance keeps for objects of its art. Commands that change nothing in the document, such as `attributes.info`, `css.selection`, `css.export`, `effect.list` and `object.expand.info`, read the instance. These commands do not check for a selected object and use the instance: @@ -13691,8 +13692,19 @@ pointer show the current fill and the swatches before and after it), `selection` `straightLine`: a drag touches what the line from its first point to the pointer crosses), `highlightFill` (on by default; when it is off, merge mode shades no regions), `gapDetection` (off) with `gapLength` (pt, 0 to 72; 3), `clickStrokeSplitsPath` (In Merge Mode, Clicking Stroke Splits the Path; off), `highlightStroke` (Highlight Stroke When Editable; on) and `highlightColor` -(`#rrggbb` or a layer color's name; `#ff4f4f`, the layer color Red). The dialog's OK gives an error for a -`highlightColor` with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. `tool.setOption` gives an error that +(`#rrggbb` or a layer color's name; `#ff4f4f`, the layer color Red). While the Shape Builder is the active tool, with +either `pickColorFrom`, a fill chosen without `ids`, `id` or `item` (`paint.setFill`, `paint.none`, `paint.lastColor`, +`paint.lastGradient`, `paint.editGradient`, `paint.invert`, `paint.complement`, `paint.sampleColor` and +`gradient.presets.apply` on the fill, a swatch or the Color Picker), changes only the current fill: the selected paths +keep their paint, and no undo step is recorded. With `swatches` the next merge fills with that fill; with `artwork` +merges still take the look of the art. The Fill proxy shows that fill, the `paint.freeform.*` commands on the fill give +an error, as with the Live Paint Bucket, and the fill a new selection shows does not replace it for new art. A stroke +chosen then (`paint.setStroke`, `stroke.set` and the other stroke commands) still goes to the selection. `paint.swap` +and `paint.default` without `ids` or `id` change only the paint for new art (`paint.default` resets all of it): the +selected paths keep their fills and strokes, and `paint.swap` gives the current fill the stroke the Stroke proxy shows +(the stroke for new art when the proxy shows mixed strokes). With New Art Has Basic Appearance off, the stroke for new +art then follows the selection again, as after any command. The dialog's OK gives an error for a `highlightColor` with +an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. `tool.setOption` gives an error that names the option and sets none of the values, whether the tool is chosen or not, for a switch that is not `true` or `false`, a `pickColorFrom` other than `artwork` or `swatches`, a `selection` other than `freeform` or `straightLine`, a `gapLength` that is not a number, a `highlightColor` that is not `#rrggbb`, `#rgb` (with or without `#`), a layer From 1cecbb9aeedd66a24a47bda966f2983afba030fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:25:08 -0800 Subject: [PATCH 041/101] Display Print Size: keep the last density, fits and percentages right - A fit made while a floating window's display has not answered keeps counting from the density the window was last shown at, so Actual Size and the zoom field no longer fall back to 96 points to an inch meanwhile. - A view that still fits its floating window keeps fitting it after a move to a display of another density: the fit kept for the window takes the settled zoom. - The plausible range of a measured display applies to its pixels per inch, before the display scale divides them into points. A 1920 x 1080 display of 527 x 296 mm at scale 4 now measures about 23 points to an inch instead of falling back to 96, and Actual Size takes any finite, positive point density the host measured. - View > Set Zoom, Zoom In and Zoom Out, the wheel and the Zoom tool clear the zoom a fit gave the view, so a percentage that equals the last fit's zoom keeps its percentage at the first reading. - The Actual Size and preference descriptions say that a size no display has also counts 96 points to an inch. --- apps/vectorcraft/src/screen_density.rs | 24 ++++++--- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/app/view.rs | 10 +++- crates/ui-egui/src/canvas/tests.rs | 16 ++++++ crates/ui-egui/src/canvas/view.rs | 1 + crates/ui-egui/src/doc_windows.rs | 4 ++ crates/ui-egui/src/doc_windows/tests.rs | 50 +++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 2 +- crates/ui-egui/src/i18n/bs.tsv | 2 +- crates/ui-egui/src/i18n/ca.tsv | 2 +- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/da.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/gu.tsv | 2 +- crates/ui-egui/src/i18n/hi.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/id.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- crates/ui-egui/src/menus/run.rs | 3 ++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- .../ui-egui/src/prefs_dialog/descriptions.rs | 2 +- crates/ui-egui/src/state.rs | 18 ++++--- docs/target-app-parity.md | 2 +- 40 files changed, 144 insertions(+), 46 deletions(-) diff --git a/apps/vectorcraft/src/screen_density.rs b/apps/vectorcraft/src/screen_density.rs index 70ba069684..4a8c91ec76 100644 --- a/apps/vectorcraft/src/screen_density.rs +++ b/apps/vectorcraft/src/screen_density.rs @@ -301,19 +301,20 @@ impl Tracker { /// The density, in points per inch, of a display `size` physical pixels wide and high, drawn at /// `scale` pixels to a point, that the system says is `mm` millimeters wide and high. `None` for a /// size that is no display's: zero or less, an aspect ratio given in place of the size (16 × 9, -/// 160 × 90 and the like), axes whose densities disagree in either orientation, or a density -/// outside [`vectorcraft_ui_egui::state::SCREEN_PPI_RANGE`]. A display turned a quarter turn may -/// report the size of its panel upright, so the axes are also tried swapped. +/// 160 × 90 and the like), axes whose densities disagree in either orientation, or a pixel density +/// outside [`vectorcraft_ui_egui::state::SCREEN_PPI_RANGE`]. The range applies to the pixels, before +/// the scale divides them into points. A display turned a quarter turn may report the size of its +/// panel upright, so the axes are also tried swapped. pub(crate) fn points_per_inch(size: PhysicalSize, scale: f64, mm: [f64; 2]) -> Option { if !(scale.is_finite() && scale > 0.0) || mm.iter().any(|v| !(v.is_finite() && *v > 0.0)) || aspect_as_size(mm) { return None; } - let points = [f64::from(size.width) / scale, f64::from(size.height) / scale]; - let density = |[w, h]: [f64; 2]| [points[0] / (w / MM_PER_INCH), points[1] / (h / MM_PER_INCH)]; + let pixels = [f64::from(size.width), f64::from(size.height)]; + let density = |[w, h]: [f64; 2]| [pixels[0] / (w / MM_PER_INCH), pixels[1] / (h / MM_PER_INCH)]; let agree = |[x, y]: [f64; 2]| (x - y).abs() <= AXES_AGREE * x.max(y); let [x, y] = [density(mm), density([mm[1], mm[0]])].into_iter().find(|d| agree(*d))?; let ppi = (x + y) / 2.0; - vectorcraft_ui_egui::state::SCREEN_PPI_RANGE.contains(&ppi).then_some(ppi) + vectorcraft_ui_egui::state::SCREEN_PPI_RANGE.contains(&ppi).then_some(ppi / scale) } /// Whether `mm` is an aspect ratio that a display's EDID gave in place of its size: 16:9, 16:10 @@ -545,6 +546,17 @@ mod tests { assert_eq!(points_per_inch(PhysicalSize::new(7680, 4320), 1.0, [53.0, 30.0]), None, "over it"); } + /// The range applies to the display's pixels: a 1920 × 1080 display of 527 × 296 mm drawn at + /// scale 4 has about 23 points to an inch, which is a real density. + #[test] + fn a_large_scale_factor_does_not_put_a_display_out_of_range() { + let ppi = points_per_inch(PhysicalSize::new(1920, 1080), 4.0, [527.0, 296.0]); + let pixels = points_per_inch(PhysicalSize::new(1920, 1080), 1.0, [527.0, 296.0]).unwrap_or(0.0); + assert!(ppi.is_some_and(|p| p < 30.0 && (p - pixels / 4.0).abs() < 1e-9), "{ppi:?}"); + let print = vectorcraft_ui_egui::state::print_ppi(true, ppi); + assert_eq!(print, ppi, "Actual Size counts from it, not from 96"); + } + /// A 1920 × 1080 display at scale 1 and position `x`, named `name`. fn display(name: &str, x: i32) -> Display { Display { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 55b0df872e..7a18fcf475 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -484,7 +484,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "view.actualSize", "Actual Size", "Cmd+1", - "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills an inch of the display that shows the window, measured from the physical size the system reports for it, or 96 screen points where it reports none; the same at every UI Scaling", + "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills an inch of the display that shows the window, measured from the physical size the system reports for it, or 96 screen points where it reports none or a size no display has; the same at every UI Scaling", ), ("view.setZoom", "Set Zoom", "", "{zoom: percent, center?: [x,y]}"), ( diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index f20ad4758f..8498732365 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -191,8 +191,14 @@ impl VectorcraftApp { } if !keep { // While the display is being read, the fit counts from the last reading, as the other - // views there do, and the reading keeps its zoom. - v.shown_ppi = Some(now); + // views there do, and the reading keeps its zoom. A floating window whose display has + // not answered keeps counting from the density it was last shown at. + match now { + crate::ScreenPpi::Unread => { + v.shown_ppi.get_or_insert(now); + } + read => v.shown_ppi = Some(read), + } v.fit_unread = reading == crate::ScreenPpi::Unread; return; } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 2576980464..0314401506 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -8674,6 +8674,22 @@ fn actual_size_after_a_fit_of_the_same_zoom_stays_at_100_percent() { assert!((now - shown).abs() < 1e-9, "a zoom chosen after the fit keeps its percentage: {shown} → {now}"); } +/// A percentage set with `view.setZoom` keeps its percentage at the first reading, also when it +/// gives the view the zoom of the fit made before it. +#[test] +fn a_set_zoom_of_the_fits_zoom_keeps_its_percentage_at_the_first_reading() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 300, "height": 100})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(460.0, 260.0))); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + app.run("view.fitArtboard", json!({})).unwrap(); + let fitted = app.view().unwrap().zoom; + app.run("view.setZoom", json!({"zoom": 100})).unwrap(); + assert_eq!(app.view().unwrap().zoom, fitted, "100% has the fit's zoom before any reading"); + assert!(app.set_screen_ppi(Some(127.0))); + assert!((app.view().unwrap().zoom * 72.0 - 127.0).abs() < 1e-9, "the reading keeps 100%: {}", app.view().unwrap().zoom * 72.0); +} + /// Fit Artboard in Window fits the artboard as a rotated view shows it: at 45° every corner is /// on the canvas and one is within the 30-point margin of an edge. At 0° the zoom is unchanged. #[test] diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index b2714f2645..9dd5c3b974 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -123,6 +123,7 @@ pub(crate) fn actual_size_zoom(print: Option) -> f64 { pub(super) fn zoom_about(vm: &mut View, rect: egui::Rect, p: Pos2, zoom: f64, ui_zoom: f32) { let before = Xf::at(rect, vm, ui_zoom).to_doc(p); vm.zoom = zoom.clamp(0.0313, 640.0); + vm.fit_zoom = None; vm.center += before - Xf::at(rect, vm, ui_zoom).to_doc(p); } diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index f565fcb4a8..058132f839 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -650,6 +650,10 @@ fn take_window_ppi(app: &mut VectorcraftApp, ctx: &egui::Context, ((uid, number) let size = shown.body.map(|b| b.size()); let following = view(app, win).is_some_and(|v| v.fitted && shown.fit.is_some_and(|(s, z, c)| Some(s) == size && z == v.zoom && c == v.center)); app.settle_window_ppi(win, !(following && (first || fitted_now))); + // A view that still fits its window keeps fitting it at the zoom the new density gave it. + if following && let (Some((s, _, _)), Some(v)) = (shown.fit, view(app, win)) { + shown.fit = Some((s, v.zoom, v.center)); + } ctx.request_repaint(); } diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 8a001a3748..fb803249e1 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -1331,3 +1331,53 @@ fn a_floating_os_window_takes_the_density_of_the_display_it_is_found_on() { take_window_ppi(&mut app, &ctx, ((uid, 1), false), win, &mut found(Some(crate::ScreenPpi::Read(Some(110.0))))); assert!((inch(&app) - 127.0).abs() < 1e-9, "drawn in the main window, 100% counts from the main window's display: {}", inch(&app)); } + +/// A fit made while a floating OS window is off every display keeps counting from the density the +/// window was last shown at, and the reading that follows leaves the fit's zoom alone. +#[test] +fn a_fit_made_while_a_floating_window_is_unread_counts_from_its_last_reading() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + app.set_screen_ppi(Some(127.0)); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + let uid = app.session.documents()[1].uid; + let win = (1, 1); + let found = |ppi: Option| Shown { ppi, ..Default::default() }; + take_window_ppi(&mut app, &ctx, ((uid, 1), true), win, &mut found(Some(crate::ScreenPpi::Read(Some(150.0))))); + take_window_ppi(&mut app, &ctx, ((uid, 1), true), win, &mut found(None)); + app.run("view.fitArtboard", json!({})).unwrap(); + let zoom = app.views[1].zoom; + assert_eq!(app.print_ppi_of(Some(win)), Some(150.0), "the fit counts from the last reading"); + take_window_ppi(&mut app, &ctx, ((uid, 1), true), win, &mut found(Some(crate::ScreenPpi::Read(Some(110.0))))); + assert_eq!(app.views[1].zoom, zoom, "the reading leaves the fit alone"); + assert_eq!(app.print_ppi_of(Some(win)), Some(110.0)); +} + +/// A floating OS window whose view still fits it, moved between two displays read before, keeps +/// fitting it at the zoom the new density gives: the fit this frame keeps is the settled one. +#[test] +fn a_fitted_floating_window_moved_to_another_density_keeps_fitting() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + app.set_screen_ppi(Some(127.0)); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + let uid = app.session.documents()[1].uid; + let win = (1, 1); + take_window_ppi(&mut app, &ctx, ((uid, 1), true), win, &mut Shown { ppi: Some(crate::ScreenPpi::Read(Some(91.0))), ..Default::default() }); + app.run("view.fitArtboard", json!({})).unwrap(); + let (zoom, center) = (app.views[1].zoom, app.views[1].center); + let body = egui::Rect::from_min_size(Pos2::ZERO, vec2(500.0, 400.0)); + let fit = Some((body.size(), zoom, center)); + if let Some(x) = app.ui.floating.iter_mut().find(|x| x.uid == uid && x.view == 1) { + x.fit = fit; + } + let mut moved = Shown { ppi: Some(crate::ScreenPpi::Read(Some(150.0))), body: Some(body), fit, ..Default::default() }; + take_window_ppi(&mut app, &ctx, ((uid, 1), true), win, &mut moved); + let v = app.views[1]; + assert_ne!(v.zoom, zoom, "the move to a denser display keeps the zoom percentage"); + assert_eq!(moved.fit, Some((body.size(), v.zoom, v.center)), "and the fit kept is the settled zoom"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index a547a5de48..1dc78ac049 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3209,7 +3209,7 @@ digits Malayalam Малаялам Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. „Селекция › Същото › Цвят на запълване“, „Цвят на щриха“ и „Запълване и щрих“ намират само същия нюанс на глобална или плътна мостра, а не всеки неин нюанс. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Показва началния екран, когато няма отворен документ; ако е изключено, прозорецът остава празен, докато не щракнете „Начало“. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Измерва обектите заедно с щрихите и ефектите, които променят формата, за размер, позиция и подравняване; сенките, сиянията и замъгляванията не се измерват. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. При мащаб 100 % един инч от документа запълва един инч от дисплея или 96 екранни точки, когато системата не съобщава размера на дисплея. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. При мащаб 100 % един инч от документа запълва един инч от дисплея или 96 екранни точки, когато системата не съобщава използваем размер на дисплея. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Двойно щракване върху група, контур или изображение с инструмента „Селекция“ ги отваря в режим на изолация. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Запълванията и щрихите с мостра се трансформират заедно с графиката, освен ако трансформацията или менюто на панела „Трансформиране“ не избере друго. Live corner radii scale with the art, unless the scale chooses otherwise. Радиусите на динамичните ъгли се мащабират заедно с графиката, освен ако мащабирането не избере друго. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9204190552..87484221a8 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4696,7 +4696,7 @@ font-technology Variable Varijabilni Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Odabir › Isto › Boja ispune, Boja poteza i Ispuna i potez pronalaze samo istu nijansu globalnog ili spot uzorka, a ne bilo koju njegovu nijansu. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Prikazuje početni ekran kada nijedan dokument nije otvoren; kada je isključeno, prozor ostaje prazan dok ne kliknete Početna. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mjeri objekte zajedno s potezima i efektima koji mijenjaju oblik za veličinu, položaj i poravnanje; sjene, sjaj i zamućenja se ne mjere. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Pri zumu od 100% jedan inč dokumenta ispunjava jedan inč ekrana, ili 96 tačaka ekrana kada sistem ne javlja veličinu ekrana. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Pri zumu od 100% jedan inč dokumenta ispunjava jedan inč ekrana, ili 96 tačaka ekrana kada sistem ne javlja upotrebljivu veličinu ekrana. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dvostruki klik na grupu, putanju ili sliku alatom Odabir otvara ih u načinu izolacije. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Ispune i potezi s uzorkom transformišu se zajedno s grafikom, osim ako transformacija ili meni panela Transformiši ne odabere drugačije. Live corner radii scale with the art, unless the scale chooses otherwise. Poluprečnici dinamičnih uglova skaliraju se zajedno s grafikom, osim ako skaliranje ne odabere drugačije. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index d9fe0a739a..b3ad7e42d6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4067,7 +4067,7 @@ digits Malayalam Malaiàlam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selecció › Igual › Color de farciment, Color del traç i Farciment i traç només coincideixen amb el mateix matís d’una mostra global o de tinta plana, no amb qualsevol matís seu. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Mostra la pantalla d’inici quan no hi ha cap document obert; desactivada, la finestra queda buida fins que feu clic a Inici. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mesura els objectes amb els traços i els efectes que en canvien la forma per a la mida, la posició i l’alineació; les ombres, les lluïsors i els desenfocaments no es mesuren. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Amb un zoom del 100 %, una polzada del document omple una polzada de la pantalla, o 96 punts de pantalla quan el sistema no n’indica la mida. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Amb un zoom del 100 %, una polzada del document omple una polzada de la pantalla, o 96 punts de pantalla quan el sistema no n’indica una mida utilitzable. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Fer doble clic en un grup, traçat o imatge amb l’eina Selecció l’obre en mode d’aïllament. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Els farciments i traços de motiu es transformen amb la il·lustració, tret que una transformació o el menú del panell Transforma triï una altra cosa. Live corner radii scale with the art, unless the scale chooses otherwise. Els radis de cantonada dinàmics s’escalen amb la il·lustració, tret que l’escalat triï una altra cosa. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index bb1e2f34ab..bd96fc2da4 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4805,7 +4805,7 @@ font-technology Variable Variabilní Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Výběr › Stejné › Barva výplně, Barva tahu a Výplň a tah najdou jen stejný odstín globálního nebo přímého vzorku, ne libovolný jeho odstín. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Zobrazí domovskou obrazovku, když není otevřený žádný dokument; když je vypnuto, okno zůstane prázdné, dokud neklepnete na Domů. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Měří objekty včetně tahů a efektů měnících tvar pro velikost, polohu a zarovnání; stíny, záře a rozostření se neměří. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Při zvětšení 100 % vyplní jeden palec dokumentu jeden palec displeje, nebo 96 obrazovkových bodů, pokud systém velikost displeje neudává. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Při zvětšení 100 % vyplní jeden palec dokumentu jeden palec displeje, nebo 96 obrazovkových bodů, pokud systém neudává použitelnou velikost displeje. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Poklepání na skupinu, cestu nebo obraz nástrojem Výběr je otevře v izolačním režimu. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Výplně a tahy se vzorkem se transformují s kresbou, pokud transformace nebo nabídka panelu Transformace nezvolí jinak. Live corner radii scale with the art, unless the scale chooses otherwise. Poloměry živých rohů se mění s velikostí kresby, pokud změna velikosti nezvolí jinak. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d3978bfddf..6d0be9adb7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7253,7 +7253,7 @@ font-technology Variable Variable Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Markér › Samme › Fyldfarve, Stregfarve og Fyld og streg finder kun samme nuance af en global farveprøve eller staffagefarve, ikke en hvilken som helst nuance af den. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Viser startskærmen, når intet dokument er åbent; når den er slået fra, forbliver vinduet tomt, indtil du klikker på Home. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Måler objekter med deres streger og formændrende effekter til størrelse, position og justering; skygger, glød og sløringer måles ikke. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Ved 100 % zoom fylder en tomme af dokumentet en tomme af skærmen, eller 96 skærmpunkter, hvis systemet ikke oplyser skærmens størrelse. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Ved 100 % zoom fylder en tomme af dokumentet en tomme af skærmen, eller 96 skærmpunkter, hvis systemet ikke oplyser en brugbar skærmstørrelse. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dobbeltklik på en gruppe, en sti eller et billede med værktøjet Markering åbner det i isolationstilstand. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Mønsterfyld og -streger transformeres med grafikken, medmindre en transformation eller menuen i panelet Transformér vælger andet. Live corner radii scale with the art, unless the scale chooses otherwise. Live-hjørneradier skaleres med grafikken, medmindre skaleringen vælger andet. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2663967128..002798227c 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3279,7 +3279,7 @@ digits Malayalam Malayalam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. „Auswahl › Gleich › Flächenfarbe“, „Konturfarbe“ und „Fläche und Kontur“ finden nur denselben Farbton eines globalen oder Volltonfarbfelds, nicht jeden Farbton davon. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Zeigt den Startbildschirm, wenn kein Dokument geöffnet ist; ist die Option aus, bleibt das Fenster leer, bis Sie auf „Start“ klicken. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Misst Objekte für Größe, Position und Ausrichtung mit ihren Konturen und formverändernden Effekten; Schatten, Schein und Weichzeichnungen werden nicht gemessen. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Bei 100 % Zoom füllt ein Zoll des Dokuments einen Zoll des Bildschirms, oder 96 Bildschirmpunkte, wenn das System keine Bildschirmgröße meldet. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Bei 100 % Zoom füllt ein Zoll des Dokuments einen Zoll des Bildschirms, oder 96 Bildschirmpunkte, wenn das System keine verwendbare Bildschirmgröße meldet. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Ein Doppelklick mit dem Auswahl-Werkzeug auf eine Gruppe, einen Pfad oder ein Bild öffnet sie im Isolationsmodus. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Musterflächen und -konturen werden mit dem Bildmaterial transformiert, sofern die Transformation oder das Menü des Bedienfelds „Transformieren“ nichts anderes wählt. Live corner radii scale with the art, unless the scale chooses otherwise. Live-Eckenradien skalieren mit dem Bildmaterial, sofern die Skalierung nichts anderes wählt. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 579174fce7..cbd3f5c92b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4132,7 +4132,7 @@ digits Malayalam Μαλαγιάλαμ Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Τα Επιλογή › Ίδιο › Χρώμα γεμίσματος, Χρώμα περιγράμματος και Γέμισμα και περίγραμμα βρίσκουν μόνο την ίδια απόχρωση ενός καθολικού ή σημειακού δείγματος, όχι οποιαδήποτε απόχρωσή του. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Εμφανίζει την αρχική οθόνη όταν δεν είναι ανοιχτό κανένα έγγραφο· όταν είναι ανενεργό, το παράθυρο μένει κενό μέχρι να κάνετε κλικ στην Αρχική οθόνη. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Μετρά τα αντικείμενα μαζί με τα περιγράμματα και τα εφέ που αλλάζουν το σχήμα τους για μέγεθος, θέση και στοίχιση· οι σκιές, οι λάμψεις και οι θολώσεις δεν μετρώνται. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Σε ζουμ 100%, μία ίντσα του εγγράφου γεμίζει μία ίντσα της οθόνης, ή 96 στιγμές οθόνης όταν το σύστημα δεν αναφέρει το μέγεθος της οθόνης. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Σε ζουμ 100%, μία ίντσα του εγγράφου γεμίζει μία ίντσα της οθόνης, ή 96 στιγμές οθόνης όταν το σύστημα δεν αναφέρει χρησιμοποιήσιμο μέγεθος οθόνης. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Το διπλό κλικ σε ομάδα, διαδρομή ή εικόνα με το εργαλείο Επιλογή την ανοίγει σε λειτουργία απομόνωσης. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Τα γεμίσματα και τα περιγράμματα μοτίβου μετασχηματίζονται μαζί με το γραφικό, εκτός αν ένας μετασχηματισμός ή το μενού του πλαισίου Μετασχηματισμός επιλέξει κάτι άλλο. Live corner radii scale with the art, unless the scale chooses otherwise. Οι ακτίνες των δυναμικών γωνιών κλιμακώνονται μαζί με το γραφικό, εκτός αν η κλιμάκωση επιλέξει κάτι άλλο. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 08b4fc2693..94fe1524c4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3315,7 +3315,7 @@ digits Malayalam Malayálam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selección › Igual › Color de relleno, Color de trazo y Relleno y trazo solo coinciden con el mismo matiz de una muestra global o de tinta plana, no con cualquier matiz de ella. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Muestra la pantalla de inicio cuando no hay ningún documento abierto; desactivada, la ventana queda vacía hasta que hace clic en Inicio. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mide los objetos con sus trazos y los efectos que cambian su forma para el tamaño, la posición y la alineación; las sombras, los resplandores y los desenfoques no se miden. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Con un zoom del 100 %, una pulgada del documento ocupa una pulgada de la pantalla, o 96 puntos de pantalla si el sistema no indica su tamaño. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Con un zoom del 100 %, una pulgada del documento ocupa una pulgada de la pantalla, o 96 puntos de pantalla si el sistema no indica un tamaño utilizable. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Al hacer doble clic en un grupo, trazado o imagen con la herramienta Selección, se abre en modo de aislamiento. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Los rellenos y trazos de motivo se transforman con la ilustración, salvo que una transformación o el menú del panel Transformar indique otra cosa. Live corner radii scale with the art, unless the scale chooses otherwise. Los radios de esquina dinámicos se escalan con la ilustración, salvo que el escalado indique otra cosa. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index c712366c71..037d3a5f40 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4715,7 +4715,7 @@ font-technology Variable Muuttuvat Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Valinta › Sama › Täyttöväri, Viivan väri sekä Täyttö ja viiva löytävät vain globaalin tai spottivärimallin saman sävyn, eivät mitä tahansa sen sävyä. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Näyttää aloitusnäytön, kun yhtään asiakirjaa ei ole auki; kun asetus ei ole käytössä, ikkuna pysyy tyhjänä, kunnes napsautat Aloitus. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mittaa objektit viivoineen ja muotoa muuttavine tehosteineen kokoa, sijaintia ja tasausta varten; varjoja, hehkuja ja sumennuksia ei mitata. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100 %:n zoomauksella asiakirjan tuuma täyttää näytön tuuman, tai 96 näyttöpistettä, jos järjestelmä ei ilmoita näytön kokoa. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. 100 %:n zoomauksella asiakirjan tuuma täyttää näytön tuuman, tai 96 näyttöpistettä, jos järjestelmä ei ilmoita käyttökelpoista näytön kokoa. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Ryhmän, polun tai kuvan kaksoisnapsautus Valinta-työkalulla avaa sen eristystilaan. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Kuviotäytöt ja -viivat muuntuvat grafiikan mukana, ellei muunnos tai Muunna-paneelin valikko valitse toisin. Live corner radii scale with the art, unless the scale chooses otherwise. Dynaamisten kulmien säteet skaalautuvat grafiikan mukana, ellei skaalaus valitse toisin. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 384add6e6f..46dea97980 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3303,7 +3303,7 @@ digits Malayalam Malayalam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Sélection › Identique › Couleur de fond, Couleur du contour et Fond et contour ne retiennent que la même teinte d’une nuance globale ou d’une couleur d’accompagnement, et non toutes ses teintes. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Affiche l’écran d’accueil quand aucun document n’est ouvert. Désactivée, la fenêtre reste vide jusqu’à ce que vous cliquiez sur Accueil. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mesure les objets avec leurs contours et leurs effets qui modifient la forme pour la taille, la position et l’alignement. Les ombres, lueurs et flous ne sont pas mesurés. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. À 100 % de zoom, un pouce du document occupe un pouce de l’écran, ou 96 points d’écran si le système n’indique pas la taille de l’écran. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. À 100 % de zoom, un pouce du document occupe un pouce de l’écran, ou 96 points d’écran si le système n’indique pas de taille d’écran utilisable. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Un double-clic sur un groupe, un tracé ou une image avec l’outil Sélection l’ouvre en mode Isolation. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Les fonds et contours de motif se transforment avec l’illustration, sauf si une transformation ou le menu du panneau Transformation en décide autrement. Live corner radii scale with the art, unless the scale chooses otherwise. Les rayons d’angle dynamiques se mettent à l’échelle avec l’illustration, sauf si la mise à l’échelle en décide autrement. diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c9b4e617f7..815b4668ab 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3370,7 +3370,7 @@ arrowhead Feather પીંછું Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. પસંદ કરો › સમાન › ભરવાનો રંગ, સ્ટ્રોક રંગ અને ભરો અને સ્ટ્રોક ફક્ત ગ્લોબલ કે સ્પોટ સ્વૉચના એ જ ટિન્ટ સાથે મેળ ખાય છે, તેના કોઈપણ ટિન્ટ સાથે નહીં. Shows the Home screen when no document is open; off, the window stays empty until you click Home. કોઈ દસ્તાવેજ ખુલ્લો ન હોય ત્યારે હોમ સ્ક્રીન બતાવે છે; બંધ હોય ત્યારે તમે હોમ પર ક્લિક ન કરો ત્યાં સુધી વિન્ડો ખાલી રહે છે. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. કદ, સ્થાન અને ગોઠવણી માટે ઑબ્જેક્ટને તેમના સ્ટ્રોક અને આકાર બદલતી ઇફેક્ટ્સ સાથે માપે છે; છાયા, ગ્લો અને બ્લર માપવામાં આવતા નથી. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100% ઝૂમ પર દસ્તાવેજનો એક ઇંચ ડિસ્પ્લેનો એક ઇંચ ભરે છે, અથવા સિસ્ટમ ડિસ્પ્લેનું કદ ન જણાવે ત્યારે 96 સ્ક્રીન પોઇન્ટ લે છે. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. 100% ઝૂમ પર દસ્તાવેજનો એક ઇંચ ડિસ્પ્લેનો એક ઇંચ ભરે છે, અથવા સિસ્ટમ ડિસ્પ્લેનું ઉપયોગી કદ ન જણાવે ત્યારે 96 સ્ક્રીન પોઇન્ટ લે છે. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. પસંદગી ટૂલથી ગ્રુપ, પાથ કે છબી પર ડબલ-ક્લિક કરવાથી તે આઇસોલેશન મોડમાં ખુલે છે. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. પૅટર્ન ભરણ અને સ્ટ્રોક આર્ટવર્ક સાથે ટ્રાન્સફોર્મ થાય છે, સિવાય કે કોઈ ટ્રાન્સફોર્મ કે ટ્રાન્સફોર્મ પેનલનું મેનૂ બીજું પસંદ કરે. Live corner radii scale with the art, unless the scale chooses otherwise. લાઇવ ખૂણાઓની ત્રિજ્યાઓ આર્ટવર્ક સાથે સ્કેલ થાય છે, સિવાય કે સ્કેલિંગ બીજું પસંદ કરે. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 4f875c707c..5eba3a7548 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4698,7 +4698,7 @@ arrowhead Feather पंख Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. सिलेक्ट › समान › फ़िल रंग, स्ट्रोक रंग और फ़िल व स्ट्रोक केवल ग्लोबल या स्पॉट स्वॉच के उसी टिंट से मेल खाते हैं, उसके किसी भी टिंट से नहीं। Shows the Home screen when no document is open; off, the window stays empty until you click Home. कोई डॉक्यूमेंट खुला न होने पर होम स्क्रीन दिखाता है; बंद होने पर विंडो तब तक खाली रहती है जब तक आप होम पर क्लिक नहीं करते। Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. साइज़, स्थिति और संरेखण के लिए ऑब्जेक्ट को उनके स्ट्रोक और आकार बदलने वाले इफ़ेक्ट के साथ मापता है; छाया, ग्लो और ब्लर नहीं मापे जाते। - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100% ज़ूम पर डॉक्यूमेंट का एक इंच डिस्प्ले का एक इंच घेरता है, या सिस्टम डिस्प्ले का आकार न बताए तो 96 स्क्रीन पॉइंट लेता है। + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. 100% ज़ूम पर डॉक्यूमेंट का एक इंच डिस्प्ले का एक इंच घेरता है, या सिस्टम डिस्प्ले का उपयोग योग्य आकार न बताए तो 96 स्क्रीन पॉइंट लेता है। Double-clicking a group, path or image with the Selection tool opens it in isolation mode. सिलेक्शन टूल से किसी ग्रुप, पाथ या इमेज पर डबल-क्लिक करने से वह आइसोलेशन मोड में खुलता है। Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. पैटर्न वाले फ़िल और स्ट्रोक आर्टवर्क के साथ रूपांतरित होते हैं, जब तक कोई रूपांतरण या रूपांतरण पैनल का मेनू कुछ और न चुने। Live corner radii scale with the art, unless the scale chooses otherwise. लाइव कोनों की त्रिज्याएँ आर्टवर्क के साथ स्केल होती हैं, जब तक स्केलिंग कुछ और न चुने। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d14fb0bced..f6b4d33442 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3903,7 +3903,7 @@ mark-style Japanese Japán Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. A Kijelölés › Azonos › Kitöltőszín, Körvonalszín és Kitöltés és körvonal csak egy globális vagy direkt színminta azonos árnyalatát találja meg, nem bármely árnyalatát. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Megjeleníti a kezdőképernyőt, ha nincs megnyitott dokumentum; kikapcsolva az ablak üres marad, amíg a Kezdőképernyő gombra nem kattint. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Az objektumokat körvonalaikkal és alakmódosító effektusaikkal együtt méri a mérethez, a pozícióhoz és az igazításhoz; az árnyékokat, ragyogásokat és elmosásokat nem méri. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100%-os nagyításnál a dokumentum egy hüvelyke a kijelző egy hüvelykét tölti ki, vagy 96 képernyőpontot, ha a rendszer nem adja meg a kijelző méretét. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. 100%-os nagyításnál a dokumentum egy hüvelyke a kijelző egy hüvelykét tölti ki, vagy 96 képernyőpontot, ha a rendszer nem ad meg használható kijelzőméretet. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Ha a Kijelölés eszközzel duplán kattint egy csoportra, útvonalra vagy képre, az elkülönítő módban nyílik meg. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. A mintázatos kitöltések és körvonalak a grafikával együtt alakulnak át, hacsak egy átalakítás vagy az Átalakítás panel menüje mást nem választ. Live corner radii scale with the art, unless the scale chooses otherwise. Az élő sarkok sugara a grafikával együtt méreteződik, hacsak a méretezés mást nem választ. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ec6c655037..e389d8b129 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5119,7 +5119,7 @@ font-technology Variable Variabel Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Seleksi › Sama › Warna isian, Warna stroke, dan Isian & stroke hanya mencocokkan tint yang sama dari swatch global atau spot, bukan sembarang tint-nya. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Menampilkan layar Home saat tidak ada dokumen yang terbuka; saat nonaktif, jendela tetap kosong sampai Anda mengklik Home. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mengukur objek beserta stroke dan efek yang mengubah bentuknya untuk ukuran, posisi, dan perataan; bayangan, cahaya, dan kekaburan tidak diukur. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Pada zum 100%, satu inci dokumen mengisi satu inci layar, atau 96 titik layar bila sistem tidak melaporkan ukuran layar. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Pada zum 100%, satu inci dokumen mengisi satu inci layar, atau 96 titik layar bila sistem tidak melaporkan ukuran layar yang dapat dipakai. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Mengklik ganda grup, jalur, atau gambar dengan alat Seleksi membukanya dalam mode isolasi. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Isian dan stroke pola ikut bertransformasi dengan karya seni, kecuali transformasi atau menu panel Transformasi memilih lain. Live corner radii scale with the art, unless the scale chooses otherwise. Radius sudut dinamis ikut diskalakan dengan karya seni, kecuali penskalaan memilih lain. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 451efa2381..86c8940d87 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3364,7 +3364,7 @@ digits Malayalam Malayalam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selezione › Uguale › Colore riempimento, Colore traccia e Riempimento e traccia trovano solo la stessa tinta di un campione globale o di un colore spot, non qualsiasi sua tinta. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Mostra la schermata Home quando nessun documento è aperto; se disattivata, la finestra resta vuota finché non fai clic su Home. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Misura gli oggetti con le tracce e gli effetti che ne cambiano la forma per dimensioni, posizione e allineamento; ombre, bagliori e sfocature non vengono misurati. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Allo zoom del 100%, un pollice del documento occupa un pollice dello schermo, o 96 punti dello schermo se il sistema non ne indica le dimensioni. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Allo zoom del 100%, un pollice del documento occupa un pollice dello schermo, o 96 punti dello schermo se il sistema non ne indica dimensioni utilizzabili. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Un doppio clic su un gruppo, un tracciato o un'immagine con lo strumento Selezione lo apre in modalità isolamento. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. I riempimenti e le tracce con motivo si trasformano con la grafica, a meno che una trasformazione o il menu del pannello Trasforma scelga diversamente. Live corner radii scale with the art, unless the scale chooses otherwise. I raggi degli angoli dinamici si ridimensionano con la grafica, a meno che il ridimensionamento scelga diversamente. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index e1e9cf8bc4..cead28c43e 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3332,7 +3332,7 @@ mark-style Japanese 日本式 Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 選択 › 共通 › カラー (塗り)、カラー (線)、塗りと線は、グローバルスウォッチまたは特色スウォッチの同じ濃度だけを選び、ほかの濃度は選びません。 Shows the Home screen when no document is open; off, the window stays empty until you click Home. ドキュメントが開いていないときにホーム画面を表示します。オフのときは、ホームをクリックするまでウィンドウは空のままです。 Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. サイズ、位置、整列のために、線と形を変える効果を含めてオブジェクトを測ります。ドロップシャドウ、光彩、ぼかしは含めません。 - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100% 表示のとき、ドキュメントの 1 インチをディスプレイの 1 インチで表示します。システムがディスプレイのサイズを報告しない場合は 96 スクリーンポイントで表示します。 + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. 100% 表示のとき、ドキュメントの 1 インチをディスプレイの 1 インチで表示します。システムが使用できるディスプレイのサイズを報告しない場合は 96 スクリーンポイントで表示します。 Double-clicking a group, path or image with the Selection tool opens it in isolation mode. 選択ツールでグループ、パス、画像をダブルクリックすると、編集モードで開きます。 Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. 変形コマンドや変形パネルのメニューで別の指定をしない限り、パターンの塗りと線をアートワークと一緒に変形します。 Live corner radii scale with the art, unless the scale chooses otherwise. 拡大・縮小で別の指定をしない限り、ライブコーナーの半径をアートワークと一緒に拡大・縮小します。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 513b6ff533..ee4e1da69d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6506,7 +6506,7 @@ font-technology Variable ცვლადი Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. მონიშვნა › იგივე › შევსების ფერი, კონტურის ფერი და შევსება და კონტური პოულობს გლობალური ან სპოტ-ფერის ნიმუშის მხოლოდ იმავე ტონირებას და არა მის ნებისმიერ ტონირებას. Shows the Home screen when no document is open; off, the window stays empty until you click Home. აჩვენებს საწყის ეკრანს, როცა არცერთი დოკუმენტი არ არის გახსნილი; გამორთვისას ფანჯარა ცარიელი რჩება, „საწყის ეკრანზე“ დაწკაპუნებამდე. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. ზომის, პოზიციისა და სწორების დროს ობიექტებს ზომავს კონტურებითა და ფორმის შემცვლელი ეფექტებით; ჩრდილები, ნათება და გაბუნდოვნება არ იზომება. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100%-იან მასშტაბზე დოკუმენტის ერთი დუიმი ეკრანის ერთ დუიმს ავსებს, ან 96 ეკრანის პუნქტს, როცა სისტემა ეკრანის ზომას არ აცნობებს. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. 100%-იან მასშტაბზე დოკუმენტის ერთი დუიმი ეკრანის ერთ დუიმს ავსებს, ან 96 ეკრანის პუნქტს, როცა სისტემა ეკრანის გამოსადეგ ზომას არ აცნობებს. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. მონიშვნის ხელსაწყოთი ჯგუფზე, ტრაექტორიაზე ან გამოსახულებაზე ორჯერ დაწკაპუნება მას იზოლაციის რეჟიმში ხსნის. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. პატერნის შევსებები და კონტურები ნახატთან ერთად გარდაიქმნება, თუ გარდაქმნა ან გარდაქმნის პანელის მენიუ სხვას არ აირჩევს. Live corner radii scale with the art, unless the scale chooses otherwise. ცოცხალი კუთხეების რადიუსები ნახატთან ერთად მასშტაბირდება, თუ მასშტაბირება სხვას არ აირჩევს. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 84e309e056..ccff8c99f0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3321,7 +3321,7 @@ mark-style Japanese 일본식 Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 선택 › 동일 › 칠 색상, 선 색상, 칠 및 선은 전역 또는 별색 견본의 같은 색조만 찾고, 다른 색조는 찾지 않습니다. Shows the Home screen when no document is open; off, the window stays empty until you click Home. 열린 문서가 없을 때 홈 화면을 표시합니다. 끄면 홈을 클릭할 때까지 창이 비어 있습니다. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. 크기, 위치, 정렬을 위해 선과 모양을 바꾸는 효과를 포함하여 개체를 측정합니다. 그림자, 광선, 흐림 효과는 측정하지 않습니다. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 100% 확대/축소에서 문서의 1인치가 디스플레이의 1인치를 채우며, 시스템이 디스플레이 크기를 알려 주지 않으면 96 화면 포인트를 차지합니다. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. 100% 확대/축소에서 문서의 1인치가 디스플레이의 1인치를 채우며, 시스템이 사용할 수 있는 디스플레이 크기를 알려 주지 않으면 96 화면 포인트를 차지합니다. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. 선택 도구로 그룹, 패스 또는 이미지를 두 번 클릭하면 격리 모드로 엽니다. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. 변형 명령이나 변형 패널의 메뉴에서 달리 선택하지 않는 한, 패턴 칠과 선이 아트웍과 함께 변형됩니다. Live corner radii scale with the art, unless the scale chooses otherwise. 크기 조정에서 달리 선택하지 않는 한, 라이브 모퉁이 반지름이 아트웍과 함께 크기 조정됩니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4dbafaa5a5..4f957f65a4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5119,7 +5119,7 @@ font-technology Variable Variabel Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Selecteren › Zelfde › Vulkleur, Contourkleur en Vulling en contour vinden alleen dezelfde tint van een globaal of steunkleurstaal, niet elke tint ervan. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Toont het startscherm wanneer er geen document open is; uitgeschakeld blijft het venster leeg totdat u op Home klikt. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Meet objecten met hun contouren en vormveranderende effecten voor grootte, positie en uitlijning; schaduwen, gloed en vervagingen worden niet gemeten. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Bij 100% zoom vult één inch van het document één inch van het scherm, of 96 schermpunten als het systeem geen schermgrootte doorgeeft. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Bij 100% zoom vult één inch van het document één inch van het scherm, of 96 schermpunten als het systeem geen bruikbare schermgrootte doorgeeft. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dubbelklikken op een groep, pad of afbeelding met het gereedschap Selectie opent die in de isolatiemodus. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Patroonvullingen en -contouren transformeren mee met de illustratie, tenzij een transformatie of het menu van het deelvenster Transformeren anders kiest. Live corner radii scale with the art, unless the scale chooses otherwise. Dynamische hoekradii schalen mee met de illustratie, tenzij het schalen anders kiest. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 46d2cc120b..f36c82c07a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4648,7 +4648,7 @@ font-technology Variable Zmienne Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Zaznacz › Taki sam › Kolor wypełnienia, Kolor obrysu oraz Wypełnienie i obrys dopasowują tylko ten sam odcień globalnej lub dodatkowej próbki, a nie dowolny jej odcień. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Pokazuje stronę startową, gdy nie jest otwarty żaden dokument; po wyłączeniu okno pozostaje puste, dopóki nie klikniesz Strona startowa. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mierzy obiekty razem z obrysami i efektami zmieniającymi kształt na potrzeby rozmiaru, położenia i wyrównania; cienie, poświaty i rozmycia nie są mierzone. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Przy powiększeniu 100% jeden cal dokumentu wypełnia jeden cal ekranu albo 96 punktów ekranu, gdy system nie podaje rozmiaru ekranu. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Przy powiększeniu 100% jeden cal dokumentu wypełnia jeden cal ekranu albo 96 punktów ekranu, gdy system nie podaje użytecznego rozmiaru ekranu. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dwukrotne kliknięcie grupy, ścieżki lub obrazu narzędziem Zaznaczanie otwiera je w trybie izolacji. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Wypełnienia i obrysy wzorkiem przekształcają się razem z kompozycją, chyba że przekształcenie lub menu panelu Przekształć wybierze inaczej. Live corner radii scale with the art, unless the scale chooses otherwise. Promienie narożników dynamicznych skalują się razem z kompozycją, chyba że skalowanie wybierze inaczej. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 7e03fc77f0..7359c63c3b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2770,7 +2770,7 @@ digits Malayalam Malaiala Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Seleção › Igual › Cor de Preenchimento, Cor do Traçado e Preenchimento e Traçado encontram apenas o mesmo tom de uma amostra global ou de cor especial, não qualquer tom dela. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Mostra a tela Início quando nenhum documento está aberto; desativada, a janela fica vazia até você clicar em Início. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mede os objetos com seus traçados e efeitos que mudam a forma para tamanho, posição e alinhamento; sombras, brilhos e desfoques não são medidos. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Com zoom de 100%, uma polegada do documento ocupa uma polegada da tela, ou 96 pontos de tela quando o sistema não informa o tamanho da tela. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Com zoom de 100%, uma polegada do documento ocupa uma polegada da tela, ou 96 pontos de tela quando o sistema não informa um tamanho de tela utilizável. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Clicar duas vezes em um grupo, demarcador ou imagem com a ferramenta Seleção o abre no modo de isolamento. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Preenchimentos e traçados de padrão se transformam com a arte, a menos que uma transformação ou o menu do painel Transformar escolha outra coisa. Live corner radii scale with the art, unless the scale chooses otherwise. Os raios de canto dinâmicos mudam de escala com a arte, a menos que a escala escolha outra coisa. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 731d09bd06..007ed80f9e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3346,7 +3346,7 @@ digits Malayalam Малаялам Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. «Выделение › То же › Цвет заливки», «Цвет обводки» и «Заливка и обводка» находят только тот же оттенок глобального или плашечного образца, а не любой его оттенок. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Показывает начальный экран, когда нет открытых документов; если выключено, окно остаётся пустым, пока вы не нажмёте «Домой». Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Измеряет объекты с обводками и эффектами, меняющими форму, для размера, положения и выравнивания; тени, свечения и размытия не учитываются. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. При масштабе 100 % один дюйм документа занимает один дюйм дисплея или 96 экранных пунктов, если система не сообщает размер дисплея. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. При масштабе 100 % один дюйм документа занимает один дюйм дисплея или 96 экранных пунктов, если система не сообщает пригодный размер дисплея. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Двойной щелчок по группе, контуру или изображению инструментом «Выделение» открывает их в режиме изоляции. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Заливки и обводки узором трансформируются вместе с графикой, если трансформирование или меню панели «Трансформировать» не задаёт иное. Live corner radii scale with the art, unless the scale chooses otherwise. Радиусы динамических углов масштабируются вместе с графикой, если масштабирование не задаёт иное. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 597a5dbc1e..76bf7fc17f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3235,7 +3235,7 @@ digits Malayalam Malayalam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Markera › Samma › Fyllnadsfärg, Konturfärg och Fyllning och kontur hittar bara samma nyans av ett globalt färgprov eller en dekorfärg, inte vilken nyans som helst av det. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Visar startskärmen när inget dokument är öppet; när det är av förblir fönstret tomt tills du klickar på Start. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mäter objekt med deras konturer och formändrande effekter för storlek, position och justering; skuggor, glöd och oskärpa mäts inte. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Vid 100 % zoom fyller en tum av dokumentet en tum av skärmen, eller 96 skärmpunkter om systemet inte anger skärmens storlek. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Vid 100 % zoom fyller en tum av dokumentet en tum av skärmen, eller 96 skärmpunkter om systemet inte anger en användbar skärmstorlek. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dubbelklick på en grupp, en bana eller en bild med verktyget Markering öppnar den i isoleringsläge. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Mönsterfyllningar och -konturer transformeras med grafiken, om inte en transformering eller menyn i panelen Transformera väljer annat. Live corner radii scale with the art, unless the scale chooses otherwise. Dynamiska hörnradier skalas med grafiken, om inte skalningen väljer annat. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b4b8af414f..bb509d56b6 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3080,7 +3080,7 @@ digits Malayalam Malayalam Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Seçim › Aynı › Dolgu Rengi, Kontur Rengi ve Doldur ve Konturla yalnızca genel veya spot renk örneğinin aynı tonunu bulur, herhangi bir tonunu değil. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Hiçbir belge açık değilken Ana Sayfa ekranını gösterir; kapalıyken siz Ana Sayfa'ya tıklayana kadar pencere boş kalır. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Nesneleri boyut, konum ve hizalama için konturları ve şekil değiştiren efektleriyle birlikte ölçer; gölgeler, parlamalar ve bulanıklaştırmalar ölçülmez. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. %100 yakınlaştırmada belgenin bir inçi ekranın bir inçini kaplar; sistem ekran boyutunu bildirmezse 96 ekran noktası kaplar. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. %100 yakınlaştırmada belgenin bir inçi ekranın bir inçini kaplar; sistem kullanılabilir bir ekran boyutu bildirmezse 96 ekran noktası kaplar. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Seçim aracıyla bir gruba, yola veya görüntüye çift tıklamak onu yalıtım modunda açar. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Desen dolguları ve konturları, bir dönüşüm veya Dönüştür panelinin menüsü başka bir seçim yapmadıkça resimle birlikte dönüşür. Live corner radii scale with the art, unless the scale chooses otherwise. Canlı köşe yarıçapları, ölçekleme başka bir seçim yapmadıkça resimle birlikte ölçeklenir. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 1be9d21a56..fe18c0556a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3356,7 +3356,7 @@ digits Malayalam Малаялам Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. «Виділення › Те саме › Колір заливки», «Колір обведення» та «Заливка та обведення» знаходять лише той самий відтінок глобального або плашкового зразка, а не будь-який його відтінок. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Показує початковий екран, коли немає відкритих документів; якщо вимкнено, вікно лишається порожнім, доки ви не натиснете «Додому». Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Вимірює об’єкти з обведеннями та ефектами, що змінюють форму, для розміру, положення й вирівнювання; тіні, світіння та розмиття не враховуються. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. За масштабу 100 % один дюйм документа займає один дюйм дисплея або 96 екранних пунктів, якщо система не повідомляє розмір дисплея. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. За масштабу 100 % один дюйм документа займає один дюйм дисплея або 96 екранних пунктів, якщо система не повідомляє придатний розмір дисплея. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Подвійне клацання на групі, контурі або зображенні інструментом «Виділення» відкриває їх у режимі ізоляції. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Заливки й обведення візерунком трансформуються разом із графікою, якщо трансформування або меню панелі «Трансформувати» не задає іншого. Live corner radii scale with the art, unless the scale chooses otherwise. Радіуси динамічних кутів масштабуються разом із графікою, якщо масштабування не задає іншого. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5bc97afbae..bf64a5ac76 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3676,7 +3676,7 @@ mark-style Japanese Kiểu Nhật Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Vùng chọn › Giống nhau › Màu tô, Màu nét và Tô & Nét chỉ khớp với cùng sắc độ của một mẫu màu toàn cục hoặc màu pha, không phải mọi sắc độ của nó. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Hiển thị màn hình Trang chủ khi không có tài liệu nào mở; khi tắt, cửa sổ để trống cho đến khi bạn nhấp vào Trang chủ. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Đo đối tượng cùng với nét và các hiệu ứng thay đổi hình dạng cho kích thước, vị trí và căn chỉnh; bóng đổ, ánh sáng và làm mờ không được đo. - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. Ở mức thu phóng 100%, một inch của tài liệu chiếm một inch trên màn hình, hoặc 96 điểm màn hình khi hệ thống không báo kích thước màn hình. + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. Ở mức thu phóng 100%, một inch của tài liệu chiếm một inch trên màn hình, hoặc 96 điểm màn hình khi hệ thống không báo kích thước màn hình dùng được. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Nhấp đúp vào một nhóm, đường dẫn hoặc hình ảnh bằng công cụ Vùng chọn sẽ mở nó trong chế độ cô lập. Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Phần tô và nét họa tiết biến đổi cùng hình minh họa, trừ khi phép biến đổi hoặc menu của bảng Biến đổi chọn khác. Live corner radii scale with the art, unless the scale chooses otherwise. Bán kính góc động co giãn cùng hình minh họa, trừ khi phép co giãn chọn khác. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index fd591e2ff4..79986acba9 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3205,7 +3205,7 @@ digits Malayalam 马拉雅拉姆数字 Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 选择 › 相同 › 填色、描边颜色和填色和描边只匹配全局色板或专色色板的相同色调,而不是其任意色调。 Shows the Home screen when no document is open; off, the window stays empty until you click Home. 没有打开文档时显示主页屏幕;关闭时,窗口保持空白,直到你点击主页。 Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. 在尺寸、位置和对齐中按对象的描边和改变形状的效果测量对象;阴影、发光和模糊不计入测量。 - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 缩放为 100% 时,文档的一英寸占显示器上的一英寸;系统未报告显示器尺寸时占 96 个屏幕点。 + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. 缩放为 100% 时,文档的一英寸占显示器上的一英寸;系统未报告可用的显示器尺寸时占 96 个屏幕点。 Double-clicking a group, path or image with the Selection tool opens it in isolation mode. 用选择工具双击编组、路径或图像时,会在隔离模式中打开它。 Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. 图案填色和描边随图稿一起变换,除非变换命令或变换面板的菜单另有选择。 Live corner radii scale with the art, unless the scale chooses otherwise. 实时转角半径随图稿一起缩放,除非缩放命令另有选择。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a7136b8c76..0d8417a001 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4654,7 +4654,7 @@ digits Malayalam 馬來亞拉姆數字 Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. 選取 › 相同 › 填色顏色、筆畫顏色和填色與筆畫只符合全域色票或特別色色票的相同色調,而不是其任意色調。 Shows the Home screen when no document is open; off, the window stays empty until you click Home. 沒有開啟文件時顯示首頁畫面;關閉時,視窗保持空白,直到你按下首頁。 Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. 在尺寸、位置和對齊中依物件的筆畫和改變形狀的效果測量物件;陰影、光暈和模糊不計入測量。 - At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size. 縮放為 100% 時,文件的一英吋佔顯示器上的一英吋;系統未回報顯示器尺寸時佔 96 個螢幕點。 + At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size. 縮放為 100% 時,文件的一英吋佔顯示器上的一英吋;系統未回報可用的顯示器尺寸時佔 96 個螢幕點。 Double-clicking a group, path or image with the Selection tool opens it in isolation mode. 用選取工具按兩下群組、路徑或影像時,會在隔離模式中開啟它。 Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. 圖樣填色和筆畫隨圖稿一起變形,除非變形指令或變形面板的選單另有選擇。 Live corner radii scale with the art, unless the scale chooses otherwise. 即時轉角半徑隨圖稿一起縮放,除非縮放指令另有選擇。 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 7eda9e95ca..ef79a20221 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -461,6 +461,7 @@ fn run_ui_part5(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { v.zoom = next_zoom(v.zoom, up, print); + v.fit_zoom = None; if let Some(c) = focus { v.center = c; } @@ -479,6 +480,8 @@ fn run_ui_part5(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { v.zoom = z.clamp(0.0313, 640.0); + // A percentage, not a fit: the first reading of the display keeps it. + v.fit_zoom = None; v.fitted = true; if let Some(c) = center { v.center = c; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 920331ea39..d0f09d63d0 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -485,7 +485,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "view.actualSize", "Actual Size", "Cmd+1", - "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills an inch of the display that shows the window, measured from the physical size the system reports for it, or 96 screen points where it reports none; the same at every UI Scaling", + "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills an inch of the display that shows the window, measured from the physical size the system reports for it, or 96 screen points where it reports none or a size no display has; the same at every UI Scaling", ), ("view.setZoom", "Set Zoom", "", "{zoom: percent, center?: [x,y]}"), ( diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index 0593304e0b..fe1d5bc81b 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -30,7 +30,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ), ( "displayPrintSize", - "At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no display size.", + "At 100% zoom, one inch of the document fills an inch of the display, or 96 screen points where the system reports no usable display size.", ), ("doubleClickToIsolate", "Double-clicking a group, path or image with the Selection tool opens it in isolation mode."), ( diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 751cd87584..133a3ec7e3 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -142,15 +142,19 @@ use std::sync::mpsc::Sender; /// reference density that display scaling is set against (a CSS inch). pub const REFERENCE_PPI: f64 = 96.0; -/// The densities a measured display may have, in screen points per inch. A size outside them is -/// a wrong report (a projector or television that gives its aspect ratio as its size, or none). +/// The pixel densities a measured display may have, in pixels per inch, before the display scale +/// divides them into screen points. A size outside them is a wrong report (a projector or +/// television that gives its aspect ratio as its size, or none). pub const SCREEN_PPI_RANGE: std::ops::RangeInclusive = 30.0..=1000.0; /// The screen points one inch takes at 100% zoom: `None` with Preferences › General › Display /// Print Size at 100% Zoom off, else the measured density of the display (`screen_ppi`, -/// [`crate::Services::screen_ppi`]), or [`REFERENCE_PPI`] when the display has none. +/// [`crate::Services::screen_ppi`]), or [`REFERENCE_PPI`] when the display has none. A measured +/// density is taken when it is finite and positive: the host checks the display's pixels against +/// [`SCREEN_PPI_RANGE`] before the display scale divides them into points, so a point density can +/// fall outside that range. pub fn print_ppi(display_print_size: bool, screen_ppi: Option) -> Option { - display_print_size.then(|| screen_ppi.filter(|p| SCREEN_PPI_RANGE.contains(p)).unwrap_or(REFERENCE_PPI)) + display_print_size.then(|| screen_ppi.filter(|p| p.is_finite() && *p > 0.0).unwrap_or(REFERENCE_PPI)) } /// The preset zoom stops, in percent. @@ -1646,7 +1650,7 @@ mod tests { /// #9051: with Display Print Size on, 100% follows the measured density of the display, so an /// inch of the document takes as many screen points as an inch of that display holds. A - /// density outside the range a display can have counts as no measurement. + /// density that is not finite and positive counts as no measurement. #[test] fn print_size_follows_the_displays_measured_density() { assert_eq!(print_ppi(false, Some(127.0)), None, "the preference off ignores the display"); @@ -1654,9 +1658,11 @@ mod tests { assert!(zoom_baseline(dense) > zoom_baseline(print_ppi(true, None)), "a denser display than the reference zooms 100% further in"); assert!(zoom_baseline(sparse) < zoom_baseline(print_ppi(true, None)), "a sparser one zooms it out"); assert!((zoom_baseline(dense) * 72.0 - 127.0).abs() < 1e-9, "an inch of the document fills an inch of the display"); - for wrong in [Some(0.0), Some(-5.0), Some(f64::NAN), Some(f64::INFINITY), Some(5000.0), None] { + for wrong in [Some(0.0), Some(-5.0), Some(f64::NAN), Some(f64::INFINITY), Some(f64::NEG_INFINITY), None] { assert_eq!(print_ppi(true, wrong), print_ppi(true, None), "{wrong:?} is no measurement"); } + assert_eq!(print_ppi(true, Some(23.15)), Some(23.15), "a display at a large scale factor has few points to an inch"); + assert_eq!(print_ppi(true, Some(1600.0)), Some(1600.0), "and one at a scale below 1 many"); assert_eq!(zoom_label(zoom_from_display_percent(100.0, dense), dense), "100%"); let thin = print_ppi(true, Some(40.0)); assert!(next_zoom(0.0313, false, thin) >= 0.0313, "the last stop down stays in the zoom range"); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e32dc77d7e..c0ba336669 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1292,7 +1292,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen rubber band after a smooth anchor:** the preview segment to the pointer is the curve a click there adds, leaving the last anchor along its outgoing handle and arriving at the new corner anchor without a handle, so the segment keeps its shape when the anchor is placed, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes. Before, the preview was a different curve, and the segment changed shape at the click (#8296, in part; `pen::tests::rubber_band_is_the_segment_a_click_adds`); scores and estimates unchanged. - **Pen rubber band over an anchor a click ends on:** over the path's first anchor, the preview segment ends on that anchor, as the closing segment does; over an end of another open path, it ends on that end and arrives along the end's own handle, as the joining segment does. The preview picks these anchors at the pointer before snapping, as a press does. Before, the preview ended at the pointer and arrived without a handle, so the segment moved by up to the pick tolerance at the click, and changed shape when the other end was smooth (#8296, in part; the `pen_rubber_band` tests in `engine/tests/it`); scores and estimates unchanged. - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (on by default, as [the help page](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes; in VectorCraft, View › Actual Size shows one document inch in an inch of the display that shows the document's window, measured from the physical size the system reports for that display, or 96 screen points where it reports none; VectorCraft's own rules: a document in a floating window counts from that window's display, where the help page names only the primary monitor, and the preference also applies in Pixel Preview, which the help page leaves out; off, one document point per screen point; `view.actualSize` / `prefs.set`, #394, #9051). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). + - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (on by default, as [the help page](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes; in VectorCraft, View › Actual Size shows one document inch in an inch of the display that shows the document's window, measured from the physical size the system reports for that display, or 96 screen points where it reports none or a size no display has; VectorCraft's own rules: a document in a floating window counts from that window's display, where the help page names only the primary monitor, and the preference also applies in Pixel Preview, which the help page leaves out; off, one document point per screen point; `view.actualSize` / `prefs.set`, #394, #9051). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). - Preferences › General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default; dimmed while Zoom with Mouse Wheel is on): while Zoom with Mouse Wheel is off, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer, and once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. Under either wheel preference, Cmd/Ctrl with a touchpad zooms about the pointer. - Preferences › Type › Highlight Substituted Fonts (on by default) paints pink behind text drawn in a substitute for a missing font in every document, and turning it off removes that highlight everywhere (`prefs.set highlightSubstitutedFonts`); Document Setup keeps Highlight Substituted Glyphs ([help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/edit-text-without-replacing-missing-fonts.html)). - Preferences › User Interface › UI Scaling scales the interface ([help](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/modify-workspaces.html)). VectorCraft's own rule is that it leaves the art's size alone: at a given zoom a document point covers the same device pixels at every UI Scaling, so View › Actual Size shows the art at the same size whatever the UI Scaling. A click, a pinch or wheel zoom about the pointer, a pan, the Zoom tool's marquee, Fit, tiled panes, Pixel Preview and the Navigator's view box use the same mapping. Evidence: `canvas::tests_ui_scaling`, `tiled_documents_fit_their_panes_at_every_ui_scaling`, `the_view_box_outlines_the_canvas_at_every_ui_scaling`. Scores unchanged. From f9679bf92b6cd16c6d9fbbb02cc04bce46baff8e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:05:40 -0800 Subject: [PATCH 042/101] Overprint Preview: the canvas around the artboards is white, with no artboard shadows In Overprint Preview, and in Separations Preview, which turns it on, the canvas outside the artboards was drawn in the pasteboard color. It is now white, and the artboards draw no drop shadows. Turning the preview off brings back the pasteboard color and the shadows. - With a display profile, translucent art around the artboards is blended with the white canvas before the conversion, as it is on the paper. - Artboard names and the ruler origin's crosshair use the dark gray they use in Outline. Where the Artboard tool's Fade Region Outside Artboard darkens a white canvas, in Overprint Preview and in Outline, the names and the crosshair are black. - Over a white canvas the Artboard tool's names of its selected artboards are dark blue instead of the selection blue. - proof::overprint_preview_on() reads the proof view without copying it, since the canvas now asks for it several times a frame. - The canvas tests that check the pasteboard, the names or the display profile's frames hold the proof view while they run, and the tests that change it outside the Proof Setup tests take it for writing. - docs/mcp.md, docs/target-app-parity.md and docs/ui-parity.md describe the white canvas. --- crates/render/src/proof.rs | 3 +- crates/ui-egui/src/canvas.rs | 66 ++++++-- crates/ui-egui/src/canvas/panes.rs | 2 +- crates/ui-egui/src/canvas/tests.rs | 188 ++++++++++++++++++++++ crates/ui-egui/src/control/tests.rs | 1 + crates/ui-egui/src/dialogs/proof_setup.rs | 6 + crates/ui-egui/src/display_profile.rs | 30 +++- docs/mcp.md | 7 +- docs/target-app-parity.md | 4 +- docs/ui-parity.md | 1 + 10 files changed, 282 insertions(+), 26 deletions(-) diff --git a/crates/render/src/proof.rs b/crates/render/src/proof.rs index dd7d28eb23..3d5da3ac3c 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -619,6 +619,5 @@ pub fn active_proof() -> Option { /// Whether [`RenderOptions::overprint_preview`] should be on (Separations Preview implies it). pub fn overprint_preview_on() -> bool { - let v = view(); - v.overprint || v.separations.is_some() + VIEW.read().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|v| v.overprint || v.separations.is_some()) } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b366665d4..095401a866 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -431,7 +431,8 @@ 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 mut overlays = selection_visuals(app, &painter, &xf, (hidden_chars, selection_marks, hover_still), revolve_edit, view_info); + names_on_a_white_canvas(app, &mut overlays); 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); @@ -865,7 +866,7 @@ fn ruler_bands(app: &VectorcraftApp, ui: &Ui, xf: &Xf, (full, rect): (egui::Rect let painter = ui.painter_at(rect); if let Some(origin) = origin_preview { let at = xf.to_screen(origin); - let color = dim_on_canvas(t, app.outline_view()); + let color = dim_on_canvas(app, t, (app.outline_view(), fades_outside_artboards(app))); painter.line_segment([pos2(at.x, rect.top()), pos2(at.x, rect.bottom())], Stroke::new(1.0, color)); painter.line_segment([pos2(rect.left(), at.y), pos2(rect.right(), at.y)], Stroke::new(1.0, color)); } @@ -1296,12 +1297,14 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { const OUTLINE_CANVAS: Color32 = Color32::WHITE; /// The color of the artboards' names and the ruler origin's crosshair in Outline, on -/// [`OUTLINE_CANVAS`]. +/// [`OUTLINE_CANVAS`], and in Overprint Preview, on its white canvas. const OUTLINE_DIM: Color32 = Color32::from_gray(0x4b); /// The pasteboard and the artboards' shadows and paper of document `st`, or in Outline (`outline`) /// the whole canvas in [`OUTLINE_CANVAS`], with no paper drawn for the artboards: no Simulate /// Colored Paper color, no artboard background color, and no paper with View › Hide Artboards. +/// In Overprint Preview (and Separations Preview, which turns it on) the canvas outside the +/// artboards is white instead of the pasteboard color, and the artboards draw no shadows. fn paint_paper( app: &VectorcraftApp, st: &vectorcraft_engine::DocState, @@ -1323,11 +1326,13 @@ fn paint_paper( // An artboard with a background color draws its paper in that color. With Simulate Colored Paper // on, the canvas multiplies it with the paper color: each sRGB channel is artboard × paper / 255, // rounded. The transparency grid, while it shows, covers it as it covers the others. - painter.rect_filled(rect, 0.0, t.pasteboard); // The paper and the transparency grid are document colors: they go through the display - // profile as the art does. The pasteboard and the shadows are the interface's. + // profile as the art does. The pasteboard and the shadows are the interface's. Overprint + // Preview's white canvas is white paper, so it goes through the profile too. let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); let on_display = |c: Color32| crate::display_profile::color32(display.as_deref(), c); + let overprint = vectorcraft_render::proof::overprint_preview_on(); + painter.rect_filled(rect, 0.0, if overprint { on_display(Color32::WHITE) } else { t.pasteboard }); if !shows_artboards(app) { // View › Hide Artboards: no edges and no pasteboard, the whole canvas paper (#4038). painter.rect_filled(rect, 0.0, on_display(paper_color(&doc.setup))); @@ -1338,9 +1343,12 @@ fn paint_paper( for ab in &doc.artboards { let q = xf.quad(ab.rect); // Hard 2 pt drop shadow, right and bottom (measured: #4d4d4d then #565656 on #606060). - let shift = |d: f32| q.iter().map(|p| *p + vec2(d, d)).collect::>(); - painter.add(Shape::convex_polygon(shift(2.0), Color32::from_black_alpha(26), Stroke::NONE)); - painter.add(Shape::convex_polygon(shift(1.0), Color32::from_black_alpha(52), Stroke::NONE)); + // Overprint Preview draws no shadows. + if !overprint { + let shift = |d: f32| q.iter().map(|p| *p + vec2(d, d)).collect::>(); + painter.add(Shape::convex_polygon(shift(2.0), Color32::from_black_alpha(26), Stroke::NONE)); + painter.add(Shape::convex_polygon(shift(1.0), Color32::from_black_alpha(52), Stroke::NONE)); + } match &grid { Some((tex, cell)) => checker(painter, &q, ab.rect, xf.zoom, tex.id(), *cell), None => { @@ -1380,7 +1388,8 @@ fn backdrop(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, outline: bo let paper = paper_color(setup); let b = if shows_artboards(app) { crate::display_profile::Backdrop { - everywhere: None, + // In Overprint Preview the canvas around the artboards is white paper. + everywhere: vectorcraft_render::proof::overprint_preview_on().then_some([255; 3]), artboards: st.doc.artboards.iter().map(|ab| (ab.rect, rgb(artboard_paper(ab, paper)))).collect(), grid: shows_transparency_grid(st).then(|| (setup.grid_colors.map(|c| rgb(crate::panels::c32(&c))), setup.grid_size.cell())), } @@ -1557,13 +1566,44 @@ fn artboard_outlines(app: &VectorcraftApp, ui: &Ui, painter: &egui::Painter, xf: let tool_selected = artboards::tool_labelled(app); let editing_name = ui.data(|d| d.get_temp::(name_edit_id()).map(|e| e.index)); let unlabelled = |i: usize| editing_name == Some(i) || u64::try_from(i).ok().is_some_and(|idx| tool_selected.contains(&idx)); - artboard_edges(app, doc, (painter, xf, t), (active_ab, dim_on_canvas(t, app.outline_view())), unlabelled); + artboard_edges(app, doc, (painter, xf, t), (active_ab, dim_on_canvas(app, t, (app.outline_view(), fades_outside_artboards(app)))), unlabelled); } /// The color of the artboards' names and the ruler origin's crosshair over the pasteboard, or over -/// [`OUTLINE_CANVAS`] in Outline (`outline`). -fn dim_on_canvas(t: &Tokens, outline: bool) -> Color32 { - if outline { OUTLINE_DIM } else { t.text_dim } +/// [`OUTLINE_CANVAS`] in Outline (`outline`), or over Overprint Preview's white canvas while the +/// artboards show. Over a white canvas that Fade Region Outside Artboard darkens (`faded`), they +/// are black. +fn dim_on_canvas(app: &VectorcraftApp, t: &Tokens, (outline, faded): (bool, bool)) -> Color32 { + match (white_canvas(app, outline), faded) { + (true, true) => Color32::BLACK, + (true, false) => OUTLINE_DIM, + (false, _) => t.text_dim, + } +} + +/// The canvas outside the artboards is white: in Outline (`outline`), and in Overprint Preview +/// while the artboards show. +fn white_canvas(app: &VectorcraftApp, outline: bool) -> bool { + outline || (vectorcraft_render::proof::overprint_preview_on() && shows_artboards(app)) +} + +/// The color of the Artboard tool's names of its selected artboards over a white canvas, faded by +/// Fade Region Outside Artboard or not: a dark blue. +const SELECTED_NAME_ON_WHITE: [u8; 3] = [0x1a, 0x2b, 0x59]; + +/// Over a white canvas ([`white_canvas`]), the labels among `overlays` that name an artboard (the +/// Artboard tool's names of its selected artboards) draw in [`SELECTED_NAME_ON_WHITE`]. +fn names_on_a_white_canvas(app: &VectorcraftApp, overlays: &mut [Overlay]) { + if !white_canvas(app, app.outline_view()) { + return; + } + for o in overlays { + if let Overlay::Label { text, color, .. } = o + && artboards::names_an_artboard(text) + { + *color = SELECTED_NAME_ON_WHITE; + } + } } /// The edges, bleeds, marks and names of `doc`'s artboards, `active_ab` the active one, the names diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 63d89f2be2..54622c48bd 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -585,7 +585,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look); } if shows_artboards(app) { - artboard_edges(app, &st.doc, (&painter, &xf, &t), (v.artboard, dim_on_canvas(&t, v.outline)), |_| false); + artboard_edges(app, &st.doc, (&painter, &xf, &t), (v.artboard, dim_on_canvas(app, &t, (v.outline, false))), |_| false); } if app.ui.view.guides_shown() { guides_of(app, st, (&painter, &xf, &t), rect); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 1922842acd..88b45a8a0f 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3335,6 +3335,7 @@ fn pixel_preview_shows_the_document_pixels() { #[test] fn the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on() { use crate::display_profile::{Found, Reading}; + let _view = crate::dialogs::proof_setup::tests::keeping_the_proof_view(); let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); @@ -3515,6 +3516,88 @@ fn translucent_art_over_the_paper() { assert!(app.canvas.key.as_ref().is_some_and(|k| k.outline && k.backdrop.is_none())); } +/// With a display profile, in Overprint Preview translucent art around the artboards is blended +/// with the white canvas before the conversion, as art over the paper is. With the preview off it +/// converts alone, over the pasteboard. +#[test] +fn translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas() { + let _view = crate::dialogs::proof_setup::tests::changing_the_proof_view(); + vectorcraft_color::cms::with_active(vectorcraft_color::cms::active(), translucent_art_around_the_artboards); +} + +fn translucent_art_around_the_artboards() { + use crate::display_profile::{Found, Reading}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.canvas.worker_started = true; // every frame on this thread + // Left of the artboard. + let outside = app.run("shape.rectangle", json!({"x": -60, "y": 100, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [outside], "color": "#00ff00"})).unwrap(); + app.run("transparency.set", json!({"ids": [outside], "opacity": 50})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let ctx = egui::Context::default(); + // The whole art raster one frame uploads: its width and its pixels. + let upload = |app: &mut VectorcraftApp| -> Option<(usize, Vec)> { + let (_, mut delta) = frame_output(app, &ctx); + let art = app.canvas.texture.as_ref()?.id(); + let up = delta.set.iter().find(|e| e.0.eq(&art)).and_then(|e| e.1.last()).filter(|d| d.pos.is_none()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + (img.width(), img.pixels.clone()) + }); + delta.clear(); + up + }; + upload(&mut app).expect("the first frame"); + let v = app.view_mut().unwrap(); + (v.zoom, v.center) = (1.0, Point::new(120.0, 150.0)); + upload(&mut app).expect("the view at 100%"); + let p3 = crate::display_profile::tests::p3(); + let t = vectorcraft_color::cms::display::DisplayTransform::from_icc(&p3).unwrap(); + app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } }); + upload(&mut app).expect("drawn again, converted"); + let white = t.apply8([255; 3]); + let over = |c: egui::Color32, under: [u8; 3]| { + let k = 255 - u32::from(c.a()); + [0, 1, 2].map(|i| u32::from(c.to_array()[i]) + (u32::from(under[i]) * k + 127) / 255) + }; + let plain = |s: egui::Color32| { + let mut px = s.to_array(); + t.apply_premultiplied(&mut px); + egui::Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3]) + }; + // The pixel at the translucent rectangle's center, in sRGB (the display profile's preference + // off) and as the canvas shows it (on). + let pixel = |app: &mut VectorcraftApp| { + app.session.prefs.monitor_profile_display = false; + let (width, srgb) = upload(app).expect("drawn in sRGB"); + let key = app.canvas.key.clone().unwrap(); + let view = View { zoom: key.zoom, center: Point::new(key.cx, key.cy), rotation: key.rot, ..View::default() }; + let (_, _, view) = frame_view(None, (key.w, key.h), &view, key.ppp); + let at = view * Point::new(-40.0, 120.0); + let at = at.y as usize * width + at.x as usize; + app.session.prefs.monitor_profile_display = true; + let (_, shown) = upload(app).expect("drawn again, converted"); + (srgb[at], shown[at], app.canvas.key.clone().unwrap()) + }; + let (s, c, key) = pixel(&mut app); + assert!((50..=205).contains(&s.a()), "the 50% fill: {s:?}"); + assert!(key.backdrop.as_ref().is_some_and(|b| b.everywhere.is_none()), "Preview: the pasteboard is no paper"); + assert_eq!(c, plain(s), "over the pasteboard the art converts alone"); + app.run("view.overprintPreview", json!({"on": true})).unwrap(); + let (s, c, key) = pixel(&mut app); + assert!((50..=205).contains(&s.a()), "the 50% fill: {s:?}"); + assert_eq!(key.backdrop.as_ref().and_then(|b| b.everywhere), Some([255; 3]), "the white canvas is paper"); + let k = 255 - u32::from(s.a()); + let mix = [0, 1, 2].map(|j| (u32::from(s.to_array()[j]) + (255 * k + 127) / 255).min(255) as u8); + let (want, got) = (t.apply8(mix), over(c, white)); + assert!((0..3).all(|j| got[j].abs_diff(u32::from(want[j])) <= 1), "{got:?} shown, {want:?} wanted"); + // The test tells the two apart: the fill converted alone shows another color over the white canvas. + let alone = over(plain(s), white); + assert!((0..3).any(|j| alone[j].abs_diff(got[j]) > 2), "{alone:?} and {got:?}"); +} + /// View › Hide Template (#2000): a template layer's art leaves the canvas, and Show Template /// draws it again, dimmed as before; each re-renders at once. #[test] @@ -6705,6 +6788,7 @@ fn canvas_look(app: &mut VectorcraftApp, ctx: &egui::Context) -> (Vec, /// Preview the pasteboard keeps its color and the artboards their white paper. #[test] fn outline_draws_on_a_white_canvas_with_artboards_as_edges() { + let _view = crate::dialogs::proof_setup::tests::keeping_the_proof_view(); let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); for brightness in crate::theme::Brightness::ALL { @@ -6744,6 +6828,7 @@ fn outline_draws_on_a_white_canvas_with_artboards_as_edges() { /// artboard's color and the paper color over the whole canvas. #[test] fn outline_draws_no_colored_paper() { + let _view = crate::dialogs::proof_setup::tests::keeping_the_proof_view(); let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); { @@ -6778,11 +6863,111 @@ fn outline_draws_no_colored_paper() { assert_eq!(edges, 0); } +/// In Overprint Preview, and in Separations Preview, which turns it on, the canvas outside the +/// artboards is white instead of the pasteboard color in every interface brightness, the artboards +/// draw no shadows, and their names draw in the dark gray that shows on white. Where the Artboard +/// tool darkens the canvas, the names are black and the tool's names of its selected artboards dark +/// blue. The artboards keep their paper and edges. Turning it off brings back the pasteboard, the +/// shadows and the theme's names. +#[test] +fn overprint_preview_draws_a_white_canvas_without_shadows() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + // The filled shapes laid over an artboard moved down and right, as a shadow is. + let shadows = |app: &mut VectorcraftApp, ctx: &egui::Context| { + let s = shapes(app, ctx); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let quads: Vec> = app.session.active().unwrap().doc.artboards.iter().map(|a| xf.quad(a.rect).to_vec()).collect(); + let moved = |p: &[Pos2]| { + quads.iter().any(|q| { + let d = p.first().zip(q.first()).map(|(a, b)| *a - *b); + d.is_some_and(|d| { + d.x > 0.5 && (d.x - d.y).abs() < 0.01 && q.len() == p.len() && q.iter().zip(p).all(|(a, b)| (*a + d - *b).length() < 0.01) + }) + }) + }; + s.iter().filter(|s| matches!(s, Shape::Path(p) if p.fill != Color32::TRANSPARENT && moved(&p.points))).count() + }; + let rgb = |[r, g, b]: [u8; 3]| Color32::from_rgb(r, g, b); + let (selected_blue, dark_blue) = (rgb(vectorcraft_tools::xform::BLUE), rgb(SELECTED_NAME_ON_WHITE)); + let _view = crate::dialogs::proof_setup::tests::changing_the_proof_view(); + for brightness in crate::theme::Brightness::ALL { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, brightness); + let t = Tokens::get(&ctx); + assert_ne!(t.pasteboard, Color32::WHITE, "{brightness:?}"); + let steps = [ + ("view.overprintPreview", false), + ("view.overprintPreview", true), + ("view.overprintPreview", false), + ("view.separationsPreview", true), + ("view.separationsPreview", false), + ]; + for (command, on) in steps { + let case = format!("{brightness:?} {command} {on}"); + app.run(command, json!({"on": on})).unwrap(); + assert_eq!(vectorcraft_render::proof::overprint_preview_on(), on, "{case}"); + let (covers, papers, edges, names) = canvas_look(&mut app, &ctx); + assert_eq!(papers, [Color32::WHITE; 2], "{case}: the artboards keep their paper"); + assert_eq!(edges, 2, "{case}"); + if on { + assert_eq!(covers.last(), Some(&Color32::WHITE), "{case}: the canvas is white"); + assert!(!covers.contains(&t.pasteboard), "{case}: no pasteboard: {covers:?}"); + assert_eq!(shadows(&mut app, &ctx), 0, "{case}: no artboard shadows"); + assert_eq!(names, [OUTLINE_DIM; 2], "{case}: names readable on white"); + // The Artboard tool darkens the canvas around the artboards (Fade Region Outside + // Artboard) and labels its selected artboard itself: the other artboard's name is + // black, and the tool's name dark blue. + app.select_tool("artboard"); + let (_, _, _, names) = canvas_look(&mut app, &ctx); + assert!(names.contains(&Color32::BLACK), "{case}: names readable on the faded canvas: {names:?}"); + assert!(names.contains(&dark_blue), "{case}: {names:?}"); + assert!(!names.contains(&OUTLINE_DIM) && !names.contains(&selected_blue), "{case}: {names:?}"); + app.select_tool("selection"); + } else { + assert_eq!(covers.last(), Some(&t.pasteboard), "{case}: the pasteboard"); + assert!(shadows(&mut app, &ctx) > 0, "{case}: the artboards' shadows"); + assert_eq!(names, [t.text_dim; 2], "{case}"); + // Over the pasteboard the Artboard tool's name keeps its blue. + app.select_tool("artboard"); + let (_, _, _, names) = canvas_look(&mut app, &ctx); + assert!(names.contains(&selected_blue), "{case}: {names:?}"); + app.select_tool("selection"); + } + } + } +} + +/// In Outline, where the Artboard tool's Fade Region Outside Artboard darkens the white canvas, +/// the artboards' names are black and the tool's names of its selected artboards dark blue. With +/// Fade Region Outside Artboard off, the names keep Outline's dark gray. +#[test] +fn outline_names_show_on_the_faded_canvas() { + let _view = crate::dialogs::proof_setup::tests::keeping_the_proof_view(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, crate::theme::Brightness::Dark); + app.view_mut().unwrap().outline = true; + app.select_tool("artboard"); + assert!(app.session.prefs.fade_region_outside_artboard, "on by default"); + let [r, g, b] = SELECTED_NAME_ON_WHITE; + let dark_blue = Color32::from_rgb(r, g, b); + let (_, _, _, names) = canvas_look(&mut app, &ctx); + assert!(names.contains(&Color32::BLACK) && names.contains(&dark_blue), "{names:?}"); + assert!(!names.contains(&OUTLINE_DIM), "{names:?}"); + app.session.prefs.fade_region_outside_artboard = false; + let (_, _, _, names) = canvas_look(&mut app, &ctx); + assert!(names.contains(&OUTLINE_DIM) && names.contains(&dark_blue), "{names:?}"); + assert!(!names.contains(&Color32::BLACK), "{names:?}"); +} + /// A split-view pane or floating window draws its own view's Outline, whatever the current view /// shows: the white canvas and dark gray artboard names in Outline, and the pasteboard and the /// theme's names in Preview. #[test] fn a_pane_draws_its_own_views_outline() { + let _view = crate::dialogs::proof_setup::tests::keeping_the_proof_view(); let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); crate::doc_windows::new_window(&mut app).unwrap(); @@ -6823,6 +7008,7 @@ fn a_pane_draws_its_own_views_outline() { #[test] fn a_pane_blends_translucent_art_before_the_display_profile() { use crate::display_profile::{Found, Reading}; + let _view = crate::dialogs::proof_setup::tests::keeping_the_proof_view(); let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); let half = app.run("shape.rectangle", json!({"x": 50, "y": 25, "width": 100, "height": 50})).unwrap()["id"].clone(); @@ -6892,6 +7078,7 @@ fn a_pane_blends_translucent_art_before_the_display_profile() { #[test] fn the_ruler_origin_crosshair_shows_on_the_outline_canvas() { use egui::Event; + let _view = crate::dialogs::proof_setup::tests::keeping_the_proof_view(); for outline in [false, true] { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); @@ -13921,6 +14108,7 @@ fn the_task_bar_stays_up_through_a_click_and_gives_way_to_a_drag() { /// the Artboard tool still shows them. #[test] fn hidden_artboards_leave_a_paper_canvas_without_edges() { + let _view = crate::dialogs::proof_setup::tests::keeping_the_proof_view(); let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 96c4880d39..5be51f84a6 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -1257,6 +1257,7 @@ fn menu_dialogs_open_after_a_merge_on_another_thread() { /// leave the view off, so they apply it by command id without giving the documents new revisions. #[test] fn panels_that_redraw_apply_a_merge_on_another_thread_first() { + let _view = crate::dialogs::proof_setup::tests::changing_the_proof_view(); let cases = [ ("view.separationsPreview", json!({"on": false})), ("view.overprintPreview", json!({"on": false})), diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs index 735fafaaef..b0b772f316 100644 --- a/crates/ui-egui/src/dialogs/proof_setup.rs +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -521,6 +521,12 @@ pub(crate) mod tests { VIEW.read().unwrap_or_else(|e| e.into_inner()) } + /// Lets a test elsewhere change the proof view: the tests that change or keep it wait while the + /// guard lives, and dropping it puts back the default view. + pub(crate) fn changing_the_proof_view() -> impl Drop { + DefaultView::new() + } + fn frame(app: &mut VectorcraftApp, ctx: &egui::Context) { let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); out.textures_delta.clear(); diff --git a/crates/ui-egui/src/display_profile.rs b/crates/ui-egui/src/display_profile.rs index a1acf8ebbe..b4b9ed2d6c 100644 --- a/crates/ui-egui/src/display_profile.rs +++ b/crates/ui-egui/src/display_profile.rs @@ -273,7 +273,8 @@ pub(crate) fn convert(t: Option<&DisplayTransform>, pixels: &mut [u8]) { /// The pasteboard and Outline's white canvas are interface colors and are not part of it. #[derive(Clone, Debug, PartialEq)] pub struct Backdrop { - /// View › Hide Artboards: the sRGB color of the paper that covers the whole canvas. + /// The sRGB color of the paper where no artboard is: with View › Hide Artboards the paper that + /// covers the whole canvas, and in Overprint Preview the white canvas around the artboards. pub(crate) everywhere: Option<[u8; 3]>, /// The artboards in the order they are drawn (the last on top), each with its paper's sRGB color. pub(crate) artboards: Vec<(Rect, [u8; 3])>, @@ -430,9 +431,10 @@ impl<'a> Over<'a> { } } - /// The paper at pixel `i` of the row at height `y`, whose artboard on top is `owner`. + /// The paper at pixel `i` of the row at height `y`, whose artboard on top is `owner`: the paper + /// where no artboard is when there is none. fn paper_at(&self, owner: u32, i: usize, y: f64) -> Option { - let b = self.boards.get(owner as usize)?; + let Some(b) = self.boards.get(owner as usize) else { return self.everywhere }; Some(match &self.grid { Some((colors, cell)) => { let p = self.to_doc * Point::new(i as f64 + 0.5, y); @@ -459,7 +461,7 @@ impl<'a> Over<'a> { } let paper = if a == 255 { None - } else if self.everywhere.is_some() { + } else if self.boards.is_empty() { self.everywhere } else { if !found { @@ -497,8 +499,9 @@ impl<'a> Over<'a> { /// [`convert`], with each translucent pixel over the paper or the transparency grid of `backdrop` /// blended with it in sRGB before the conversion. The canvas draws the art over the paper /// converted: such a pixel keeps its alpha and takes the color that, drawn over the converted -/// paper, shows the blend converted. Opaque and fully transparent pixels, and pixels over the -/// pasteboard, convert as [`convert`] converts them. The pixels are rows of `width`; `view` maps the +/// paper, shows the blend converted. Translucent pixels where no artboard is are blended with the +/// backdrop's paper there (`everywhere`) when it has one. Opaque and fully transparent pixels, and +/// pixels over the pasteboard, convert as [`convert`] converts them. The pixels are rows of `width`; `view` maps the /// document to them, and the backdrop's `zoom` is the canvas's screen points per document point, /// in which the grid's cells are measured. pub(crate) fn convert_over(t: Option<&DisplayTransform>, pixels: &mut [u8], width: u32, view: Affine, backdrop: Option<(&Backdrop, f64)>) { @@ -682,6 +685,21 @@ pub(crate) mod tests { assert_eq!(srgb, row(20, half_red)); } + /// Overprint Preview's white canvas is paper too: translucent pixels around the artboards are + /// blended with it, and pixels on an artboard with the artboard's own paper. + #[test] + fn translucent_pixels_around_the_artboards_are_blended_with_the_white_canvas() { + let t = DisplayTransform::from_icc(&p3()).unwrap(); + let half_red = [128, 0, 0, 128]; + let dark = [40; 3]; + let b = Backdrop { everywhere: Some([255; 3]), artboards: vec![(Rect::new(0.0, 0.0, 10.0, 1.0), dark)], grid: None }; + let mut px = row(20, half_red); + convert_over(Some(&t), &mut px, 20, Affine::IDENTITY, Some((&b, 1.0))); + let at = |i: usize| -> [u8; 4] { px[i * 4..i * 4 + 4].try_into().unwrap() }; + assert_near(shown_over(at(2), t.apply8(dark)), blended(&t, half_red, dark), "on the artboard"); + assert_near(shown_over(at(15), t.apply8([255; 3])), blended(&t, half_red, [255; 3]), "around the artboards"); + } + #[test] fn the_backdrop_is_found_through_the_view() { let t = DisplayTransform::from_icc(&p3()).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..37332352f4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5080,7 +5080,9 @@ Each fill and stroke (and each character's fill and stroke) can overprint: its i of knocking them out. `object.setOverprint {fill?, stroke?, item?, ids?}` sets it (groups set their contents, type its characters too; `item` aims at one appearance item) and `attributes.info {ids?}` reads it back (`null` where the objects differ). Overprint Preview (`view.overprintPreview`) and Separations Preview show it; rendering approximates -it by darkening (the stronger ink of each plate wins, so a colour overprinting itself stays that colour). Older files that listed Overprint Black objects in the document get the flags on load. +it by darkening (the stronger ink of each plate wins, so a colour overprinting itself stays that colour). While either +preview is on, the canvas around the artboards is white instead of the pasteboard color and the artboards draw no +shadows; turning it off brings both back. Older files that listed Overprint Black objects in the document get the flags on load. PDF export writes them with `advanced.overprint: "preserve"` (the default): each overprinting fill and stroke sets a graphics state with `/OP true /op true /OPM 1` (`/OPM 0` in PDF/A). With `discardWhiteOverprint` (`document.setup`, on by default) white ones knock out instead; `"discard"` writes none. @@ -8412,7 +8414,8 @@ profile again leaves the canvas as it is. Exports, `ui.render`, the document, panels and thumbnails are not converted; with Proof Colors on, the proof is drawn first and then converted. Translucent art and the antialiased edges of art over an artboard's paper or the transparency grid are blended with it in sRGB, and the blend is converted; over the pasteboard and in Outline the art -is converted on its own. +is converted on its own. In Overprint Preview the white canvas around the artboards is paper too, and the art there is +blended with it. `ui.inspect` returns `displayProfile`: `{enabled, display, source, profile, from, applied, reason, osManaged, readRequested}`, where `source` is `profile`, `srgbProfile` (a profile that shows sRGB unchanged), `system`, `none`, `pending` or `unsupported`, `applied` says whether the canvas is converted, `reason` says why not, and `readRequested` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..b84699f7a6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -911,7 +911,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Assign Profile's three choices:** the Assign rows of Edit › Assign Profile… (the Separations panel's Color Settings section) offer Don't Color Manage This Document, the working space of the document's color mode (Working RGB or Working CMYK, with its name) and Profile with the other profiles of that kind, as [Assign or remove a color profile](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) lists them. They act on the profile of the document's color mode: an RGB document's RGB profile, a CMYK document's CMYK profile; the other model's profile stays as it is (VectorCraft's own rule; Document Setup › Color sets both). Picking the working space assigns its profile, which stays when the working space changes later. A choice the document already has runs nothing. Tests in `panels/separations.rs`. - **Canvas through the display's profile on Windows and X11:** Preferences › Performance › Use Monitor Profile for Canvas (on by default) converts the canvas's art, artboard paper and transparency grid from sRGB into the ICC profile of the display that shows most of the main window, after any proof, as the help page describes the monitor's profile translating the document's colors for the monitor ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). Windows gives the display's default profile, and a display with Advanced Color on is left to Windows ([Microsoft Learn](https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles)); X11 gives colord's profile for the output or the `_ICC_PROFILE` property. macOS converts the window itself, and a Wayland session stays sRGB. `ui.inspect` reports `displayProfile`. Tests in `color/src/cms/display.rs`, `ui-egui/src/display_profile.rs` and `canvas::tests::the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on`. - **Refresh Monitor Profile:** Edit › Refresh Monitor Profile (`view.refreshMonitorProfile`), VectorCraft's own command, reads the display's profile again on the next frame instead of waiting up to 10 seconds, so a profile installed or changed while the app runs is used without a restart; a request made while a reading runs starts when it ends, and the command is off while Use Monitor Profile for Canvas is off. `ui.inspect`'s `displayProfile.readRequested` reports a request that hasn't started. Tests `display_profile::tests::a_requested_reading_starts_on_the_next_frame_past_both_intervals`, `a_request_made_while_a_reading_runs_waits_for_it_to_end`, `a_request_is_dropped_when_the_preference_goes_off` (desktop app) and `menus::tests::refresh_monitor_profile_asks_for_a_reading_of_the_display_profile`. -- **Translucent art blended before the display profile:** with Use Monitor Profile for Canvas converting, translucent art and the anti-aliased edges of art over an artboard's paper, a colored artboard or the transparency grid are blended with it in sRGB and the blend is converted, so the monitor's profile translates the document's colors as they are composited ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). The frame rendered whole, the part an edit renders again, the render worker's frame, the pan fill and the other windows' panes do the same; over the pasteboard and in Outline the art is converted on its own, and with no profile to convert into nothing changes. Tests `display_profile::tests::translucent_pixels_over_the_paper_are_blended_before_they_are_converted`, `the_transparency_grid_is_blended_cell_by_cell`, `the_backdrop_is_found_through_the_view` and `canvas::tests::translucent_art_over_the_paper_is_blended_before_the_display_profile`. +- **Translucent art blended before the display profile:** with Use Monitor Profile for Canvas converting, translucent art and the anti-aliased edges of art over an artboard's paper, a colored artboard or the transparency grid are blended with it in sRGB and the blend is converted, so the monitor's profile translates the document's colors as they are composited ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). The frame rendered whole, the part an edit renders again, the render worker's frame, the pan fill and the other windows' panes do the same; over the pasteboard and in Outline the art is converted on its own, in Overprint Preview the art around the artboards is blended with its white canvas, and with no profile to convert into nothing changes. Tests `display_profile::tests::translucent_pixels_over_the_paper_are_blended_before_they_are_converted`, `the_transparency_grid_is_blended_cell_by_cell`, `the_backdrop_is_found_through_the_view` and `canvas::tests::translucent_art_over_the_paper_is_blended_before_the_display_profile`. - **Out-of-gamut warning after a profile change:** the out-of-gamut warning and its closest-color correction in the Color panel and Color Picker ([the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)) check the color against the document's assigned CMYK profile, else the working CMYK space, and update when Edit › Assign Profile… or Edit › Color Settings… changes that space or a loaded profile changes, without a change of color. Which CMYK space the warning uses is VectorCraft's own rule. Tests: `gamut_warning_follows_a_profile_change` and `gamut_warning_follows_a_profile_loaded_again` in `dialogs/color_picker/tests.rs`. - **Swatch Options and New Swatch color warnings:** both dialogs show the out-of-gamut triangle and the out-of-web-color cube under the color, each with its correction beside it, and a click on the icon or the correction shifts the color to the closest printable or web-safe color ([the archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=236), Swatch options; [the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)). The icons in the Color panel and the Color Picker correct the color too. VectorCraft's own rules: the triangle shows in RGB, HSB and Lab and the cube in every mode but Web Safe RGB, both can show at once, a web correction of a Grayscale, Lab or CMYK color is edited in RGB, a gamut correction keeps the CMYK equivalent and is edited in CMYK, and a correction keeps the name, the color type and Global and changes the dialog's fields only, so OK records one undo step. Tests: `swatch_options_shows_and_corrects_both_warnings` and `swatch_warnings_follow_the_mode` in `dialogs/swatch_options.rs`, `a_warning_corrects_the_new_colour_only_until_ok` in `dialogs/new_swatch.rs`. - **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. With Window › Arrange › Tile or floating document windows, each document behind the front one draws its art, paper and transparency grid through its own assigned profiles, and loading or removing a profile redraws the documents assigned it; placed documents inside it still draw through the front document's profiles. How documents behind the front one draw is VectorCraft's own rule. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. @@ -1633,7 +1633,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Navigator panel options:** the Navigator panel menu's Panel Options… sets the color the view box is drawn in, from a preset list (VectorCraft's own: Light Red, the default, then the layer colors) or a custom color, and Draw Dashed Lines as Solid Lines, off by default, which draws dashed strokes without their dashes in the panel's thumbnail only (`ui.navigatorPanelOptions`; kept with the UI state; behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). - **Attributes panel options:** the Attributes panel menu's Panel Options… sets how many recent URLs the URL menu lists, a whole number from 1 to 30 (10 by default, VectorCraft's own value); the panel keeps the 30 newest URLs of the session, so a lower count hides older URLs without removing them (`ui.attributesPanelOptions`; kept with the UI state; behavior reference: [Create image maps for web graphics](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/create-image-maps-for-web-graphics.html); test `panel_options_set_how_many_recent_urls_the_menu_lists`). - **Navigator View Artboard Contents Only:** the Navigator panel menu's View Artboard Contents Only is on by default, and the thumbnail then shows only the art inside the artboards, with art on the pasteboard and in the gaps between artboards left out; turning it off shows the art outside the artboards too (`ui.navigatorPanelOptions {viewArtboardContentsOnly}`; kept with the UI state, read as on when it was never saved; the fit to the artboards' union and the cut at each artboard's edge are VectorCraft's own rules; behavior references: [Navigate and zoom artwork](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/navigate-and-zoom-artwork.html), [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). -- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard, fits it and synchronizes the Artboard tool selection when that tool is active; ordinary object selection is preserved. Its four buttons are also commands of their own (`view.firstArtboard`, `view.previousArtboard`, `view.nextArtboard`, `view.lastArtboard`), listed in Edit › Keyboard Shortcuts without a default key, so a user can give them keys such as Page Up and Page Down (#5218). Actual Next-button regressions cover keyboard/Properties deletion and Undo in `chrome.rs`. Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, `view.screenMode` from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible under the outlines (#1505, fixes #1486). Outline view draws on a white canvas in every interface brightness and Canvas Color, pasteboard included, with the artboards as their edges and no paper (VectorCraft's own rule), so the black outlines of art on the pasteboard show. +- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard, fits it and synchronizes the Artboard tool selection when that tool is active; ordinary object selection is preserved. Its four buttons are also commands of their own (`view.firstArtboard`, `view.previousArtboard`, `view.nextArtboard`, `view.lastArtboard`), listed in Edit › Keyboard Shortcuts without a default key, so a user can give them keys such as Page Up and Page Down (#5218). Actual Next-button regressions cover keyboard/Properties deletion and Undo in `chrome.rs`. Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, `view.screenMode` from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible under the outlines (#1505, fixes #1486). Outline view draws on a white canvas in every interface brightness and Canvas Color, pasteboard included, with the artboards as their edges and no paper (VectorCraft's own rule), so the black outlines of art on the pasteboard show. Overprint Preview and Separations Preview draw the canvas around the artboards in white, with no artboard shadows (VectorCraft's own rule), and turning them off brings back the pasteboard color and the shadows. In Presentation Mode, → and ← go to the next and the previous artboard, and a click anywhere goes to the next one, as the status bar navigator's Next and Previous do (`view.goToArtboard`): on the last artboard → and a click leave the view as it is, and so does ← on the first. The arrow keys do not move the selection there, and the tool does not receive a click, so a click selects and draws nothing (behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). Full Screen Mode and Presentation Mode put the window full screen, covering the taskbar and the window's frame, and Normal Screen Mode or Full Screen Mode with Menu Bar puts it back (#4365); a window the user made full screen stays so. An unmodified Escape in either Full Screen Mode exits to Normal Screen Mode after any open popup, focused field, tool gesture, ruler-origin drag, floating Tools panel move, edit mode, drawer, flyout or view rotation has taken its Escape; a later Escape exits when that action is finished. This is a VectorCraft choice for both full screen variants, based on the public [shortcut list](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html); the list does not specify that priority or the return mode. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..244e96035c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -540,6 +540,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | | Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | +| Overprint Preview draws a white canvas around the artboards, with no artboard shadows | done | VectorCraft's own rule, in Overprint Preview and in Separations Preview, which turns it on: the canvas outside the artboards is white in every interface brightness, the artboards keep their paper and edges and draw no shadows, and the artboard names and the ruler origin's crosshair are dark gray. Where the Artboard tool's Fade Region Outside Artboard darkens a white canvas (here and in Outline) the names are black, and over a white canvas the Artboard tool's names of its selected artboards are dark blue. With a display profile, translucent art around the artboards is blended with the white canvas. Turning the preview off brings back the pasteboard color and the shadows. Tests `overprint_preview_draws_a_white_canvas_without_shadows`, `outline_names_show_on_the_faded_canvas`, `translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas`, `translucent_pixels_around_the_artboards_are_blended_with_the_white_canvas` | | Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | From f7b7ca5f86e5339a4db2e86520a2ab2590ad0dd4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:37:59 -0800 Subject: [PATCH 043/101] Recolor with Preset: ask whether to limit colors to a swatch library first Edit > Edit Colors > Recolor with Preset (1, 2 and 3 Color Job, Color Library) now opens a Recolor with Preset dialog with a Limit to Library menu (None, Document Swatches or a library) before Recolor Artwork opens; OK opens Recolor Artwork with the preset's colors and that library, and Cancel opens nothing. The menu items run ui.recolorDialog {preset: true}. A 1 Color Job limited to the document's swatches, with a spot or global ink picked for its row, gives gray art tints of that ink linked to its swatch, so editing the swatch recolors the art. Opening either dialog over another dialog now ends that dialog as Cancel does, so a Recolor Artwork preview is rolled back. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/recolor.rs | 45 +++-- crates/ui-egui/src/dialogs/recolor_preset.rs | 77 ++++++++ crates/ui-egui/src/menus/tree.rs | 8 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/tests/recolor.rs | 184 +++++++++++++++++++ docs/control-protocol.md | 7 +- docs/target-app-parity.md | 1 + 9 files changed, 308 insertions(+), 20 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/recolor_preset.rs diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..18951b9c90 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -995,7 +995,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.recolorDialog", "Recolor Artwork…", "", - "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", + "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", ), ( "ui.recolorUndo", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..0376bf83f3 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -113,6 +113,7 @@ mod psd_options; pub mod raster_effects; pub mod rearrange_artboards; pub mod recolor; +pub mod recolor_preset; mod recovery; pub mod relink; pub mod rename_artboards; @@ -337,6 +338,7 @@ registry! { ArtboardOptions: [artboard_options::KIND] => artboard_options::SPEC, ExportForScreens: ["exportForScreens"] => export_for_screens::SPEC, Recolor: [recolor::KIND] => recolor::SPEC, + RecolorPreset: [recolor_preset::KIND] => recolor_preset::SPEC, Command: ["command"] => command::SPEC, Variables: [variables::KIND] => variables::SPEC, Effect: ["effect"] => effect::SPEC, diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 1b80ce5e35..2901c69bd9 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -192,6 +192,11 @@ const COMPS: &str = "__comps"; /// rows, which OK saves as a new colour group); `library` limits to a library or "document" ("" /// picks the first library). pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + match p.get("preset") { + None | Some(Value::Bool(false)) => {} + Some(Value::Bool(true)) => return super::recolor_preset::open(app, p), + Some(_) => return Err("`preset` must be true or false".into()), + } let st = app.session.active().ok_or("no document open")?; let art = !st.selection.is_empty(); let group = p.get("group").and_then(Value::as_str); @@ -217,11 +222,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { None if !assign.is_empty() => json!(assign.len()), None => Value::Null, }; - let limit = match p.get("library").and_then(Value::as_str) { - Some("") => first_library(app).unwrap_or_default(), - Some(l) => limit_key(app, l)?, - None => String::new(), - }; + let limit = library_param(app, p)?; // Without art the rows are the group's colours, as they are. let mut start: Vec = if art { vec![] } else { assign.iter().map(|k| json!({"from": [k], "to": k})).collect() }; number_slots(&mut start); @@ -241,6 +242,10 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { snap(app, &d, &mut rs); d.fields.insert("rows".into(), Value::Array(rs)); // Undo Changes has nothing to undo on a new opening. + // A dialog this one replaces ends as Cancel ends it, its preview rolled back. + if app.ui.dialog.is_some() { + super::cancel(app); + } app.ui.recolor_history = History { opened: Some(snapshot(&d)), ..History::default() }; app.ui.dialog = Some(d); Ok(Value::Null) @@ -253,6 +258,27 @@ fn key(c: &Color) -> Value { /// The name a new colour group (opened on colours alone) starts with. const NEW_GROUP: &str = "Color Group"; +/// Limit to Library's choices, as keys of `limitTo` and the names shown: None, the document's +/// swatches, then the colour libraries: the built-in ones (at the top level of the library menu) +/// translated, those the user saved or loaded by their names. +pub(super) fn library_choices(app: &VectorcraftApp) -> (Vec, Vec) { + let libs = colour_libraries(app); + let keys = ["", swatchlib::DOCUMENT_SWATCHES].into_iter().map(String::from).chain(libs.iter().map(|l| l.id.clone())).collect(); + let names: Vec<&str> = ["None", DOCUMENT_SWATCHES].into_iter().chain(libs.iter().map(|l| l.name.as_str())).collect(); + let builtin = |k: usize| k.checked_sub(2).is_none_or(|i| libs.get(i).is_some_and(|l| l.submenu.is_none())); + let shown = super::shown_names(crate::i18n::current(), &names, builtin).into_iter().map(String::from).collect(); + (keys, shown) +} + +/// The `limitTo` key of `ui.recolorDialog`'s `library` (none without it, the first library for ""). +pub(super) fn library_param(app: &VectorcraftApp, p: &Value) -> Result { + match p.get("library").and_then(Value::as_str) { + Some("") => Ok(first_library(app).unwrap_or_default()), + Some(l) => limit_key(app, l), + None => Ok(String::new()), + } +} + fn first_library(app: &VectorcraftApp) -> Option { colour_libraries(app).into_iter().next().map(|l| l.id) } @@ -1956,13 +1982,8 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut } ui.end_row(); ui.label(egui::RichText::new(tl!("Limit to Library:")).color(t.text_dim)); - // None, the document's swatches, then the colour libraries: the built-in ones (at the top - // level of the library menu) translated, those the user saved or loaded by their names. - let libs = colour_libraries(app); - let keys: Vec<&str> = ["", swatchlib::DOCUMENT_SWATCHES].into_iter().chain(libs.iter().map(|l| l.id.as_str())).collect(); - let names: Vec<&str> = ["None", DOCUMENT_SWATCHES].into_iter().chain(libs.iter().map(|l| l.name.as_str())).collect(); - let builtin = |k: usize| k.checked_sub(2).is_none_or(|i| libs.get(i).is_some_and(|l| l.submenu.is_none())); - let shown = super::shown_names(crate::i18n::current(), &names, builtin); + let (keys, shown) = library_choices(app); + let shown: Vec<&str> = shown.iter().map(String::as_str).collect(); let cur = d.str("limitTo"); let at = keys.iter().position(|k| *k == cur).unwrap_or(0); let current = shown.get(at).copied().unwrap_or_default(); diff --git a/crates/ui-egui/src/dialogs/recolor_preset.rs b/crates/ui-egui/src/dialogs/recolor_preset.rs new file mode 100644 index 0000000000..a9063c8945 --- /dev/null +++ b/crates/ui-egui/src/dialogs/recolor_preset.rs @@ -0,0 +1,77 @@ +//! Edit → Edit Colors → Recolor with Preset: before Recolor Artwork opens on a preset (an n-color +//! job or Color Library), this dialog asks whether to limit the new colors to a swatch library +//! (`ui.recolorDialog {preset: true, colors?, library?}`). OK opens Recolor Artwork with the +//! preset's colors and the library chosen (None: no limit); Cancel opens nothing. +//! +//! Fields: `colors` (the preset's count, null for Color Library) and `limitTo` (a library id, +//! `"document"` for the document's swatches, `""` for None), as Recolor Artwork's. + +use serde_json::{Value, json}; + +use super::DialogSpec; +use super::recolor::{library_choices, library_param}; +use super::swatch_options::{grid, label}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Recolor with Preset. +pub const KIND: &str = "recolorPreset"; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Recolor with Preset").into(), body, confirm, min_width: 340.0, ..DialogSpec::FORM }; + +/// Open the dialog for the preset of `p` (`colors`: a count; `library`: the library it starts on, +/// "" the first library) on the selected art. +pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + let st = app.session.active().ok_or("no document open")?; + if st.selection.is_empty() { + return Err("select artwork to recolor".into()); + } + let colors = count(p.get("colors"))?; + let limit = library_param(app, p)?; + // A dialog this one replaces ends as Cancel ends it, its preview rolled back. + if app.ui.dialog.is_some() { + super::cancel(app); + } + app.ui.dialog = Some(Dialog::new(KIND, json!({"colors": colors, "limitTo": limit}))); + Ok(Value::Null) +} + +/// The preset's count of new colors: none for Color Library, else at least 1. +fn count(v: Option<&Value>) -> Result { + match v { + None | Some(Value::Null) => Ok(Value::Null), + Some(n) => Ok(json!(n.as_u64().filter(|n| *n >= 1).ok_or("`colors` must be a count of at least 1")?)), + } +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let (keys, shown) = library_choices(app); + let shown: Vec<&str> = shown.iter().map(String::as_str).collect(); + let cur = d.str("limitTo"); + let at = keys.iter().position(|k| *k == cur).unwrap_or(0); + let current = shown.get(at).copied().unwrap_or_default(); + grid(ui, |ui| { + label(ui, tl!("Limit to Library:")); + let library = ui.name_inputs(tl!("Limit to Library:"), |ui| widgets::dropdown_names(ui, "recolor-preset-library", current, &shown, 200.0)); + if let Some(k) = library.and_then(|i| keys.get(i)) { + d.fields.insert("limitTo".into(), json!(k)); + } + ui.end_row(); + }); + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut p = serde_json::Map::new(); + let n = count(d.fields.get("colors"))?; + if !n.is_null() { + p.insert("colors".into(), n); + } + let limit = d.str("limitTo"); + if !limit.is_empty() { + p.insert("library".into(), json!(limit)); + } + // Recolor Artwork takes the dialog's place; when it cannot open, this dialog stays. + super::recolor::open(app, &Value::Object(p)) +} diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 3e68b98c92..c0f10056cc 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -109,10 +109,10 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { sub( "Recolor with Preset", vec![ - cp("1 Color Job…", "ui.recolorDialog", json!({"colors": 1})), - cp("2 Color Job…", "ui.recolorDialog", json!({"colors": 2})), - cp("3 Color Job…", "ui.recolorDialog", json!({"colors": 3})), - cp("Color Library…", "ui.recolorDialog", json!({"library": ""})), + cp("1 Color Job…", "ui.recolorDialog", json!({"colors": 1, "preset": true})), + cp("2 Color Job…", "ui.recolorDialog", json!({"colors": 2, "preset": true})), + cp("3 Color Job…", "ui.recolorDialog", json!({"colors": 3, "preset": true})), + cp("Color Library…", "ui.recolorDialog", json!({"library": "", "preset": true})), ], ), c("Adjust Color Balance…", "ui.colorBalanceDialog"), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..27bcf98155 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -996,7 +996,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.recolorDialog", "Recolor Artwork…", "", - "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", + "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", ), ( "ui.recolorUndo", diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 986dbb6290..d55b9f1882 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -104,6 +104,7 @@ fn presets_open_colour_jobs_and_libraries_and_both_tabs_draw() { entries.iter().filter(|e| e.path.last().is_some_and(|p| p == "Recolor with Preset")).map(|e| (e.label.as_str(), &e.params)).collect(); assert_eq!(presets.iter().map(|p| p.0).collect::>(), ["1 Color Job…", "2 Color Job…", "3 Color Job…", "Color Library…"]); app.run("ui.recolorDialog", presets[1].1.clone()).unwrap(); + dialogs::confirm(&mut app).unwrap(); dialog_frame(&mut app, &ctx); assert_eq!((field(&app, "colors"), field(&app, "method")), (json!(2), json!("scaleTints"))); assert_eq!(field(&app, "rows").as_array().unwrap().len(), 2); @@ -111,6 +112,8 @@ fn presets_open_colour_jobs_and_libraries_and_both_tabs_draw() { dialog_frame(&mut app, &ctx); dialogs::cancel(&mut app); app.run("ui.recolorDialog", presets[3].1.clone()).unwrap(); + assert_eq!(field(&app, "limitTo"), "web-safe-216", "Color Library asks with the first library chosen"); + dialogs::confirm(&mut app).unwrap(); assert_eq!(field(&app, "limitTo"), "web-safe-216", "Color Library starts on the first library"); dialog_frame(&mut app, &ctx); let web = |k: &Value| vectorcraft_engine::cmd::color_value(k).unwrap().to_rgb().iter().all(|v| ((v * 5.0).round() - v * 5.0).abs() < 1e-3); @@ -1992,3 +1995,184 @@ fn the_color_picker_leaves_the_dialog_in_place() { } assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("recolor")); } + +fn dialog_kind(app: &VectorcraftApp) -> Option<&str> { + app.ui.dialog.as_ref().map(|d| d.kind.as_str()) +} + +/// Edit › Edit Colors › Recolor with Preset asks whether to limit the colors to a swatch library +/// before Recolor Artwork opens: Cancel opens nothing, and OK opens Recolor Artwork with the +/// preset's colors and the library chosen. +#[test] +fn recolor_with_preset_asks_for_a_library_first() { + let mut app = app(); + let ctx = context(); + assert!(app.run("ui.recolorDialog", json!({"colors": 1, "preset": true})).is_err(), "nothing selected"); + assert_eq!(dialog_kind(&app), None); + art(&mut app, &["#333333", "#999999"]); + assert!(app.run("ui.recolorDialog", json!({"colors": 1, "preset": 1})).is_err(), "`preset` is true or false"); + assert!(app.run("ui.recolorDialog", json!({"colors": 0, "preset": true})).is_err(), "a preset has at least one color"); + assert_eq!(dialog_kind(&app), None); + let entries = crate::menus::menu_entries(&app); + let presets: Vec = + entries.iter().filter(|e| e.path.last().is_some_and(|p| p == "Recolor with Preset")).map(|e| e.params.clone()).collect(); + assert_eq!(presets.len(), 4); + for p in &presets { + app.run("ui.recolorDialog", p.clone()).unwrap(); + assert_eq!(dialog_kind(&app), Some(dialogs::recolor_preset::KIND), "{p}"); + dialog_frame(&mut app, &ctx); + dialogs::cancel(&mut app); + assert_eq!(dialog_kind(&app), None, "Cancel opens nothing: {p}"); + } + // A preset opened over Recolor Artwork's preview rolls the preview back. + let start = colors(&mut app); + app.run("ui.recolorDialog", json!({})).unwrap(); + set(&mut app, "colors", json!(1)); + set(&mut app, "method", json!("exact")); + dialog_frame(&mut app, &ctx); + assert_eq!(colors(&mut app), 1, "previewed"); + app.run("ui.recolorDialog", presets[0].clone()).unwrap(); + assert_eq!(dialog_kind(&app), Some(dialogs::recolor_preset::KIND)); + assert_eq!(colors(&mut app), start, "the preview is rolled back"); + assert_eq!(field(&app, "limitTo"), json!(""), "a color job starts on None"); + set(&mut app, "colors", json!("two")); + assert!(dialogs::confirm(&mut app).is_err(), "the count is checked again on OK"); + assert_eq!(dialog_kind(&app), Some(dialogs::recolor_preset::KIND), "the dialog stays"); + set(&mut app, "colors", json!(1)); + set(&mut app, "limitTo", json!("document")); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(dialog_kind(&app), Some(dialogs::recolor::KIND)); + assert_eq!((field(&app, "colors"), field(&app, "method"), field(&app, "limitTo")), (json!(1), json!("scaleTints"), json!("document"))); + // Recolor Artwork opened over its own preview rolls that preview back too. + set(&mut app, "method", json!("exact")); + set(&mut app, "limitTo", json!("")); + dialog_frame(&mut app, &ctx); + assert_eq!(colors(&mut app), 1, "previewed"); + app.run("ui.recolorDialog", json!({})).unwrap(); + assert_eq!(colors(&mut app), start, "the preview is rolled back"); + dialogs::cancel(&mut app); +} + +/// Every paint under `v`, in order: its color, the swatch it is linked to and its tint. +fn paints_in(v: &Value, out: &mut Vec<(Color, Option, f64)>) { + match v { + Value::Object(m) => { + if let Some(c) = m.get("color").and_then(|c| serde_json::from_value::(c.clone()).ok()) { + out.push((c, m.get("swatch").and_then(Value::as_str).map(String::from), m.get("tint").and_then(Value::as_f64).unwrap_or(1.0))); + } + m.values().for_each(|x| paints_in(x, out)); + } + Value::Array(a) => a.iter().for_each(|x| paints_in(x, out)), + _ => {} + } +} + +/// Every number under an `opacity` key under `v`, in order. +fn opacities_in(v: &Value, out: &mut Vec) { + match v { + Value::Object(m) => { + out.extend(m.get("opacity").and_then(Value::as_f64)); + m.values().for_each(|x| opacities_in(x, out)); + } + Value::Array(a) => a.iter().for_each(|x| opacities_in(x, out)), + _ => {} + } +} + +/// The art of every layer as saved. +fn art_json(app: &VectorcraftApp) -> Value { + let d = &app.session.doc().unwrap().doc; + Value::Array(d.layers.iter().filter_map(|l| l.children()).map(|c| serde_json::to_value(c).unwrap()).collect()) +} + +fn art_paints(app: &VectorcraftApp) -> Vec<(Color, Option, f64)> { + let mut out = vec![]; + paints_in(&art_json(app), &mut out); + out +} + +/// A gray other than black or white, with its lightness. +fn gray(c: &Color) -> Option { + let [r, g, b] = c.to_rgb(); + ((r - g).abs() < 1e-3 && (g - b).abs() < 1e-3 && r > 0.01 && r < 0.99).then_some(r) +} + +/// Gray art placed from an SVG file (fills, a stroke, a group at 50% opacity, `fill-opacity`, a +/// compound path, a gradient's stops and type) with a 1 Color Job of Recolor with Preset limited +/// to the document's swatches and a spot or global ink picked for its row becomes tints of that +/// ink linked to its swatch, darker grays at higher tints, with its opacities kept; editing the +/// swatch then recolors the art at the same tints. A process swatch gives tints of its color with +/// no link. +#[test] +fn a_one_color_job_limited_to_document_swatches_links_gray_art_to_the_ink() { + let svg = r##"Ink"##; + let path = std::env::temp_dir().join(format!("vectorcraft-recolor-preset-{}.svg", std::process::id())); + std::fs::write(&path, svg).unwrap(); + for (kind, options, linked) in [("spot", json!({"spot": true}), true), ("global", json!({"global": true}), true), ("process", json!({}), false)] { + let mut app = app(); + let ctx = context(); + let mut swatch = json!({"name": "Ink", "color": "cmyk 0 100 0 0"}); + swatch.as_object_mut().unwrap().extend(options.as_object().unwrap().clone()); + app.run("swatch.new", swatch).unwrap(); + app.run("file.place", json!({"path": path.to_string_lossy(), "at": [120, 50]})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let before = art_paints(&app); + let grays: Vec = (0..before.len()).filter(|&i| gray(&before[i].0).is_some()).collect(); + assert!(grays.len() >= 9, "{kind}: the fills, the stroke, the stops and the type are gray: {before:?}"); + let mut opacities = vec![]; + opacities_in(&art_json(&app), &mut opacities); + assert!(opacities.iter().any(|o| (o - 0.5).abs() < 1e-6), "the group's opacity came in: {opacities:?}"); + assert!(opacities.iter().any(|o| (o - 0.7).abs() < 1e-6), "the fill opacity came in: {opacities:?}"); + + let entries = crate::menus::menu_entries(&app); + let job = entries.iter().find(|e| e.label == "1 Color Job…").unwrap().params.clone(); + app.run("ui.recolorDialog", job).unwrap(); + set(&mut app, "limitTo", json!("document")); + dialogs::confirm(&mut app).unwrap(); + dialog_frame(&mut app, &ctx); + let ink = app.session.doc().unwrap().doc.swatch("Ink").unwrap().paint.color().unwrap(); + let mut rows = field(&app, "rows").as_array().unwrap().clone(); + let row = rows.iter().position(|r| !r["exclude"].as_bool().unwrap_or(false)).unwrap(); + assert!(rows.iter().enumerate().all(|(i, r)| i == row || r["exclude"].as_bool().unwrap_or(false)), "one row: {rows:?}"); + rows[row]["to"] = json!(ColorKey::of(&ink).to_string()); + set(&mut app, "rows", Value::Array(rows)); + dialog_frame(&mut app, &ctx); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(dialog_kind(&app), None); + + let after = art_paints(&app); + assert_eq!(after.len(), before.len(), "{kind}: the art has the same paints"); + let mut kept = vec![]; + opacities_in(&art_json(&app), &mut kept); + assert_eq!(kept, opacities, "{kind}: the opacities are kept"); + for &i in &grays { + let (c, link, tint) = &after[i]; + assert!(gray(c).is_none(), "{kind}: paint {i} is no longer gray: {c:?}"); + assert_eq!(link.is_some(), linked, "{kind}: paint {i} linked: {link:?}"); + if linked { + assert_eq!(link.as_deref(), Some("Ink")); + assert!(*tint > 0.0 && *tint <= 1.0, "{kind}: paint {i} at a tint: {tint}"); + } + } + for (i, c) in before.iter().enumerate().filter(|(i, _)| !grays.contains(i)) { + assert_eq!(after[i].0, c.0, "{kind}: black and white are kept"); + } + if linked { + for &a in &grays { + for &b in &grays { + if gray(&before[a].0) < gray(&before[b].0) { + assert!(after[a].2 >= after[b].2, "{kind}: a darker gray takes more ink: {:?} {:?}", after[a], after[b]); + } + } + } + app.run("swatch.edit", json!({"name": "Ink", "color": "cmyk 100 0 0 0"})).unwrap(); + let edited = art_paints(&app); + for &i in &grays { + assert_eq!(edited[i].1.as_deref(), Some("Ink"), "{kind}: paint {i} stays linked"); + assert!((edited[i].2 - after[i].2).abs() < 1e-6, "{kind}: paint {i} keeps its tint"); + assert_ne!(edited[i].0, after[i].0, "{kind}: paint {i} takes the edited ink"); + } + } + } + let _ = std::fs::remove_file(&path); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dafab93a58..2f19b5fd37 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -287,9 +287,12 @@ canvas while open; `ui.dialog.confirm` keeps the result as one undo step (`edit. `edit.colors.saturate`) and `ui.dialog.cancel` rolls it back. Global mode answers with an error until tints of global and spot colours exist; the dialog then stays open. -Recolor Artwork: `ui.recolorDialog {colors?, library?, group?}` opens the `recolor` dialog on the selected art +Recolor Artwork: `ui.recolorDialog {colors?, library?, group?, preset?}` opens the `recolor` dialog on the selected art (`colors`: a count for an n-colour job, or colours to assign as the new colours; `library`: Limit to Library, a library -or `"document"`, `""` for the first library; `group`: a colour group, Edit or Apply Color Group). Fields: `rows` (`[{from: [keys], to: key, exclude?, tint?, model?}]` +or `"document"`, `""` for the first library; `group`: a colour group, Edit or Apply Color Group). With `preset: true` +(the Edit › Edit Colors › Recolor with Preset items) it first opens the `recolorPreset` dialog, which asks whether to +limit the colors to a swatch library: its field `limitTo` (a library id, `"document"`, or `""` for None) starts on +`library`, and its OK opens the `recolor` dialog with `colors` and that library. Fields: `rows` (`[{from: [keys], to: key, exclude?, tint?, model?}]` as `recolor.reduce` returns them), `colors` (null for Auto), `method`, `preserveWhite`, `preserveBlack`, `preserveGrays`, `limitTo`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`, `sliderMode` (the mode of the color sliders under the rows: `hsb`, `rgb`, `cmyk`, `lab`, or `tint` for a row whose new diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..bf1b6461a3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -641,6 +641,7 @@ since 2026-10-01. - **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). A drag or double-click on a ruler makes no guide while it is on (no preview, no undo step, a status message). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths`, `trim_view_makes_no_guide_from_the_rulers` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`. - **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. +- **Recolor with Preset asks for a library first:** Edit › Edit Colors › Recolor with Preset (1, 2 and 3 Color Job, Color Library) opens a Recolor with Preset dialog whose Limit to Library menu (None, Document Swatches or a library) is applied when Recolor Artwork opens (, "Quickly reduce colors using a preset"). A 1 Color Job limited to the document's swatches with a spot or global ink picked turns gray art into tints of that ink linked to its swatch, so editing the swatch recolors the art. Tests `recolor_with_preset_asks_for_a_library_first` and `a_one_color_job_limited_to_document_swatches_links_gray_art_to_the_ink`. 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, 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. From 1592cee7a8725d7ee1569353187a3d5c41bf7cfd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:34:02 -0800 Subject: [PATCH 044/101] =?UTF-8?q?Plug-ins:=20Apply=20Last=20Filter=20and?= =?UTF-8?q?=20Last=20Filter=E2=80=A6=20repeat=20the=20last=20filter=20plug?= =?UTF-8?q?-in?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins now starts with Apply Last Filter (plugin.applyLastFilter) and Last Filter… (plugin.lastFilter). Once a filter plug-in's plugin.run succeeds (its menu item, its dialog's OK, a shortcut, a request, the last plugin.run step of a command.batch or of an Action Batch that processed a file or data set, or a background run once its result is applied), Apply runs it again on the selection with the same parameters, without its dialog, as one undo step, and … opens its dialog with those parameters. A filter's own dialog opens with the parameters it last ran with in the session. Previews, Cancel, failed runs, a plug-in's own commands and live effects don't count. Both items are grayed out, and return an error through automation, with no document open, before a filter ran, once that filter was removed or installed again, or when its manifest no longer takes the parameters as they are. The parameters are kept for the session only, for at most 64 filters. The help page describes the same pair for filters: https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=357 Where the items sit and when they are grayed out are VectorCraft's own rules. Docs: docs/plugins.md, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/plugin.rs | 2 +- crates/mcp/src/ui_catalog.rs | 14 +- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/commands.rs | 3 + crates/ui-egui/src/dialogs/plugin.rs | 191 +++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/gu.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tests.rs | 17 ++ crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/labels.rs | 12 + crates/ui-egui/src/menus/run.rs | 2 + crates/ui-egui/src/menus/state.rs | 4 + crates/ui-egui/src/menus/tree.rs | 5 +- crates/ui-egui/src/menus/ui_commands.rs | 14 +- crates/ui-egui/src/native_menu.rs | 4 +- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/last_filter.rs | 317 ++++++++++++++++++++++++ docs/mcp.md | 9 +- docs/plugins.md | 20 +- docs/target-app-parity.md | 1 + 46 files changed, 718 insertions(+), 12 deletions(-) create mode 100644 crates/ui-egui/src/tests/last_filter.rs diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..7273d90f9d 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -124,7 +124,7 @@ pub fn describe(p: &Plugin) -> Value { /// The plug-in's own parameters from command params: `params` if given, else the top-level keys /// minus the ones the command itself uses. -fn plugin_params(p: &Value) -> Value { +pub fn plugin_params(p: &Value) -> Value { if let Some(v) = p.get("params") { return v.clone(); } diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..8f5c45eead 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1993,7 +1993,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "plugin.dialog", "Plug-in…", "", - "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns)", + "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter at the value the filter last ran with in this session, else its default, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns)", + ), + ( + "plugin.applyLastFilter", + "Apply Last Filter", + "", + "{} Object › Plug-ins › Apply : run the object filter that last ran in this session (a plugin.run that succeeded: its menu item, its dialog's OK, a request, a command.batch step or an action.batch step; not a plug-in's own commands) again on the selection with the same parameters, without its dialog, as one undo step; it runs in the background where its menu item would → plugin.run's result | {background: true, status}. An error with no document open, when no filter ran yet, when that filter was removed or installed again (the same module too) since, or when its manifest no longer takes those parameters as they are", + ), + ( + "plugin.lastFilter", + "Last Filter…", + "", + "{} Object › Plug-ins › …: open the dialog of the object filter that last ran in this session (see plugin.applyLastFilter) with the parameters it ran with (dialog `plugin`); OK runs it as one undo step and Cancel changes nothing. A filter without parameters runs at once. The same errors as plugin.applyLastFilter", ), ( "ui.installPlugin", diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..abf1e2ee27 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -109,6 +109,7 @@ impl VectorcraftApp { titlebar_inset: 0.0, last_effect: None, last_pathfinder: None, + last_filters: Default::default(), last_warp: None, character_focus: None, run_count: 0, diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 042e8b37a5..1b1e21150b 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -247,6 +247,7 @@ impl VectorcraftApp { let ime_before = crate::ime::stamp(&mut self.session, ime_view); let cursor_settings = (self.session.caps_lock, self.session.prefs.use_precise_cursors); let spot_base = panels::color_guide::before_command(self); + let plugins_before = dialogs::plugin::before_command(); let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); let r = panels::actions::after_recorded_command(self, r); if r.is_ok() && cursor_settings != (self.session.caps_lock, self.session.prefs.use_precise_cursors) { @@ -262,6 +263,8 @@ impl VectorcraftApp { { self.last_pathfinder = Some(op.to_string()); } + // A filter plug-in run becomes Object › Plug-ins › Apply Last Filter. + dialogs::plugin::after_command(self, id, ¶ms, &r, plugins_before); let copied = r.is_ok() && self.publish_copy(id); self.sync_views(); self.refresh_replace_font_warning(false); diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 706188f6da..02d7ca9dd3 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -11,7 +11,10 @@ //! background too, with its progress and Cancel, when it runs at once or when OK runs it without a //! kept preview ([`in_background`]). A filter or live effect with commands of //! its own is a submenu named after it, holding its item and then its commands; a command with -//! parameters opens the same dialog for them ([`open_command`]). Exporters are formats of File › Export › +//! parameters opens the same dialog for them ([`open_command`]). Object › Plug-ins starts with +//! Apply Last Filter and Last Filter…, which run the filter that last ran again with the same +//! parameters or open its dialog with them, and a filter's dialog opens with the parameters it last +//! ran with in the session ([`LastFilters`]). Exporters are formats of File › Export › //! Export As; one with parameters opens dialog `pluginExport` once the file is picked, and its //! Export button writes the file. Importers open the files File › Open finds no built-in format //! for, and File › Open With lists them, to open a file with one of them by name; one with @@ -120,8 +123,173 @@ pub fn effect_menu() -> Option { (!items.is_empty()).then_some(Item::Sub("Plug-ins", items)) } +/// Object › Plug-ins' first items: Apply Last Filter, which runs the filter that last ran again with +/// the same parameters, and Last Filter…, which opens its dialog with them. Each is named after the +/// filter once one has run ([`last_filter_name`]). +pub fn last_filter_menu() -> Vec { + vec![Item::Cmd("Apply Last Filter", APPLY_LAST, Value::Null), Item::Cmd("Last Filter…", LAST, Value::Null), Item::Sep] +} + +/// Apply Last Filter's command id. +pub const APPLY_LAST: &str = "plugin.applyLastFilter"; + +/// Last Filter…'s command id. +pub const LAST: &str = "plugin.lastFilter"; + +/// The error of Apply Last Filter and Last Filter… when no filter can run again: none ran in this +/// session, or the one that ran last was removed or installed again, or its parameters no longer fit it. +pub const NO_LAST_FILTER: &str = "no plug-in filter to repeat: run one from Object › Plug-ins first"; + +/// The most filters whose last parameters [`LastFilters`] keeps. +const MAX_REMEMBERED: usize = 64; + +/// The parameters filter `id` last ran with, as its manifest resolved them, and the installation +/// that ran with them (its [`Plugin::serial`]; installing the plug-in again gives it a new one). +#[derive(Clone, Debug, PartialEq)] +struct Used { + id: String, + serial: u64, + params: Map, +} + +/// The parameters each object filter last ran with in this session (`plugin.run`), the filter that +/// ran last at the end, for at most [`MAX_REMEMBERED`] filters. They are never saved. +#[derive(Default)] +pub struct LastFilters { + used: Vec, +} + +impl LastFilters { + /// The id of the filter that ran last, whether or not it can run again. + pub fn last_id(&self) -> Option<&str> { + self.used.last().map(|u| u.id.as_str()) + } +} + +/// Notes a `plugin.run` with params `p` that succeeded: its filter ran last, with the +/// parameters its manifest resolves from `p`. Anything else (not a filter, parameters the manifest +/// refuses) is not noted. +pub(crate) fn record(app: &mut VectorcraftApp, p: &Value) { + let Some(plugin) = p.get("id").and_then(Value::as_str).and_then(registry::get) else { return }; + let m = plugin.manifest(); + if m.kind != Kind::Filter { + return; + } + let Ok(params) = m.resolve_params(&vectorcraft_engine::cmd::plugin::plugin_params(p)) else { return }; + let used = &mut app.last_filters.used; + used.retain(|u| u.id != m.id); + used.push(Used { id: m.id.clone(), serial: plugin.serial(), params }); + if used.len() > MAX_REMEMBERED { + used.remove(0); + } +} + +/// The plug-in registry's revision before a command runs, for [`after_command`]. +pub(crate) fn before_command() -> u64 { + registry::revision() +} + +/// After command `id` with `params` ran with result `r`, the registry at revision `before` when it +/// started: a `plugin.run` that succeeded, or the last `plugin.run` step of a batch that succeeded +/// (`command.batch`, or `action.batch` on at least one file or data set), is noted as the filter +/// that ran last ([`record`]). +pub(crate) fn after_command(app: &mut VectorcraftApp, id: &str, params: &Value, r: &Result, before: u64) { + let Ok(reply) = r else { return }; + // Action Batch returns success even when files or data sets fail, and runs every step on each + // one that doesn't. + let played = |v: &Value| v.get("count").and_then(Value::as_u64).unwrap_or(0) > v.get("failed").and_then(Value::as_u64).unwrap_or(0); + let ran = match id { + CMD => Some(params), + "command.batch" | "action.batch" if id == "command.batch" || played(reply) => { + let steps = params.get("commands").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); + let Some(at) = steps.iter().rposition(|s| step_id(s) == Some(CMD)) else { return }; + let p = steps[at].get("params").unwrap_or(&Value::Null); + // The plug-in installed under the id now is the one that ran when no later step changed + // the plug-ins, or when it was installed before the batch (installing gives a new serial). + let changed_later = steps[at + 1..].iter().any(|s| step_id(s).is_some_and(|c| REGISTRY_CHANGES.contains(&c))); + let installed_before = p.get("id").and_then(Value::as_str).and_then(registry::get).is_some_and(|q| q.serial() <= before); + if changed_later && !installed_before { + forget(app, p); + return; + } + Some(p) + } + _ => None, + }; + if let Some(p) = ran.cloned() { + record(app, &p); + } +} + +/// The command id of batch step `s`. +fn step_id(s: &Value) -> Option<&str> { + s.get("command").and_then(Value::as_str) +} + +/// The commands that install, remove or reload plug-ins. +const REGISTRY_CHANGES: [&str; 3] = ["plugin.install", "plugin.remove", "plugin.reload"]; + +/// Notes the filter `plugin.run` params `p` name as the one that ran last, without parameters or a +/// module, so that Apply Last Filter and Last Filter… stay off until a filter runs again. +fn forget(app: &mut VectorcraftApp, p: &Value) { + let Some(id) = p.get("id").and_then(Value::as_str) else { return }; + let used = &mut app.last_filters.used; + used.retain(|u| u.id != id); + // Serial 0 belongs to no installed plug-in. + used.push(Used { id: id.to_string(), serial: 0, params: Map::new() }); + if used.len() > MAX_REMEMBERED { + used.remove(0); + } +} + +/// Filter `id`'s last parameters, while the installation that ran with them is still installed under +/// its id and its manifest takes them as they are. +fn remembered(app: &VectorcraftApp, id: &str) -> Option<(Arc, Map)> { + let used = app.last_filters.used.iter().find(|u| u.id == id)?; + let plugin = registry::get(id).filter(|p| p.manifest().kind == Kind::Filter && p.serial() == used.serial)?; + let params = Value::Object(used.params.clone()); + plugin.manifest().resolve_params(¶ms).ok().filter(|r| *r == used.params)?; + Some((plugin, used.params.clone())) +} + +/// The filter that ran last and its parameters, while it can run again with them ([`remembered`]). +pub(crate) fn last_filter(app: &VectorcraftApp) -> Option<(Arc, Map)> { + remembered(app, app.last_filters.last_id()?) +} + +/// The name Apply Last Filter and Last Filter… show once a filter ran that can run again +/// ([`last_filter`]): the filter's own name, without an ellipsis at its end and with hidden +/// characters shown as escapes, as a submenu named after a plug-in shows it. `None` before. +pub(crate) fn last_filter_name(app: &VectorcraftApp) -> Option { + let (plugin, _) = last_filter(app)?; + let name = plugin.manifest().name.trim().trim_end_matches('…').trim_end().to_string(); + Some(permissions::display_text(&name, permissions::MAX_SHOWN_NAME)) +} + +/// `plugin.applyLastFilter`: runs the filter that ran last again, with the same parameters, on the +/// selection, without its dialog, as its menu item runs it ([`run`]). +pub fn apply_last(app: &mut VectorcraftApp) -> Result { + app.session.active().ok_or("no document open")?; + let (plugin, params) = last_filter(app).ok_or(NO_LAST_FILTER)?; + let p = json!({"id": plugin.id(), "params": params}); + run(app, &plugin, p) +} + +/// `plugin.lastFilter`: opens the dialog of the filter that ran last with the parameters it ran +/// with; one without parameters runs at once, as its menu item runs it. +pub fn open_last(app: &mut VectorcraftApp) -> Result { + app.session.active().ok_or("no document open")?; + let (plugin, params) = last_filter(app).ok_or(NO_LAST_FILTER)?; + if plugin.manifest().params.is_empty() { + return run(app, &plugin, json!({"id": plugin.id(), "params": params})); + } + open_dialog(app, plugin.manifest(), params); + Ok(Value::Null) +} + /// `plugin.dialog {id, params?}`: run filter `id` at once when it takes no parameters or `params` -/// are given, else open its dialog prefilled with its defaults. +/// are given, else open its dialog prefilled with the parameters it last ran with in this session +/// ([`remembered`]), or with its defaults. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let id = p.get("id").and_then(Value::as_str).ok_or("missing `id` (see plugin.list)")?; let plugin = registry::get(id).ok_or_else(|| format!("no plug-in {id:?} is installed"))?; @@ -136,12 +304,19 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if m.params.is_empty() || given.is_some() { return run(app, &plugin, json!({"id": id, "params": given.cloned().unwrap_or(Value::Null)})); } + let values = remembered(app, id).map(|(_, params)| params).unwrap_or_else(|| m.defaults()); + open_dialog(app, m, values); + Ok(Value::Null) +} + +/// Opens filter `m`'s dialog with its parameters at `values`, with Preview on for a light filter. +fn open_dialog(app: &mut VectorcraftApp, m: &Manifest, values: Map) { let mut fields = fields_for(m); + fields.extend(values); if m.budget == Budget::Light { fields.insert("preview".into(), json!(true)); } app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); - Ok(Value::Null) } /// The fields of plug-in `m`'s dialog: its parameters at their defaults, `__plugin` (its id) and @@ -266,7 +441,15 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } r } - _ => form::commit_preview(app, &command(d), params(d)), + _ => { + let r = form::commit_preview(app, &command(d), params(d)); + // A kept preview commits without running `plugin.run` again ([`after_command`]); for + // the filter's own run, `params(d)` is `plugin.run`'s `{id, params}`. + if r.is_ok() && own_run { + record(app, ¶ms(d)); + } + r + } } } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..fc29c28a64 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1998,6 +1998,9 @@ font-technology Variable Променливи Last Effect: {name} Посл. ефект: {name} Last Effect: {} Посл. ефект: {} Last Effect… Посл. ефект… + Apply Last Filter Прилагане на последния филтър + Last Filter… Посл. филтър… + Apply {filter} Прилагане на {filter} Last Page Последна страница Latin Латиница Thai Тайландски @@ -5008,6 +5011,7 @@ axis Both И двете @msg no document няма документ @msg no document open няма отворен документ @msg no effect applied yet все още няма приложен ефект +@msg no plug-in filter to repeat: run one from Object › Plug-ins first няма филтър от приставка за повторение: първо стартирайте такъв от Обект › Приставки @msg no Pathfinder operation applied yet все още няма приложена операция на Pathfinder @msg no effect at index {k} няма ефект на индекс {k} @msg no end record няма краен запис diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..9f711d28f8 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -539,6 +539,9 @@ Effect Efekat Apply Last Effect Primijeni posljednji efekat Last Effect… Posljednji efekat… + Apply Last Filter Primijeni posljednji filter + Last Filter… Posljednji filter… + Apply {filter} Primijeni {filter} Document Raster Effects Settings… Postavke rasterskih efekata dokumenta… Vector Effects Vektorski efekti 3D and Materials 3D i materijali @@ -5439,6 +5442,7 @@ imageTrace Outline Obris @msg no document nema dokumenta @msg no document open nijedan dokument nije otvoren @msg no effect applied yet još nije primijenjen nijedan efekat +@msg no plug-in filter to repeat: run one from Object › Plug-ins first nema filtera dodatka za ponavljanje: prvo pokrenite jedan iz Objekat › Dodaci @msg no effect at index {k} nema efekta na indeksu {k} @msg no end record nema završnog zapisa @msg no file manager here ovdje nema upravitelja datoteka diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..a24c6a91b4 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2554,6 +2554,9 @@ digits Malayalam Malaiàlam Last Effect: {name} Últim efecte: {name} Last Effect: {} Últim efecte: {} Last Effect… Últim efecte… + Apply Last Filter Aplica l’últim filtre + Last Filter… Últim filtre… + Apply {filter} Aplica {filter} Last Page Última pàgina Latin Llatí Latin Extended Llatí estès @@ -6879,6 +6882,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg no document no hi ha document @msg no document open no hi ha cap document obert @msg no effect applied yet encara no s’ha aplicat cap efecte +@msg no plug-in filter to repeat: run one from Object › Plug-ins first no hi ha cap filtre de complement per repetir: executeu-ne primer un des d’Objecte › Complements @msg no Pathfinder operation applied yet encara no s’ha aplicat cap operació del Cercador de traçats @msg no effect at index {k} no hi ha cap efecte a l’índex {k} @msg no empty artboards to delete no hi ha taulers buits per suprimir diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..149ea27ff6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -553,6 +553,9 @@ Effect Efekt Apply Last Effect Použít poslední efekt Last Effect… Poslední efekt… + Apply Last Filter Použít poslední filtr + Last Filter… Poslední filtr… + Apply {filter} Použít {filter} Document Raster Effects Settings… Nastavení rastrových efektů dokumentu… Vector Effects Vektorové efekty 3D and Materials 3D a materiály @@ -5764,6 +5767,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg no document žádný dokument @msg no document open není otevřen žádný dokument @msg no effect applied yet zatím nebyl použit žádný efekt +@msg no plug-in filter to repeat: run one from Object › Plug-ins first žádný filtr zásuvného modulu k zopakování: nejprve jeden spusťte z nabídky Objekt › Zásuvné moduly @msg no Pathfinder operation applied yet zatím nebyla použita žádná operace s cestami @msg no effect at index {k} na indexu {k} není žádný efekt @msg no end record chybí koncový záznam diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..43047695b7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3267,6 +3267,9 @@ liquify-list-end {0}, {1} {0} og {1} Effect Effekt Apply Last Effect Anvend sidste effekt Last Effect… Sidste effekt… + Apply Last Filter Anvend sidste filter + Last Filter… Sidste filter… + Apply {filter} Anvend {filter} Document Raster Effects Settings… Indstillinger for rastereffekter i dokumentet… Vector Effects Vektoreffekter 3D and Materials 3D og materialer @@ -7962,6 +7965,7 @@ imageTrace Outline Kontur @msg no document intet dokument @msg no document open intet åbent dokument @msg no effect applied yet ingen effekt er anvendt endnu +@msg no plug-in filter to repeat: run one from Object › Plug-ins first intet plug-in-filter at gentage: kør først et fra Objekt › Plug-ins @msg no Pathfinder operation applied yet ingen Pathfinder-handling er anvendt endnu @msg no effect at index {k} ingen effekt ved indeks {k} @msg no end record ingen slutpost diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..d21555193f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2079,6 +2079,9 @@ file-filter Templates Vorlagen Last Effect: {name} Letzter Effekt: {name} Last Effect: {} Letzter Effekt: {} Last Effect… Letzter Effekt… + Apply Last Filter Letzten Filter anwenden + Last Filter… Letzter Filter… + Apply {filter} {filter} anwenden Last Page Letzte Seite Latin Lateinisch Thai Thai @@ -5342,6 +5345,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg no document kein Dokument @msg no document open kein Dokument geöffnet @msg no effect applied yet noch kein Effekt angewendet +@msg no plug-in filter to repeat: run one from Object › Plug-ins first kein Plug-in-Filter zum Wiederholen: Führen Sie zuerst einen über Objekt › Plug-ins aus @msg no Pathfinder operation applied yet noch keine Pathfinder-Operation angewendet @msg no effect at index {k} kein Effekt bei Index {k} @msg no end record kein Endeintrag diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..1598edcb67 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1973,6 +1973,9 @@ font-technology Variable Μεταβλητές Last Effect: {name} Τελευταίο εφέ: {name} Last Effect: {} Τελευταίο εφέ: {} Last Effect… Τελευταίο εφέ… + Apply Last Filter Εφαρμογή τελευταίου φίλτρου + Last Filter… Τελευταίο φίλτρο… + Apply {filter} Εφαρμογή {filter} Last Page Τελευταία σελίδα Latin Extended Εκτεταμένα λατινικά Latin-1 Supplement Συμπλήρωμα Latin-1 @@ -5399,6 +5402,7 @@ digits Malayalam Μαλαγιάλαμ @msg no document δεν υπάρχει έγγραφο @msg no document open δεν υπάρχει ανοιχτό έγγραφο @msg no effect applied yet δεν έχει εφαρμοστεί ακόμη εφέ +@msg no plug-in filter to repeat: run one from Object › Plug-ins first δεν υπάρχει φίλτρο πρόσθετου για επανάληψη: εκτελέστε πρώτα ένα από το Αντικείμενο › Πρόσθετα @msg no Pathfinder operation applied yet δεν έχει εφαρμοστεί ακόμη λειτουργία Pathfinder @msg no effect at index {k} δεν υπάρχει εφέ στον δείκτη {k} @msg no end record λείπει η εγγραφή τέλους diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..34a83d6c7e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2077,6 +2077,9 @@ font-technology Variable Variables Last Effect: {name} Último efecto: {name} Last Effect: {} Último efecto: {} Last Effect… Último efecto… + Apply Last Filter Aplicar último filtro + Last Filter… Último filtro… + Apply {filter} Aplicar {filter} Last Page Última página Latin Latín Thai Tailandés @@ -5452,6 +5455,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg no document no hay documento @msg no document open no hay ningún documento abierto @msg no effect applied yet todavía no se aplicó ningún efecto +@msg no plug-in filter to repeat: run one from Object › Plug-ins first no hay ningún filtro de plugin que repetir: ejecute primero uno desde Objeto › Plugins @msg no Pathfinder operation applied yet todavía no se aplicó ninguna operación de Buscatrazos @msg no effect at index {k} no hay ningún efecto en el índice {k} @msg no end record no hay registro final diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..a7fd48794f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -550,6 +550,9 @@ Effect Tehoste Apply Last Effect Käytä viimeisintä tehostetta Last Effect… Viimeisin tehoste… + Apply Last Filter Käytä viimeisintä suodinta + Last Filter… Viimeisin suodin… + Apply {filter} Käytä: {filter} Document Raster Effects Settings… Asiakirjan rasteritehosteiden asetukset… Vector Effects Vektoritehosteet 3D and Materials 3D ja materiaalit @@ -5683,6 +5686,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no document ei asiakirjaa @msg no document open asiakirjaa ei ole auki @msg no effect applied yet tehostetta ei ole vielä käytetty +@msg no plug-in filter to repeat: run one from Object › Plug-ins first ei toistettavaa laajennussuodinta: suorita ensin yksi kohdasta Objekti › Laajennukset @msg no Pathfinder operation applied yet polunetsimen toimintoa ei ole vielä käytetty @msg no effect at index {k} ei tehostetta indeksissä {k} @msg no end record ei loppumerkintää diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..ca44149698 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2067,6 +2067,9 @@ font-technology Variable Variables Last Effect: {name} Dernier effet : {name} Last Effect: {} Dernier effet : {} Last Effect… Dernier effet… + Apply Last Filter Appliquer le dernier filtre + Last Filter… Dernier filtre… + Apply {filter} Appliquer {filter} Last Page Dernière page Latin Latin Thai Thaï @@ -5411,6 +5414,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg no document aucun document @msg no document open aucun document ouvert @msg no effect applied yet aucun effet appliqué pour l’instant +@msg no plug-in filter to repeat: run one from Object › Plug-ins first aucun filtre de module externe à répéter. Exécutez-en d’abord un depuis Objet › Modules externes @msg no Pathfinder operation applied yet aucune opération Pathfinder appliquée pour l’instant @msg no effect at index {k} aucun effet à l’indice {k} @msg no end record aucun enregistrement de fin diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..022f637b75 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2072,6 +2072,9 @@ Redos ફરીથી કરો Last Effect: {name} છેલ્લી ઇફેક્ટ: {name} Last Effect… છેલ્લી ઇફેક્ટ… + Apply Last Filter છેલ્લું ફિલ્ટર લાગુ કરો + Last Filter… છેલ્લું ફિલ્ટર… + Apply {filter} {filter} લાગુ કરો Last Page છેલ્લું પેજ Last commit છેલ્લો કમિટ Latin લેટિન diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..dbd77946f2 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3053,6 +3053,9 @@ arrowhead Feather पंख Last Effect: {} अंतिम इफ़ेक्ट: {} Last Effect: {name} अंतिम इफ़ेक्ट: {name} Last Effect… अंतिम इफ़ेक्ट… + Apply Last Filter पिछला फ़िल्टर लागू करें + Last Filter… अंतिम फ़िल्टर… + Apply {filter} {filter} लागू करें Last Page अंतिम पृष्ठ Latin लैटिन Latin Extended लैटिन विस्तारित @@ -8403,6 +8406,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg no document कोई डॉक्यूमेंट नहीं @msg no document open कोई डॉक्यूमेंट खुला नहीं है @msg no effect applied yet अभी तक लागू नहीं +@msg no plug-in filter to repeat: run one from Object › Plug-ins first दोहराने के लिए कोई प्लग-इन फ़िल्टर नहीं: पहले ऑब्जेक्ट › प्लग-इन्स से एक चलाएँ @msg no effect at index {k} इंडेक्स {k} पर कोई इफ़ेक्ट नहीं @msg no empty artboards to delete हटाने के लिए कोई खाली आर्टबोर्ड नहीं @msg no encoder for {_1} yet अभी तक {_1} के लिए कोई एनकोडर नहीं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..edaa4bca47 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2562,6 +2562,9 @@ file-filter Templates Sablonok Last Effect: {name} Legutóbbi effektus: {name} Last Effect: {} Legutóbbi effektus: {} Last Effect… Legutóbbi effektus… + Apply Last Filter Legutóbbi szűrő alkalmazása + Last Filter… Legutóbbi szűrő… + Apply {filter} {filter} alkalmazása Last Page Utolsó oldal Latin Latin Latin Extended Bővített latin @@ -6139,6 +6142,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg no document nincs dokumentum @msg no document open nincs megnyitott dokumentum @msg no effect applied yet még nincs alkalmazott effektus +@msg no plug-in filter to repeat: run one from Object › Plug-ins first nincs ismételhető bővítményszűrő: előbb futtasson egyet az Objektum › Bővítmények menüből @msg no Pathfinder operation applied yet még nincs alkalmazott útvonalkezelő-művelet @msg no effect at index {k} ezen az indexen nincs effektus: {k} @msg no end record nincs záró rekord diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..ed123d3079 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1144,6 +1144,9 @@ Effect Efek Apply Last Effect Terapkan efek terakhir Last Effect… Efek terakhir… + Apply Last Filter Terapkan filter terakhir + Last Filter… Filter terakhir… + Apply {filter} Terapkan {filter} Document Raster Effects Settings… Pengaturan efek raster dokumen… Vector Effects Efek vektor 3D and Materials 3D dan material @@ -5811,6 +5814,7 @@ imageTrace Outline Kontur @msg no document tidak ada dokumen @msg no document open tidak ada dokumen yang terbuka @msg no effect applied yet belum ada efek yang diterapkan +@msg no plug-in filter to repeat: run one from Object › Plug-ins first tidak ada filter plug-in untuk diulang: jalankan satu dari Objek › Plug-in terlebih dahulu @msg no Pathfinder operation applied yet belum ada operasi Pathfinder yang diterapkan @msg no effect at index {k} tidak ada efek pada indeks {k} @msg no end record tidak ada rekaman akhir diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..b07ca1c2fd 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2119,6 +2119,9 @@ file-filter Templates Modelli Last Effect: {name} Ultimo effetto: {name} Last Effect: {} Ultimo effetto: {} Last Effect… Ultimo effetto… + Apply Last Filter Applica ultimo filtro + Last Filter… Ultimo filtro… + Apply {filter} Applica {filter} Last Page Ultima pagina Latin Latino Thai Thailandese @@ -5479,6 +5482,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg no document nessun documento @msg no document open nessun documento aperto @msg no effect applied yet nessun effetto ancora applicato +@msg no plug-in filter to repeat: run one from Object › Plug-ins first nessun filtro plug-in da ripetere: eseguine prima uno da Oggetto › Plug-in @msg no Pathfinder operation applied yet nessuna operazione di elaborazione tracciati ancora applicata @msg no effect at index {k} nessun effetto all'indice {k} @msg no end record nessun record finale diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..3c6c2551c0 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -621,6 +621,9 @@ digits Malayalam マラヤーラム数字 Effect 効果 Apply Last Effect 前回の効果を適用 Last Effect… 前回の効果… + Apply Last Filter 前回のフィルターを適用 + Last Filter… 前回のフィルター… + Apply {filter} 「{filter}」を適用 Document Raster Effects Settings… ドキュメントのラスタライズ効果設定… Vector Effects ベクター効果 3D and Materials 3D とマテリアル @@ -5712,6 +5715,7 @@ variable-list-end {0}, {1} {0}、{1} @msg no PNG encoder PNG エンコーダーがありません @msg no document open ドキュメントが開かれていません @msg no effect applied yet まだ効果を適用していません +@msg no plug-in filter to repeat: run one from Object › Plug-ins first 繰り返すプラグインフィルターがありません:先にオブジェクト › プラグインからフィルターを実行してください @msg no Pathfinder operation applied yet まだパスファインダーの操作を適用していません @msg no such perspective grid preset 指定された遠近グリッドプリセットが見つかりません @msg no such recent file 指定された最近使ったファイルが見つかりません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..17aee7f63f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2683,6 +2683,9 @@ Effect ეფექტი Apply Last Effect ბოლო ეფექტის გამოყენება Last Effect… ბოლო ეფექტი… + Apply Last Filter ბოლო ფილტრის გამოყენება + Last Filter… ბოლო ფილტრი… + Apply {filter} გამოყენება: {filter} Document Raster Effects Settings… დოკუმენტის რასტრული ეფექტების პარამეტრები… Vector Effects ვექტორული ეფექტები 3D and Materials 3D და მასალები @@ -7217,6 +7220,7 @@ font-technology Variable ცვლადი @msg no document დოკუმენტი არ არის @msg no document open გახსნილი დოკუმენტი არ არის @msg no effect applied yet ეფექტი ჯერ არ გამოყენებულა +@msg no plug-in filter to repeat: run one from Object › Plug-ins first გასამეორებელი პლაგინის ფილტრი არ არის: ჯერ გაუშვით ერთი მენიუდან ობიექტი › პლაგინები @msg no Pathfinder operation applied yet ტრაექტორიების ოპერაცია ჯერ არ გამოყენებულა @msg no effect at index {k} ინდექსზე {k} ეფექტი არ არის @msg no end record დასასრულის ჩანაწერი არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..38deaa0017 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -614,6 +614,9 @@ digits Malayalam 말라얄람어 Effect 효과 Apply Last Effect 마지막 효과 적용 Last Effect… 마지막 효과… + Apply Last Filter 마지막 필터 적용 + Last Filter… 마지막 필터… + Apply {filter} {filter} 적용 Document Raster Effects Settings… 문서 래스터 효과 설정… Vector Effects 벡터 효과 3D and Materials 3D 및 재질 @@ -5641,6 +5644,7 @@ variable-list-end {0}, {1} {0} 및 {1} @msg no PNG encoder PNG 인코더가 없습니다 @msg no document open 열린 문서가 없습니다 @msg no effect applied yet 아직 적용된 효과가 없습니다 +@msg no plug-in filter to repeat: run one from Object › Plug-ins first 반복할 플러그인 필터가 없습니다: 먼저 개체 › 플러그인에서 필터를 실행하세요 @msg no Pathfinder operation applied yet 아직 적용된 패스파인더 작업이 없습니다 @msg no such perspective grid preset 해당 원근 격자 프리셋이 없습니다 @msg no such recent file 해당 최근 파일이 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..27bd12540e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1131,6 +1131,9 @@ liquify-list-end {0}, {1} {0} en {1} Effect Effect Apply Last Effect Laatste effect toepassen Last Effect… Laatste effect… + Apply Last Filter Laatste filter toepassen + Last Filter… Laatste filter… + Apply {filter} {filter} toepassen Document Raster Effects Settings… Instellingen voor documentrastereffecten… Vector Effects Vectoreffecten 3D and Materials 3D en materialen @@ -5833,6 +5836,7 @@ imageTrace Outline Contour @msg no document geen document @msg no document open geen document geopend @msg no effect applied yet nog geen effect toegepast +@msg no plug-in filter to repeat: run one from Object › Plug-ins first geen plug-infilter om te herhalen: voer er eerst een uit via Object › Plug-ins @msg no Pathfinder operation applied yet nog geen Pathfinder-bewerking toegepast @msg no effect at index {k} geen effect op index {k} @msg no end record geen eindrecord diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..f9c4bcc79b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -512,6 +512,9 @@ Effect Efekt Apply Last Effect Zastosuj ostatni efekt Last Effect… Ostatni efekt… + Apply Last Filter Zastosuj ostatni filtr + Last Filter… Ostatni filtr… + Apply {filter} Zastosuj {filter} Document Raster Effects Settings… Ustawienia efektów rastrowych dokumentu… Vector Effects Efekty wektorowe 3D and Materials 3D i materiały @@ -5583,6 +5586,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg no document brak dokumentu @msg no document open brak otwartego dokumentu @msg no effect applied yet nie zastosowano jeszcze żadnego efektu +@msg no plug-in filter to repeat: run one from Object › Plug-ins first brak filtra wtyczki do powtórzenia: najpierw uruchom jeden z menu Obiekt › Wtyczki @msg no Pathfinder operation applied yet nie zastosowano jeszcze żadnej operacji odnajdywania ścieżek @msg no effect at index {k} brak efektu o indeksie {k} @msg no end record brak rekordu końcowego diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..0524e74070 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1757,6 +1757,9 @@ antiAlias Sharp Nítido Polygonal Lasso Laço poligonal Last Effect: {name} Último Efeito: {name} Last Effect… Último Efeito… + Apply Last Filter Aplicar Último Filtro + Last Filter… Último Filtro… + Apply {filter} Aplicar {filter} Last Page Última Página Layer Options… Opções de Camada… Layers Camadas @@ -4719,6 +4722,7 @@ axis Both Ambos @msg no document nenhum documento @msg no document open nenhum documento aberto @msg no effect applied yet nenhum efeito aplicado ainda +@msg no plug-in filter to repeat: run one from Object › Plug-ins first nenhum filtro de plug-in para repetir: execute um em Objeto › Plug-ins primeiro @msg no Pathfinder operation applied yet nenhuma operação do Localizador de Caminhos aplicada ainda @msg no effect at index {k} nenhum efeito no índice {k} @msg no end record sem registro final diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..3fb2ab4a77 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2104,6 +2104,9 @@ file-filter Templates Шаблоны Last Effect: {name} Последний эффект: {name} Last Effect: {} Последний эффект: {} Last Effect… Последний эффект… + Apply Last Filter Применить последний фильтр + Last Filter… Последний фильтр… + Apply {filter} Применить {filter} Last Page Последняя страница Latin Латиница Thai Тайская @@ -5474,6 +5477,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg no document нет документа @msg no document open нет открытого документа @msg no effect applied yet эффект ещё не применён +@msg no plug-in filter to repeat: run one from Object › Plug-ins first нет фильтра модуля для повтора: сначала запустите фильтр из меню Объект › Модули @msg no Pathfinder operation applied yet операция обработки контуров ещё не применена @msg no effect at index {k} нет эффекта с индексом {k} @msg no end record нет конечной записи diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..3959e2d4e4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2020,6 +2020,9 @@ font-technology Variable Variabla Last Effect: {name} Senaste effekten: {name} Last Effect: {} Senaste effekten: {} Last Effect… Senaste effekten… + Apply Last Filter Använd senaste filtret + Last Filter… Senaste filtret… + Apply {filter} Använd {filter} Last Page Sista sidan Latin Latin Thai Thailändska @@ -5337,6 +5340,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg no document inget dokument @msg no document open inget dokument är öppet @msg no effect applied yet ingen effekt har använts än +@msg no plug-in filter to repeat: run one from Object › Plug-ins first inget pluginfilter att upprepa: kör först ett från Objekt › Plugins @msg no Pathfinder operation applied yet ingen banfinnaråtgärd har använts än @msg no effect at index {k} ingen effekt vid index {k} @msg no end record ingen slutpost diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..5ceb3638ae 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -517,6 +517,23 @@ fn attributes_panel_options_strings_are_in_complete_catalogs() { } } +/// Object › Plug-ins › Apply Last Filter and Last Filter…, the template that names Apply after the +/// filter, and the error when no filter can run again. +#[test] +fn last_filter_strings_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Apply Last Filter", "Last Filter…", "Apply {filter}"] { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + let none = crate::dialogs::plugin::NO_LAST_FILTER; + assert!(message_literals().contains(none)); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, none), none, "{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..8e60743a77 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1899,6 +1899,9 @@ font-technology Variable Değişken Last Effect: {name} Son Etki: {name} Last Effect: {} Son Etki: {} Last Effect… Son Etki… + Apply Last Filter Son Filtreyi Uygula + Last Filter… Son Filtre… + Apply {filter} {filter} Uygula Last Page Son Sayfa Latin Latince Thai Tay dili @@ -5162,6 +5165,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg no document belge yok @msg no document open hiçbir belge açık değil @msg no effect applied yet henüz hiçbir efekt uygulanmadı +@msg no plug-in filter to repeat: run one from Object › Plug-ins first yinelenecek eklenti filtresi yok: önce Nesne › Eklentiler menüsünden birini çalıştırın @msg no Pathfinder operation applied yet henüz hiçbir Yol Bulucu işlemi uygulanmadı @msg no effect at index {k} {k} endeksinde etkisi yok @msg no end record son kayıt yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..e214980e44 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2113,6 +2113,9 @@ file-filter Templates Шаблони Last Effect: {name} Останній ефект: {name} Last Effect: {} Останній ефект: {} Last Effect… Останній ефект… + Apply Last Filter Застосувати останній фільтр + Last Filter… Останній фільтр… + Apply {filter} Застосувати {filter} Last Page Остання сторінка Latin Латиниця Thai Тайська @@ -5463,6 +5466,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg no document немає документа @msg no document open немає відкритого документа @msg no effect applied yet ефект ще не застосований +@msg no plug-in filter to repeat: run one from Object › Plug-ins first немає фільтра модуля для повторення: спершу запустіть фільтр із меню Об’єкт › Модулі @msg no Pathfinder operation applied yet операцію обробки контурів ще не застосовано @msg no effect at index {k} немає ефекту з індексом {k} @msg no end record немає кінцевого запису diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..93eb2e36b9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2409,6 +2409,9 @@ digits Hindi Hindi Last Effect: {name} Hiệu ứng vừa dùng: {name} Last Effect: {} Hiệu ứng vừa dùng: {} Last Effect… Hiệu ứng vừa dùng… + Apply Last Filter Áp dụng bộ lọc cuối + Last Filter… Bộ lọc vừa dùng… + Apply {filter} Áp dụng {filter} Last Page Trang cuối Latin Latinh Latin Extended Latin mở rộng @@ -5833,6 +5836,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg no document không có tài liệu @msg no document open không có tài liệu nào đang mở @msg no effect applied yet chưa áp dụng hiệu ứng +@msg no plug-in filter to repeat: run one from Object › Plug-ins first không có bộ lọc plug-in nào để lặp lại: hãy chạy một bộ lọc từ Đối tượng › Plug-in trước @msg no Pathfinder operation applied yet chưa áp dụng thao tác Pathfinder @msg no effect at index {k} không có hiệu ứng tại chỉ mục {k} @msg no end record không có bản ghi kết thúc diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..e697fa0b5a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1994,6 +1994,9 @@ file-filter Templates 模板 Last Effect: {name} 最后一次效果:{name} Last Effect: {} 上次效果:{} Last Effect… 上次效果… + Apply Last Filter 应用上一次滤镜 + Last Filter… 上次滤镜… + Apply {filter} 应用“{filter}” Last Page 最后一页 Latin Extended 拉丁文扩充 Latin-1 Supplement 拉丁文-1 补充 @@ -5377,6 +5380,7 @@ imageTrace Outline 轮廓 @msg no PNG encoder 没有 PNG 编码器 @msg no document open 没有打开的文档 @msg no effect applied yet 尚未应用任何效果 +@msg no plug-in filter to repeat: run one from Object › Plug-ins first 没有可重复的增效工具滤镜:请先从“对象 › 增效工具”运行一个 @msg no Pathfinder operation applied yet 尚未应用任何路径查找器操作 @msg no such perspective grid preset 没有此透视网格预设 @msg no such recent file 没有此最近使用的文件 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..d954d6a1d2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2723,6 +2723,7 @@ file-filter Templates 範本 @msg no PNG encoder 沒有 PNG 編碼器 @msg no document open 沒有開啟的文件 @msg no effect applied yet 尚未套用任何效果 +@msg no plug-in filter to repeat: run one from Object › Plug-ins first 沒有可重複的增效模組濾鏡:請先從「物件 › 增效模組」執行一個 @msg no Pathfinder operation applied yet 尚未套用任何路徑管理員操作 @msg no such perspective grid preset 沒有這個透視格點預設集 @msg no such recent file 沒有這個最近使用的檔案 @@ -3387,6 +3388,9 @@ liquify-list-end {0}, {1} {0}和{1} Last Effect: {name} 最後一次效果:{name} Last Effect: {} 上次效果:{} Last Effect… 最後一次效果… + Apply Last Filter 套用上次的濾鏡 + Last Filter… 上次的濾鏡… + Apply {filter} 套用「{filter}」 Last Page 最後一頁 Latin 拉丁文 Thai 泰文 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a50527cede..f0e51a84cc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -165,6 +165,8 @@ pub struct VectorcraftApp { pub last_effect: Option<(String, serde_json::Value)>, /// Last successful destructive Pathfinder operation, repeated on the current selection. pub last_pathfinder: Option, + /// The parameters each object filter plug-in last ran with (Object › Plug-ins › Apply Last Filter). + pub last_filters: dialogs::plugin::LastFilters, /// Last confirmed Warp Options (bend, distortion, orientation) for the next new warp dialog. pub last_warp: Option, /// The Character panel field that takes the keyboard focus when the panel next draws it diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 61a4bf5872..15620b69f3 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -98,6 +98,12 @@ fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option Some((e, _)) => format!("Last Effect: {}", vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str())), None => label.into(), }, + // Apply Last Filter and Last Filter… are named after the filter that ran last. + crate::dialogs::plugin::APPLY_LAST | crate::dialogs::plugin::LAST => match crate::dialogs::plugin::last_filter_name(app) { + Some(name) if id == crate::dialogs::plugin::APPLY_LAST => format!("Apply {name}"), + Some(name) => format!("{name}…"), + None => label.into(), + }, // Edit Contents reads Edit Envelope while an envelope's contents are being edited. "object.envelope.editContents" => { let editing = app.session.active().is_some_and(|st| { @@ -192,6 +198,12 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } None => crate::i18n::tr_id(lang, id, label).to_string(), }, + // The filter's name is the plug-in's own text, never translated. + crate::dialogs::plugin::APPLY_LAST | crate::dialogs::plugin::LAST => match crate::dialogs::plugin::last_filter_name(app) { + Some(name) if id == crate::dialogs::plugin::APPLY_LAST => fmt(tl!("Apply {filter}"), &[("filter", &name)]), + Some(name) => format!("{name}…"), + None => crate::i18n::tr_id(lang, id, label).to_string(), + }, _ => { let shown = dynamic_label(app, id, label); if shows_a_name(id, &shown) { shown } else { crate::i18n::tr_id(lang, id, &shown).to_string() } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index aa9451d3f9..fa16a084e1 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1227,6 +1227,8 @@ fn run_ui_part13(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::print::open_preset(app, p), "plugin.dialog" => crate::dialogs::plugin::open(app, p), + crate::dialogs::plugin::APPLY_LAST => crate::dialogs::plugin::apply_last(app), + crate::dialogs::plugin::LAST => crate::dialogs::plugin::open_last(app), "ui.installPlugin" => io::install_plugin(app, p), "plugin.cancelRuns" => Ok(crate::plugin_runs::cancel_all(app)), "plugin.hideRuns" => Ok(crate::plugin_runs::hide_all(app)), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 5533352c18..96fa06d550 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -376,6 +376,10 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { "view.guides" | "view.grid" => !app.ui.view.trim_view, "view.refreshMonitorProfile" => app.session.prefs.monitor_profile_display && app.display_profile.has_reader(), "plugin.dialog" => app.session.active().is_some(), + // A filter may take no objects and add new ones, so no selection is needed. + crate::dialogs::plugin::APPLY_LAST | crate::dialogs::plugin::LAST => { + app.session.active().is_some() && crate::dialogs::plugin::last_filter(app).is_some() + } "ui.perspectiveGridDialog" | "ui.savePerspectivePreset" => app.session.active().is_some(), id if id.starts_with(crate::dialogs::perspective_presets::SLOT) => { app.session.active().is_some() && crate::dialogs::perspective_presets::slot_preset(app, id).is_some() diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 3e68b98c92..8ab4319992 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -396,7 +396,10 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { ], ), Sep, - sub("Plug-ins", [crate::addons::plugin_menu(), crate::dialogs::plugin::object_menu()].concat()), + sub( + "Plug-ins", + [crate::dialogs::plugin::last_filter_menu(), crate::addons::plugin_menu(), crate::dialogs::plugin::object_menu()].concat(), + ), ], ), ( diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..473d2d6f58 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1994,7 +1994,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "plugin.dialog", "Plug-in…", "", - "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns)", + "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter at the value the filter last ran with in this session, else its default, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns)", + ), + ( + "plugin.applyLastFilter", + "Apply Last Filter", + "", + "{} Object › Plug-ins › Apply : run the object filter that last ran in this session (a plugin.run that succeeded: its menu item, its dialog's OK, a request, a command.batch step or an action.batch step; not a plug-in's own commands) again on the selection with the same parameters, without its dialog, as one undo step; it runs in the background where its menu item would → plugin.run's result | {background: true, status}. An error with no document open, when no filter ran yet, when that filter was removed or installed again (the same module too) since, or when its manifest no longer takes those parameters as they are", + ), + ( + "plugin.lastFilter", + "Last Filter…", + "", + "{} Object › Plug-ins › …: open the dialog of the object filter that last ran in this session (see plugin.applyLastFilter) with the parameters it ran with (dialog `plugin`); OK runs it as one undo step and Cancel changes nothing. A filter without parameters runs at once. The same errors as plugin.applyLastFilter", ), ( "ui.installPlugin", diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index b1c2ae4594..2169b55e11 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -603,7 +603,7 @@ pub fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { } /// What the menus' rows depend on, cheaply (no allocation): commands run, the active document, -/// its revision (edits, selection and view changes), history and clipboard, the language, +/// its revision (edits, selection and view changes), history and clipboard, the filter plug-in that ran last, the language, /// shortcuts, plug-ins, the Scripts folder's listing, an open file dialog and the fonts (Type › Font lists the loaded fonts /// until the installed ones are scanned, then all of them, #5483). `input` forces a change on frames with a click or /// a key press, which covers what the hash doesn't list (panels shown, a tool picked). While an @@ -621,6 +621,8 @@ pub(crate) fn state_hash(app: &VectorcraftApp, input: Option) -> u64 { (d.uid, revision, d.history.undo.len(), d.history.redo.len(), d.transparency_grid, d.print_tiling).hash(&mut h); } (app.system_paste, app.last_effect.is_some(), app.ui.recent_files.len(), app.ui.recent_files.first(), app.recent_fonts().len()).hash(&mut h); + // Apply Last Filter and Last Filter… are named after the filter that ran last. + app.last_filters.last_id().hash(&mut h); app.file_dialog_open().hash(&mut h); (crate::i18n::current().code(), menus::plugin_revision(), crate::scripts_menu::revision(), crate::dialogs::proof_setup::saved_revision()) .hash(&mut h); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e0619ddaf7..5fea6e38fa 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -14,6 +14,7 @@ mod fonts; mod guide_escape; mod home; pub(super) mod labels; +mod last_filter; mod lifecycle; mod nativemenu; mod nativeoptions; diff --git a/crates/ui-egui/src/tests/last_filter.rs b/crates/ui-egui/src/tests/last_filter.rs new file mode 100644 index 0000000000..20b761062f --- /dev/null +++ b/crates/ui-egui/src/tests/last_filter.rs @@ -0,0 +1,317 @@ +//! Object › Plug-ins › Apply Last Filter and Last Filter…: the object filter that last ran in the +//! session runs again with the same parameters, or opens its dialog with them, and each filter's +//! dialog opens with the parameters it last ran with. Both items are off before a filter ran and +//! once that filter was removed or installed again. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_plugins::wat as tpl; + +use crate::dialogs::plugin::{APPLY_LAST, LAST, NO_LAST_FILTER}; +use crate::{VectorcraftApp, dialogs, menus, theme}; + +/// The whole-number parameter `n` of [`filter`]: 0 to 10, 3 by default. +const N: &str = r#"{"n":{"type":"int","min":0,"max":10,"default":3}}"#; + +/// An app with a new 200 × 200 pt document. +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.allow_plugin_grants_from_requests(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app +} + +/// A filter `id` named `name` with `params` that adds a 30 pt wide triangle when it is given `n` 7, +/// and a 50 pt square otherwise. +fn filter(id: &str, name: &str, params: &str) -> Vec { + let manifest = format!(r#"{{"id":"{id}","name":"{name}","version":"1","kind":"filter","params":{params}}}"#); + let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[30,0]},{"p":[15,20]}]}]}}]}"#; + let square = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[50,0]},{"p":[50,50]},{"p":[0,50]}]}]}}]}"#; + wat::parse_str(tpl::when_given_else(&manifest, tpl::Given::Params, r#""n":7"#, triangle, square)).unwrap() +} + +/// Installs `wasm`, in place of a plug-in with its id if there is one. +fn install(app: &mut VectorcraftApp, wasm: &[u8]) { + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(wasm), "replace": true})).unwrap(); +} + +/// The width of what a filter run returned as `ids`, in points. +fn width(app: &VectorcraftApp, ran: &Value) -> f64 { + let ids: Vec = ran["ids"].as_array().unwrap().iter().map(|i| vectorcraft_doc::NodeId(i.as_u64().unwrap())).collect(); + let r = app.session.doc().unwrap().doc.bounds_of(&ids, false).unwrap(); + r.x1 - r.x0 +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +/// One headless frame of the dialog layer, which previews the dialog's fields. +fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + let mut out = ctx.run_ui(Default::default(), |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); +} + +/// Both items are off, and say so when run, until a filter ran; then they are named after it, and +/// Apply runs it again with its parameters on what is selected now (nothing, here), without a +/// dialog, as one undo step. +#[test] +fn apply_last_filter_runs_the_last_filter_again_with_its_parameters() { + let mut app = app(); + let id = "test.ui.last.apply"; + install(&mut app, &filter(id, "Grow Shape", N)); + let entries = menus::menu_entries(&app); + let under: Vec<&str> = entries.iter().filter(|e| e.path == ["Object", "Plug-ins"]).map(|e| e.label.as_str()).take(2).collect(); + assert_eq!(under, ["Apply Last Filter", "Last Filter…"], "the first items of Object › Plug-ins"); + for cmd in [APPLY_LAST, LAST] { + assert!(!menus::enabled(&app, cmd), "{cmd} before any filter ran"); + assert_eq!(app.run(cmd, json!({})), Err(NO_LAST_FILTER.to_string())); + } + assert_eq!(menus::dynamic_label(&app, APPLY_LAST, "Apply Last Filter"), "Apply Last Filter"); + + let first = app.run("plugin.dialog", json!({"id": id, "params": {"n": 7}})).unwrap(); + assert_eq!(width(&app, &first), 30.0); + assert_eq!(app.last_filters.last_id(), Some(id)); + assert!(menus::enabled(&app, APPLY_LAST) && menus::enabled(&app, LAST)); + assert_eq!(menus::dynamic_label(&app, APPLY_LAST, "Apply Last Filter"), "Apply Grow Shape"); + assert_eq!(menus::dynamic_label(&app, LAST, "Last Filter…"), "Grow Shape…"); + assert_eq!(menus::display_label(&app, APPLY_LAST, "Apply Last Filter"), "Apply Grow Shape"); + + app.run("select.none", json!({})).unwrap(); + let undo = undo_len(&app); + let again = app.run(APPLY_LAST, json!({})).unwrap(); + assert!(app.ui.dialog.is_none(), "no dialog"); + assert_eq!(width(&app, &again), 30.0, "the same parameters: n 7"); + assert_ne!(again["ids"], first["ids"], "a new run"); + let st = app.session.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.undo.last().unwrap().label.as_str()), (undo + 1, "Grow Shape")); +} + +/// Last Filter… opens the dialog with the parameters the filter last ran with; Cancel changes +/// nothing, and OK runs it, with a kept preview or without one, the values it ran with becoming +/// the last ones. +#[test] +fn last_filter_opens_its_dialog_with_the_last_parameters() { + let mut app = app(); + let id = "test.ui.last.dialog"; + install(&mut app, &filter(id, "Grow Dialog…", N)); + app.run("plugin.dialog", json!({"id": id, "params": {"n": 7}})).unwrap(); + assert_eq!(menus::dynamic_label(&app, LAST, "Last Filter…"), "Grow Dialog…", "one ellipsis"); + app.run("select.none", json!({})).unwrap(); + let undo = undo_len(&app); + + app.run(LAST, json!({})).unwrap(); + let d = app.ui.dialog.as_ref().expect("its dialog"); + assert_eq!((d.kind.as_str(), d.str("__plugin"), d.fields.get("n")), (dialogs::plugin::KIND, id.to_string(), Some(&json!(7)))); + frame(&mut app); + dialogs::cancel(&mut app); + assert_eq!(undo_len(&app), undo, "Cancel changes nothing"); + + // OK with the preview kept. + app.run(LAST, json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("n".into(), json!(5)); + frame(&mut app); + assert!(app.session.in_interaction(), "previewing"); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(undo_len(&app), undo + 1); + app.run(LAST, json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("n"), Some(&json!(5)), "OK made 5 the last value"); + + // OK without a preview. + app.ui.dialog.as_mut().unwrap().fields.insert("n".into(), json!(7)); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(false)); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(undo_len(&app), undo + 2); + app.run("select.none", json!({})).unwrap(); + let again = app.run(APPLY_LAST, json!({})).unwrap(); + assert_eq!(width(&app, &again), 30.0); +} + +/// Each filter's own dialog opens with the parameters that filter last ran with, never another +/// filter's; one that hasn't run opens with its defaults. +#[test] +fn each_filter_dialog_opens_with_its_own_last_parameters() { + let mut app = app(); + let (a, b, c) = ("test.ui.last.own.a", "test.ui.last.own.b", "test.ui.last.own.c"); + for (id, name) in [(a, "Own A"), (b, "Own B"), (c, "Own C")] { + install(&mut app, &filter(id, name, N)); + } + app.run("plugin.dialog", json!({"id": a, "params": {"n": 7}})).unwrap(); + app.run("plugin.dialog", json!({"id": b, "params": {"n": 2}})).unwrap(); + app.run("plugin.dialog", json!({"id": a, "params": {"n": 8}})).unwrap(); + app.run("plugin.dialog", json!({"id": b, "params": {"n": 1}})).unwrap(); + assert_eq!(app.last_filters.last_id(), Some(b)); + for (id, n) in [(a, 8), (b, 1), (c, 3)] { + app.run("plugin.dialog", json!({"id": id})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("n"), Some(&json!(n)), "{id}"); + dialogs::cancel(&mut app); + } +} + +/// A batch step, a direct `plugin.run` and an Action Batch step count; a failed run, a plug-in's own +/// command and a live effect don't. +#[test] +fn only_successful_filter_runs_become_the_last_filter() { + let mut app = app(); + let id = "test.ui.last.kinds"; + install(&mut app, &filter(id, "Kinds", N)); + assert!(app.run("plugin.run", json!({"id": id, "params": {"n": "seven"}})).is_err()); + assert_eq!(app.last_filters.last_id(), None, "a run that failed"); + + let steps = json!({"commands": [{"command": "plugin.run", "params": {"id": id, "params": {"n": 7}}}]}); + app.run("command.batch", steps).unwrap(); + assert_eq!(app.last_filters.last_id(), Some(id), "a batch step"); + app.run("plugin.dialog", json!({"id": id})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("n"), Some(&json!(7))); + dialogs::cancel(&mut app); + + let other = "test.ui.last.kinds.other"; + install(&mut app, &filter(other, "Other", N)); + app.run("plugin.run", json!({"id": other, "n": 2})).unwrap(); + assert_eq!(app.last_filters.last_id(), Some(other), "a direct run, its parameters as top-level keys"); + app.run("plugin.dialog", json!({"id": other})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("n"), Some(&json!(2))); + dialogs::cancel(&mut app); + + let cmds = "test.ui.last.cmds"; + let manifest = format!(r#"{{"id":"{cmds}","name":"Cmds","version":"1","kind":"filter","commands":[{{"id":"grow","label":"Grow"}}]}}"#); + let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[5,0]},{"p":[5,5]}]}]}}]}"#; + install(&mut app, &wat::parse_str(tpl::returning(&manifest, triangle)).unwrap()); + app.run("plugin.test.ui.last.cmds.grow", json!({})).unwrap(); + assert_eq!(app.last_filters.last_id(), Some(other), "a plug-in's own command"); + + let fx = tpl::module(&tpl::manifest("test.ui.last.fx", "effect", "{}"), tpl::ECHO, "", 1); + install(&mut app, &wat::parse_str(fx).unwrap()); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("effect.apply", json!({"effect": "plugin.test.ui.last.fx"})).unwrap(); + assert_eq!(app.last_filters.last_id(), Some(other), "a live effect"); + + // Action Batch over the document's data sets counts once a data set ran the step. + app.run("dataset.new", json!({"name": "a"})).unwrap(); + let steps = json!([{"command": "plugin.run", "params": {"id": id, "params": {"n": 5}}}]); + let r = app.run("action.batch", json!({"source": "datasets", "commands": steps})).unwrap(); + assert_eq!((r["count"].clone(), r["failed"].clone()), (json!(1), json!(0)), "{r}"); + assert_eq!(app.last_filters.last_id(), Some(id), "an Action Batch step"); + app.run("plugin.dialog", json!({"id": id})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("n"), Some(&json!(5))); + dialogs::cancel(&mut app); +} + +/// Installing the plug-in again, even the same module, another module with its id, one whose +/// manifest no longer takes the parameters, and removing it turn both items off, and the new +/// module's dialog opens with its own defaults. Installing another plug-in keeps them. +#[test] +fn the_last_filter_is_off_once_its_plugin_is_removed_or_replaced() { + let mut app = app(); + let id = "test.ui.last.stale"; + let wasm = filter(id, "Stale", N); + install(&mut app, &wasm); + app.run("plugin.dialog", json!({"id": id, "params": {"n": 7}})).unwrap(); + install(&mut app, &filter("test.ui.last.unrelated", "Unrelated", N)); + assert!(menus::enabled(&app, APPLY_LAST), "another plug-in installed"); + install(&mut app, &wasm); + assert!(!menus::enabled(&app, APPLY_LAST), "the same module again"); + app.run("plugin.dialog", json!({"id": id, "params": {"n": 7}})).unwrap(); + + // Another module and then the first one again: the run with the first one doesn't come back. + install(&mut app, &filter(id, "Stale", r#"{"n":{"type":"int","min":0,"max":20,"default":3}}"#)); + install(&mut app, &wasm); + assert!(!menus::enabled(&app, APPLY_LAST), "replaced, then the module that ran installed again"); + + install(&mut app, &filter(id, "Stale", r#"{"n":{"type":"choice","options":["a","b"],"default":"b"}}"#)); + for cmd in [APPLY_LAST, LAST] { + assert!(!menus::enabled(&app, cmd), "{cmd} once the parameters no longer fit"); + assert_eq!(app.run(cmd, json!({})), Err(NO_LAST_FILTER.to_string())); + } + assert_eq!(menus::dynamic_label(&app, APPLY_LAST, "Apply Last Filter"), "Apply Last Filter"); + app.run("plugin.dialog", json!({"id": id})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("n"), Some(&json!("b")), "the new module's default"); + dialogs::cancel(&mut app); + + install(&mut app, &filter(id, "Stale", r#"{"n":{"type":"int","min":0,"max":20,"default":3}}"#)); + assert!(!menus::enabled(&app, APPLY_LAST), "another module, though it takes n 7"); + app.run("plugin.dialog", json!({"id": id, "params": {"n": 7}})).unwrap(); + assert!(menus::enabled(&app, APPLY_LAST)); + app.run("plugin.remove", json!({"id": id})).unwrap(); + assert!(!menus::enabled(&app, APPLY_LAST) && !menus::enabled(&app, LAST), "removed"); + assert_eq!(app.run(APPLY_LAST, json!({})), Err(NO_LAST_FILTER.to_string())); + + // A batch that runs the filter and then replaces its module. + install(&mut app, &wasm); + let other = filter(id, "Stale", r#"{"n":{"type":"int","min":0,"max":20,"default":3}}"#); + let steps = json!([ + {"command": "plugin.run", "params": {"id": id, "params": {"n": 7}}}, + {"command": "plugin.install", "params": {"dataBase64": vectorcraft_format::base64_encode(&other), "replace": true}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!(app.last_filters.last_id(), Some(id)); + assert!(!menus::enabled(&app, APPLY_LAST) && !menus::enabled(&app, LAST), "replaced after it ran in the batch"); + + // A batch that runs the filter and then installs another plug-in keeps it. + install(&mut app, &wasm); + let unrelated = filter("test.ui.last.unrelated", "Unrelated", N); + let steps = json!([ + {"command": "plugin.run", "params": {"id": id, "params": {"n": 7}}}, + {"command": "plugin.install", "params": {"dataBase64": vectorcraft_format::base64_encode(&unrelated), "replace": true}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(menus::enabled(&app, APPLY_LAST), "another plug-in installed after it ran in the batch"); + + // A batch that runs the filter, removes it and installs the same module again. + let steps = json!([ + {"command": "plugin.run", "params": {"id": id, "params": {"n": 7}}}, + {"command": "plugin.remove", "params": {"id": id}}, + {"command": "plugin.install", "params": {"dataBase64": vectorcraft_format::base64_encode(&wasm), "replace": true}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert!(!menus::enabled(&app, APPLY_LAST), "installed again in the batch after it ran"); +} + +/// A filter that runs in the background becomes the last filter only when its result is applied: +/// starting it or canceling it doesn't. Apply Last Filter starts it in the background as its menu +/// item does. With no document open both items are off. +#[test] +fn a_background_run_becomes_the_last_filter_only_when_applied() { + let mut app = app(); + let id = "test.ui.last.heavy"; + let manifest = format!(r#"{{"id":"{id}","name":"Heavy Last","version":"1","kind":"filter","budget":"heavy"}}"#); + let wasm = wat::parse_str(tpl::spinning(&manifest, 1_000_000_000, r#"{"objects":[]}"#)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "allowHeavy": true})).unwrap(); + assert_eq!(app.run("plugin.dialog", json!({"id": id})).unwrap()["background"], true); + assert_eq!(app.last_filters.last_id(), None, "started"); + crate::plugin_runs::cancel_all(&mut app); + crate::plugin_runs::poll(&mut app); + assert_eq!(app.last_filters.last_id(), None, "canceled"); + + // As its result would be applied: `plugin.run` with its parameters. + dialogs::plugin::record(&mut app, &json!({"id": id, "params": {}})); + assert_eq!(app.run(APPLY_LAST, json!({})).unwrap()["background"], true, "in the background, as its menu item runs it"); + crate::plugin_runs::cancel_all(&mut app); + + // A filter with parameters, so Last Filter… would open its dialog. + let with_params = "test.ui.last.nodoc"; + install(&mut app, &filter(with_params, "No Document", N)); + let mut empty = VectorcraftApp::new(Session::new(), Default::default()); + dialogs::plugin::record(&mut empty, &json!({"id": with_params, "params": {"n": 7}})); + assert_eq!(empty.last_filters.last_id(), Some(with_params)); + assert!(!menus::enabled(&empty, APPLY_LAST) && !menus::enabled(&empty, LAST), "no document"); + assert_eq!(dialogs::plugin::apply_last(&mut empty), Err("no document open".into())); + assert_eq!(dialogs::plugin::open_last(&mut empty), Err("no document open".into())); + assert!(empty.ui.dialog.is_none(), "no dialog opens without a document"); +} + +/// The native menu reads its rows again when the filter that ran last changes, also when nothing +/// else changed. +#[test] +fn the_native_menu_follows_the_last_filter() { + let mut app = app(); + let (a, b) = ("test.ui.last.native.a", "test.ui.last.native.b"); + install(&mut app, &filter(a, "Native A", N)); + install(&mut app, &filter(b, "Native B", N)); + dialogs::plugin::record(&mut app, &json!({"id": a, "params": {}})); + let before = crate::native_menu::state_hash(&app, None); + dialogs::plugin::record(&mut app, &json!({"id": b, "params": {}})); + assert_ne!(crate::native_menu::state_hash(&app, None), before); +} diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..215379996e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13341,7 +13341,14 @@ A plug-in of API level 2 (`api: 2` in its entry) that lists `progress` may repor log lines: `notifications/cancelled` makes its `vc_cancelled` return 1, and its log lines go to the server's log under its id. With a desktop app connected, `plugin.dialog` runs such a filter (one without a `commandAllowlist`) in the background when it runs at once or OK runs it with Preview off, and returns `{background: true, status}`; -`plugin.cancelRuns` stops it. One that lists `settings` or `cache` keeps settings or a cache of its own in the `Plug-ins` folder +`plugin.cancelRuns` stops it. With a desktop app connected, `plugin.applyLastFilter {}` (Object › Plug-ins › Apply +Last Filter) runs the object filter whose `plugin.run` last succeeded in the app's session again on the selection, with +the same parameters and without a dialog, and returns `plugin.run`'s result, or `{background: true, status}` for a +filter that runs in the background; `plugin.lastFilter {}` (Last Filter…) opens its dialog with those parameters +instead. Both return an error with no document open, before a filter ran and once that filter was removed, installed +again (the same module too) or no longer takes the parameters as they are; `plugin.dialog {id}` opens a filter's dialog with the +parameters it last ran with. A plug-in's own commands and live effects don't change what they run. A plug-in that +lists `settings` or `cache` keeps settings or a cache of its own in the `Plug-ins` folder (VectorCraft's own caps: 256 settings and 1 MiB, 512 MiB of cache): `plugin.list` and `plugin.info` give the cache's size as `cacheBytes`, `plugin.clearCache {id?}` empties the cache of one plug-in or of all of them and returns `{cleared: [id], bytesFreed}`, replacing a plug-in keeps both, and `plugin.remove` deletes both (also for an id that diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..fe3e2a4161 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -58,7 +58,22 @@ In the app, installed filters appear under **Object › Plug-ins**, next to **In Plug-ins**; live effects under **Effect › Plug-ins** and in the Appearance panel's effect menu. A plug-in with parameters gets a dialog generated from its schema (numbers, whole numbers, checkboxes, dropdowns, text, lists of numbers and colors, labelled, explained and sorted into sections as its manifest says) with a live preview; without -parameters it runs at once. Edit › Keyboard Shortcuts lists each installed filter under Object › Plug-ins, where +parameters it runs at once. A filter's dialog opens with the parameters that filter last ran with in the session, +else with its defaults. Object › Plug-ins starts with **Apply Last Filter** (`plugin.applyLastFilter`), which runs +the filter that last ran again with the same parameters on the selection, without its dialog, as one undo step, and +**Last Filter…** (`plugin.lastFilter`), which opens that filter's dialog with those parameters, its OK running it as a +new run. Once a filter has run they read **Apply** followed by the filter's name and the filter's name with an +ellipsis. A run counts once it succeeds: from its menu item, its dialog's OK, a shortcut, `plugin.run` or a +`command.batch` step (the last such step of the batch), an Action Batch (`action.batch`) step once a file or data set +ran it, and a background run once its +result is applied. A preview, Cancel, a failed or canceled run, a plug-in's own commands and live effects don't count, +and neither does a batch step whose filter the batch installed when a later step of the batch installs, removes or +reloads plug-ins. Both items are grayed out with no document open, before any filter ran, and once the filter that +ran last was removed, installed again (the same module too) or no longer takes those parameters as they are; +installing another plug-in keeps them. They don't need a selection: a filter given no objects can still add new ones. The parameters are +kept for the session only, for at most 64 filters. Where the two items sit, when they are grayed out and how long the +parameters are kept are VectorCraft's own rules. Edit › Keyboard Shortcuts lists each installed filter under Object › +Plug-ins, where it can be given a shortcut (`plugin:`); the shortcut stays saved while the plug-in is removed and applies again when it is reinstalled. Parameters too many for the window's height scroll inside the dialog, which keeps its heading and buttons in view. Exporters are formats of **File › Export › Export As**, where Use Artboards is greyed out @@ -891,4 +906,5 @@ per change of their input, parameters or paints (results are cached), not per fr - Live effects that change opacity, blending or effects (at `api` 2 one may [paint](#painted-live-effects) the pieces it returns), and filters that change type, images or symbol instances (a filter at `api` 2 reads them, see [`inputs`](#reading-type-images-and-symbols)). -- Apply Last Effect and Last Effect work for plug-in effects; there is no "last filter" for object filters yet. +- Scripts can't run object filters (`plugin.*` commands are refused there), so a script doesn't change what Apply + Last Filter runs. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..b8a5e7a2cc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2654,6 +2654,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. +- **Apply Last Filter and Last Filter… for filter plug-ins (G17):** Object › Plug-ins starts with Apply Last Filter (`plugin.applyLastFilter`), which runs the filter plug-in that last ran in the session again with the same parameters on the selection, without its dialog, as one undo step, and Last Filter… (`plugin.lastFilter`), which opens that filter's dialog with those parameters; once a filter has run, both items are named after it. [The help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=357) describes the same pair for filters: one item repeats the last filter with its last settings, the other opens its options. Each filter's own dialog opens with the parameters that filter last ran with. A heavy filter repeats in the background as its menu item runs it. Both items are grayed out with no document open, before a filter ran, and once that filter was removed, installed again or no longer takes the parameters as they are; they don't need a selection (VectorCraft's own rules). Regressions: `crates/ui-egui/src/tests/last_filter.rs`, `crates/ui-egui/src/i18n/tests.rs`. Scores and hours unchanged. - **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode ` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. - **Hang report and Copy Troubleshooting Info:** when the desktop app's interface thread stays in one part of a frame for 3 s (VectorCraft's own value), a watching thread writes a hang report to the log and to `logs/hang-report-.txt`, and removes the file when the interface answers again. A later launch that finds a report no process holds writes it to the log, keeps it as `logs/hang-report.1.txt` and, unless another start-up message is showing, says so in the status bar. Help › Copy Troubleshooting Info (`help.copyTroubleshootingInfo`) copies the platform facts, the recent commands and frame times, and the reports of this session and the last one. Regressions: `apps/vectorcraft/src/hang_watch/tests.rs`, `crates/ui-egui/src/hang_beacon.rs`, `crates/ui-egui/src/troubleshooting.rs`. Scores and hours unchanged. From e48b8117075f3b4b9d50820212ba1724cc746a57 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:02:06 -0800 Subject: [PATCH 045/101] Scripts: an opacity a graph mark already has replaces the one its series keeps Assigning PageItem.opacity skipped object.setProps when the item already had that opacity, so a graph mark or label set to the opacity it shows left the graph keeping the opacity another mark of its series or kind had set. The setter now leaves the no-op check to object.setProps, as the command does for that case. A value within the getter's rounding of the item's opacity sends the opacity the item has, so assigning the opacity a script read back still changes nothing and adds no undo step. --- crates/engine/src/script/dom.rs | 8 +++++- crates/engine/src/tests/script_dom.rs | 36 +++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 830351f375..e073a791ff 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1432,7 +1432,13 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - set_props(h, a, |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v})) + // A value the getter reports for the item's opacity sends the opacity it has, and + // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still + // replaces the one the graph keeps for its series or kind. + let item = this_item(h, a)?; + let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0)); + let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v); + set_props(h, a, |_| false, json!({"opacity": v})) } fn item_selected(h: &Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 7ebad8e3f2..f517312983 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -206,6 +206,42 @@ fn page_item_properties_join_one_undo_step() { } } +/// An opacity a graph mark already has still replaces the opacity another mark of its series left on +/// the graph, as `object.setProps` does. +#[test] +fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let r = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let kept = + |s: &Session| s.active().unwrap().doc.node(id).unwrap().extras().graph.as_deref().unwrap().series_paints.first().and_then(|p| p.opacity); + let series = |s: &Session| { + let n = s.active().unwrap().doc.node(id).unwrap().clone(); + let group = n.children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + group.children().unwrap().iter().map(|m| m.id).collect::>() + }; + let marks = series(&s); + s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 50})).unwrap(); + assert_eq!(kept(&s), Some(0.5)); + s.execute("object.setProps", &json!({"id": series(&s)[1].0, "name": "mark"})).unwrap(); + log(&mut s, "app.activeDocument.pageItems.getByName('mark').opacity = 100;"); + assert_eq!(kept(&s), None); +} + +/// Assigning an item the opacity it reports, rounded to four decimals, changes nothing. +#[test] +fn assigning_the_reported_opacity_changes_nothing() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 100.0 / 3.0})).unwrap(); + let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; vc.log(i.opacity); i.opacity = i.opacity;"); + assert_eq!(out, vec![json!(33.3333)]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); From c664ce630b82faae1a6356c78a09c278252f8108 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:20:07 -0800 Subject: [PATCH 046/101] =?UTF-8?q?Plug-ins:=20importers=20whose=20manifes?= =?UTF-8?q?t=20sets=20place=20also=20read=20files=20for=20File=20=E2=80=BA?= =?UTF-8?q?=20Place?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An importer plug-in with "place": true in its manifest now reads its files for File › Place as well as File › Open. file.place, file.place.info and file.place.queue take importer and params; without importer, a file no built-in format reads goes to the first placing importer by id that lists its extension. The importer is given at most 128 MiB of the file (a larger file is refused from its size before it is read) with _context.mode "place", and its objects, guides left out, become one group named after the file, as one undo step, embedded. A decline, invalid output, a trap or Cancel places nothing. - The Place dialog lists placing importers' extensions under "All placeable files" and in a filter named after each importer. - On the web, a placing importer's file dropped on the canvas is placed. - A file placed with a named importer skips the text, PDF, DXF and PSD import options. - document.formats and plugin.list mark placing importers with place: true; place on any other kind is refused at install. Docs: docs/plugins.md, docs/mcp.md, docs/gaps.md, docs/target-app-parity.md. --- apps/vectorcraft-web/src/web.rs | 8 +- apps/vectorcraft/src/host_services.rs | 2 +- crates/engine/src/cmd/fileio.rs | 6 +- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/formats.rs | 71 ++++- crates/engine/src/cmd/fileio/importer.rs | 211 +++++++++---- crates/engine/src/cmd/place.rs | 37 ++- crates/engine/src/cmd/plugin.rs | 5 +- crates/engine/tests/plugin_place.rs | 282 ++++++++++++++++++ crates/plugins/src/import.rs | 47 ++- crates/plugins/src/manifest.rs | 36 +++ crates/ui-egui/src/dialogs/tests.rs | 1 + .../src/dialogs/tests_plugin_import.rs | 48 +++ 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 + crates/ui-egui/src/place.rs | 15 +- docs/gaps.md | 3 + docs/mcp.md | 8 +- docs/plugins.md | 41 ++- docs/target-app-parity.md | 1 + 43 files changed, 781 insertions(+), 93 deletions(-) create mode 100644 crates/engine/tests/plugin_place.rs diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 6d9e0cadd5..9e23e4044f 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -482,10 +482,12 @@ fn services( let inbox = picked.clone(); let ctx = place_ctx.clone(); wasm_bindgen_futures::spawn_local(async move { - let dialog = - fileio::place_filters().fold(rfd::AsyncFileDialog::new().set_title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { + let dialog = fileio::place_dialog_filters().fold( + rfd::AsyncFileDialog::new().set_title(vectorcraft_ui_egui::i18n::t("Place")), + |d, (name, exts)| { d.add_filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts) - }); + }, + ); let Some(files) = dialog.pick_files().await else { return; }; diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 3efdb9f93f..ca9558daa5 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -75,7 +75,7 @@ fn dialog_for(d: D, request: &PickRequest) -> D { let pick = match request { PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick, PickRequest::OpenMany => { - return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { + return fileio::place_dialog_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { d.filter( vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), &open_extensions(exts, CASE_SENSITIVE_FILTERS), diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 4fcb2bf4fc..f6ee2beb31 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -37,7 +37,7 @@ mod encode; pub mod eps; mod export; pub(crate) mod imagemap; -mod importer; +pub(crate) mod importer; pub mod jxlread; mod legacy_ai; mod load; @@ -167,8 +167,8 @@ use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable}; pub use formats::{ DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters, export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions, - open_filters, opens_as_other, opens_with_importer, place_filters, plugin_formats, read_extensions, readable_format, readable_format_for_name, - titled_for_export, writable_format, + open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_filters, places_with_importer, plugin_formats, read_extensions, + readable_format, readable_format_for_name, titled_for_export, writable_format, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index a41831b200..0c03b1ea11 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "File Formats", [], None, - "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}", + "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list), place?: true (an importer's format whose files file.place also reads, see file.place's importer)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}", always, formats ), diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 0db990ad4c..0272bab874 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -737,11 +737,26 @@ fn format_filters() -> impl Iterator bool { let ext = extension(name); - !ext.is_empty() && !PLACE_EXTS.contains(&ext.as_str()) && !vectorcraft_plugins::import::for_extension(&ext).is_empty() + !ext.is_empty() + && !PLACE_EXTS.contains(&ext.as_str()) + && !vectorcraft_plugins::import::for_extension(&ext).is_empty() + && !places_with_importer(name) +} + +/// Whether File › Place places a file named `name` with an importer plug-in when no built-in format +/// reads its content: no built-in format reads its extension, and an installed importer whose manifest +/// sets `place` lists it. +pub fn places_with_importer(name: &str) -> bool { + let ext = extension(name); + !ext.is_empty() + && readable_format(&ext).is_none() + && !PLACE_EXTS.contains(&ext.as_str()) + && !vectorcraft_plugins::import::placing(&ext).is_empty() } /// Whether File › Open opens a file of extension `ext` (lower case) as something other than a @@ -871,6 +886,53 @@ pub fn place_filters() -> impl Iterator ImporterPart { + use vectorcraft_plugins::{import, registry}; + static MADE: std::sync::Mutex> = std::sync::Mutex::new(None); + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + let revision = registry::revision(); + if let Some((r, part)) = made.as_ref() + && *r == revision + { + return part.clone(); + } + let mut exts: Vec<&'static str> = PLACE_EXTS.to_vec(); + let mut filters = Vec::new(); + for p in import::installed().into_iter().filter(|p| p.manifest().place) { + let m = p.manifest(); + let own: Vec<&'static str> = + m.extensions.iter().filter(|e| readable_format(e).is_none() && !PLACE_EXTS.contains(&e.as_str())).map(|e| registry::intern(e)).collect(); + if own.is_empty() { + continue; + } + for &e in &own { + if !exts.contains(&e) { + exts.push(e); + } + } + let own: &'static [&'static str] = Box::leak(own.into_boxed_slice()); + filters.push((registry::intern(&m.name), own)); + } + let exts: &'static [&'static str] = if exts.len() == PLACE_EXTS.len() { PLACE_EXTS } else { Box::leak(exts.into_boxed_slice()) }; + let part = (exts, filters); + *made = Some((revision, part.clone())); + part +} + +/// File › Place's own dialog filters: [`place_filters`], with the extensions of the installed +/// importer plug-ins that place their files in "All placeable files" and one filter per such +/// importer after the others, under its name ([`places_with_importer`]). Pickers that relink an +/// image use [`place_filters`]. +pub fn place_dialog_filters() -> impl Iterator { + let (all, importers) = importer_place_part(); + std::iter::once(("All placeable files", all)).chain(place_filters().skip(1)).chain(importers) +} + /// A format by id or extension (any case, leading dot allowed; `jpeg` finds `jpg`): a built-in /// one, else one a plug-in adds ([`plugin_formats`]), an exporter's before an importer's for an /// extension both list. A built-in format keeps its extension, so an exporter or importer that @@ -1021,6 +1083,9 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result { let mut v = f.to_json(); if let Some(id) = vectorcraft_plugins::export::plugin_id(f.id) { v["plugin"] = json!(id); + if vectorcraft_plugins::import::by_format(f.id).is_some_and(|p| p.manifest().place) { + v["place"] = json!(true); + } } v }; diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index 3ba6c6fa19..53af9314a4 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -1,58 +1,118 @@ -//! `document.open` of the files importer plug-ins read ([`vectorcraft_plugins::import`]). +//! `document.open` and `file.place` of the files importer plug-ins read +//! ([`vectorcraft_plugins::import`]). //! //! A file opens with an importer when `importer` names one (its format id, `plugin.`), which //! must list the file's extension, or when no built-in format reads the file, by its content or by //! its extension, and an importer lists its extension (the one whose id sorts first, when several //! do). A built-in format that can't read a damaged file reports its own error: the file is not -//! handed to an importer instead. Place reads only the built-in formats. +//! handed to an importer instead. File › Place uses an importer by the same rules, among the +//! importers whose manifests set `place` ([`named_for_place`], [`for_place`]). //! //! The importer is given the file's bytes, at most [`import::MAX_INPUT_BYTES`] of them: a file //! named by `path` that only an importer can read is read no further than that. Its objects become -//! a new document whose artboard is their bounds, and nothing opens when the importer fails, -//! declines, is cancelled or returns objects that don't pass the checks a filter's output does. +//! a new document whose artboard is their bounds (or, to place, the art of one group), and nothing +//! opens or is placed when the importer fails, declines, is cancelled or returns objects that don't +//! pass the checks a filter's output does. use std::sync::Arc; use serde_json::Value; -use vectorcraft_doc::{Document, MAX_COORD}; +use vectorcraft_doc::{Document, MAX_COORD, NodeId}; use vectorcraft_geom::Rect; -use vectorcraft_plugins::{Plugin, export, import, objects}; +use vectorcraft_plugins::import::Mode; +use vectorcraft_plugins::{Manifest, Plugin, export, import, objects}; use super::super::{Result, bad, str_param}; -use super::load::{Loaded, detect, file_name}; -use super::{err, extension, file_stem, format}; +use super::load::{Loaded, Source, detect, file_name}; +use super::{Format, err, extension, file_stem, format}; use crate::EngineError; const C: &str = "document.open"; -/// The importer `document.open`'s params `p` name (`importer`), if any; a value that isn't a -/// string is an error. -fn named(p: &Value) -> Result> { +/// The importer command `cmd`'s params `p` name (`importer`), if any; a value that isn't a string +/// is an error. +fn named<'a>(p: &'a Value, cmd: &str) -> Result> { match p.get("importer").filter(|v| !v.is_null()) { None => Ok(None), - Some(v) => v.as_str().map(Some).ok_or_else(|| bad(C, "`importer` must be a plug-in format id (see document.formats)")), + Some(v) => v.as_str().map(Some).ok_or_else(|| bad(cmd, "`importer` must be a plug-in format id (see document.formats)")), } } +/// Checks that importer `m` lists the extension of the file `name`: else command `cmd`'s error, +/// which names the extensions it lists. +fn check_extension(cmd: &str, m: &Manifest, name: &str) -> Result<()> { + if m.extensions.contains(&extension(name)) { + return Ok(()); + } + let shown = vectorcraft_plugins::permissions::display_text(&m.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + let exts: Vec = m.extensions.iter().map(|e| format!(".{e}")).collect(); + Err(bad(cmd, format!("“{shown}” opens {} files, not `{}`", exts.join(", "), file_name(name)))) +} + /// The importer that opens the file `name` holding `bytes` with `document.open`'s params `p`: the /// one `importer` names, which must list the file's extension; else, when no built-in format reads /// the file, the first installed importer that lists its extension; else `None`. pub(super) fn pick(name: &str, bytes: &[u8], p: &Value) -> Result>> { - let ext = extension(name); - if let Some(id) = named(p)? { + if let Some(id) = named(p, C)? { let plugin = import::named(id).map_err(|e| bad(C, e.to_string()))?; - let m = plugin.manifest(); - if !m.extensions.contains(&ext) { - let shown = vectorcraft_plugins::permissions::display_text(&m.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); - let exts: Vec = m.extensions.iter().map(|e| format!(".{e}")).collect(); - return Err(bad(C, format!("“{shown}” opens {} files, not `{}`", exts.join(", "), file_name(name)))); - } + check_extension(C, plugin.manifest(), name)?; return Ok(Some(plugin)); } if detect(name, bytes).is_some() { return Ok(None); } - Ok(import::for_extension(&ext).into_iter().next()) + Ok(import::for_extension(&extension(name)).into_iter().next()) +} + +/// The importer `file.place`'s params `p` name (`importer`) for the file `name`, which must set +/// `place` in its manifest and list the file's extension (errors of command `cmd`); `None` when `p` +/// names none. +pub(crate) fn named_for_place(name: &str, p: &Value, cmd: &str) -> Result>> { + let Some(id) = named(p, cmd)? else { return Ok(None) }; + let plugin = import::named(id).map_err(|e| bad(cmd, e.to_string()))?; + let m = plugin.manifest(); + if !m.place { + return Err(match import::not_placing(m) { + vectorcraft_plugins::Error::Params(why) => bad(cmd, why), + e => bad(cmd, e.to_string()), + }); + } + check_extension(cmd, m, name)?; + Ok(Some(plugin)) +} + +/// The importer File › Place uses for the file `name` when no built-in format reads it: the first +/// installed importer, by plug-in id, whose manifest sets `place` and that lists its extension. +pub(crate) fn for_place(name: &str) -> Option> { + import::placing(&extension(name)).into_iter().next() +} + +/// Whether an importer may read a file of extension `ext` for `mode` when none is named: no +/// built-in format reads the extension (for Place, as text, RTF or Word either) and an importer +/// that reads for `mode` lists it. +fn importer_reads(ext: &str, mode: Mode) -> bool { + super::readable_format(ext).is_none() + && match mode { + Mode::Import => !import::for_extension(ext).is_empty(), + Mode::Place => !super::PLACE_EXTS.contains(&ext) && !import::placing(ext).is_empty(), + } +} + +/// The error of the file `name`, past [`import::MAX_INPUT_BYTES`], which an importer would read +/// for `mode`. +fn too_large(name: &str, mode: Mode) -> EngineError { + match mode { + Mode::Import => err(format!("can't open `{}`: {}", file_name(name), import::too_large())), + Mode::Place => failed(Mode::Place, name, import::too_large()), + } +} + +/// The error of the file `name`, which importer `e` couldn't read for `mode`. +fn failed(mode: Mode, name: &str, e: impl std::fmt::Display) -> EngineError { + match mode { + Mode::Import => err(format!("can't open `{}`: {e}", file_name(name))), + Mode::Place => err(format!("can't place `{}`: {e}", file_name(name))), + } } /// How much of a file [`detect`] is given: more than its content checks read. @@ -61,14 +121,17 @@ const SNIFF_BYTES: usize = 64 << 10; /// Refuses `document.open`'s `dataBase64` in `p` before it is decoded when it holds a file past /// [`import::MAX_INPUT_BYTES`] that only an importer reads, by the rule of `read_path`. pub(super) fn check_data(p: &Value) -> Result<()> { + check_data_for(p, Mode::Import, C) +} + +/// [`check_data`] for `mode` and command `cmd`: `file.place`'s params with [`Mode::Place`]. +fn check_data_for(p: &Value, mode: Mode, cmd: &str) -> Result<()> { let Some(b64) = str_param(p, "dataBase64") else { return Ok(()); }; let name = str_param(p, "name").unwrap_or("Untitled"); - let ext = extension(name); - let explicit = named(p)?.is_some(); - let built_in = !explicit && (super::readable_format(&ext).is_some() || import::for_extension(&ext).is_empty()); - if built_in || vectorcraft_format::base64_decoded_len(b64) <= import::MAX_INPUT_BYTES as u64 { + let explicit = named(p, cmd)?.is_some(); + if (!explicit && !importer_reads(&extension(name), mode)) || vectorcraft_format::base64_decoded_len(b64) <= import::MAX_INPUT_BYTES as u64 { return Ok(()); } if !explicit { @@ -78,7 +141,7 @@ pub(super) fn check_data(p: &Value) -> Result<()> { return Ok(()); } } - Err(err(format!("can't open `{}`: {}", file_name(name), import::too_large()))) + Err(too_large(name, mode)) } /// The file at `path` for `document.open`'s params `p`. A file that only an importer reads (one @@ -86,11 +149,15 @@ pub(super) fn check_data(p: &Value) -> Result<()> { /// to [`import::MAX_INPUT_BYTES`]: past that, it is an error, unless the start of the file shows a /// built-in format and no importer was named, which is read whole as any other file is. A file past /// the limit that isn't read whole is reported from its size, without reading it. -#[cfg(not(target_arch = "wasm32"))] pub(super) fn read_path(path: &str, p: &Value) -> Result> { - let ext = extension(path); - let explicit = named(p)?.is_some(); - if !explicit && (super::readable_format(&ext).is_some() || import::for_extension(&ext).is_empty()) { + read_path_for(path, p, Mode::Import, C) +} + +/// [`read_path`] for `mode` and command `cmd`: `file.place`'s params with [`Mode::Place`]. +#[cfg(not(target_arch = "wasm32"))] +fn read_path_for(path: &str, p: &Value, mode: Mode, cmd: &str) -> Result> { + let explicit = named(p, cmd)?.is_some(); + if !explicit && !importer_reads(&extension(path), mode) { return super::read_file(path); } let head = super::read_file_head(path, SNIFF_BYTES)?; @@ -100,57 +167,83 @@ pub(super) fn read_path(path: &str, p: &Value) -> Result> { if !explicit && detect(path, &head).is_some() { return super::read_file(path); } - let too_large = || err(format!("can't open `{}`: {}", file_name(path), import::too_large())); let size = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.len(); if size > import::MAX_INPUT_BYTES as u64 { - return Err(too_large()); + return Err(too_large(path, mode)); } // The file can grow after the size is read. let file = super::read_file_head(path, import::MAX_INPUT_BYTES + 1)?; if file.len() > import::MAX_INPUT_BYTES { - return Err(too_large()); + return Err(too_large(path, mode)); } Ok(file) } #[cfg(target_arch = "wasm32")] -pub(super) fn read_path(path: &str, _: &Value) -> Result> { +fn read_path_for(path: &str, _: &Value, _: Mode, _: &str) -> Result> { super::read_file(path) } +/// The file `file.place`'s params `p` name, as [`super::source`] reads it for command `cmd`, except +/// that a file an importer would place (one `importer` names, or an extension no built-in format +/// reads that an importer which places its files lists) is read, or decoded, only when it is at +/// most [`import::MAX_INPUT_BYTES`] long. +pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result> { + match str_param(p, "path") { + Some(path) => Ok(Source { name: path, bytes: read_path_for(path, p, Mode::Place, cmd)?, path: Some(path) }), + None => { + check_data_for(p, Mode::Place, cmd)?; + super::source(p, cmd) + } + } +} + +/// The file `name` holding `bytes` read by importer `plugin` for `mode` with command `cmd`'s params +/// `p` (`params`: the importer's own parameters) → the importer's format, a new document holding its +/// objects on its first layer, their ids, and its warnings. +fn read( + name: &str, + bytes: &[u8], + plugin: &Plugin, + p: &Value, + cmd: &str, + mode: Mode, +) -> Result<(&'static Format, Document, Vec, Vec)> { + let m = plugin.manifest(); + let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?; + let (ext, stem) = (extension(name), file_stem(name)); + let source = import::Source { extension: &ext, name: &stem }; + let params = p.get("params").cloned().unwrap_or(Value::Null); + let imported = import::run_as(plugin, bytes, ¶ms, source, mode).map_err(|e| match e { + vectorcraft_plugins::Error::Cancelled => EngineError::Cancelled, + vectorcraft_plugins::Error::Params(why) => bad(cmd, why), + e => failed(mode, name, e), + })?; + let mut doc = Document::new(1.0, 1.0); + let layer = doc.layers.first().map(|l| l.id); + let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(cmd, fx, n); + let ids = objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| failed(mode, name, e))?; + Ok((format, doc, ids, imported.warnings)) +} + +/// The file `name` holding `bytes` read by importer `plugin` to place it, with `file.place`'s params +/// `p` (errors of command `cmd`) → the importer's format, the document holding its objects on its +/// first layer, and its warnings. Importer `plugin`'s manifest must set `place`. +pub(crate) fn read_for_place(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value, cmd: &str) -> Result<(&'static Format, Document, Vec)> { + let (format, doc, _, warnings) = read(name, bytes, plugin, p, cmd, Mode::Place)?; + Ok((format, doc, warnings)) +} + /// The file `name` holding `bytes` read by importer `plugin` with `document.open`'s params `p` /// (`params`: the importer's own parameters) into a new document, its artboard the bounds of what /// the importer returned. pub(super) fn load(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value) -> Result { - let m = plugin.manifest(); - let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?; - let (ext, stem) = (extension(name), file_stem(name)); - let source = import::Source { extension: &ext, name: &stem }; - let params = p.get("params").cloned().unwrap_or(Value::Null); - let imported = import::run(plugin, bytes, ¶ms, source).map_err(|e| match e { - vectorcraft_plugins::Error::Cancelled => EngineError::Cancelled, - vectorcraft_plugins::Error::Params(why) => bad(C, why), - e => err(format!("can't open `{}`: {e}", file_name(name))), - })?; - let mut doc = Document::new(1.0, 1.0); - let layer = doc.layers.first().map(|l| l.id); - let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(C, fx, n); - let ids = - objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?; + let (format, mut doc, ids, warnings) = read(name, bytes, plugin, p, C, Mode::Import)?; if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) { board.rect = artboard_rect(bounds); } doc.title = file_name(name); - Ok(Loaded { - doc, - format, - warnings: imported.warnings, - restored: false, - converted: false, - preview_only: false, - editing_data: false, - native_pdf_compatible: None, - }) + Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None }) } /// The artboard of art with bounds `r`: `r` within ±[`MAX_COORD`], at least 1 pt wide and high diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index fef99cc9c3..d4146b741c 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -32,6 +32,9 @@ //! - A VectorCraft document placed from a file with Link (the default) becomes a placed document: //! one locked object showing the artboard `page`, linked to the file and read again when it //! changes ([`document`]); without Link, an editable copy of its art. +//! - A file an importer plug-in whose manifest sets `place` reads (the one `importer` names, else +//! the first by id that lists the extension of a file no built-in format reads) becomes one group +//! of the objects it returned, embedded ([`fileio::importer`]). //! //! The art lands centred on `at`, fitted into `rect`, or (Replace) where the replaced object was, //! with its transform; Template puts it on a new template layer. The images, symbols, patterns and @@ -82,7 +85,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its objects, guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -190,10 +193,14 @@ fn load_sliced(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Res /// The file `p` names, read into placeable art; a DXF drawing's Fit to Artboard fills `board` /// (unless the params name their own box). A PDF/.ai page or an EPS file read from a path is placed /// linked with Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB -/// file's slices go to `slices`. +/// file's slices go to `slices`. A file an importer plug-in places (the one `importer` names, or one +/// no built-in format reads) is read by it ([`plugin_art`]). fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_out: &mut Slices) -> Result { - let src = fileio::source(p, cmd)?; + let src = fileio::importer::place_source(p, cmd)?; let name = fileio::file_name(src.name); + if let Some(plugin) = fileio::importer::named_for_place(src.name, p, cmd)? { + return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd); + } // An Affinity file is recognised by its signature, whatever its name says. if fileio::TEXT_EXTS.contains(&fileio::extension(src.name).as_str()) && !vectorcraft_affinity::is_affinity(&src.bytes) { let text = text::import(&src.bytes, text::TextOptions::parse(p, cmd)?, cmd)?; @@ -228,8 +235,12 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o } return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None }); } - let format = fileio::detect(src.name, &src.bytes) - .ok_or_else(|| bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)")))?; + let Some(format) = fileio::detect(src.name, &src.bytes) else { + return match fileio::importer::for_place(src.name) { + Some(plugin) => plugin_art(name, src.name, &src.bytes, &plugin, p, cmd), + None => Err(bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)"))), + }; + }; let page = match p.get("page") { None => 1, Some(v) => v.as_u64().filter(|n| (1..=100_000).contains(n)).ok_or_else(|| bad(cmd, "page must be a whole number from 1"))? as usize, @@ -385,6 +396,20 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip }, natural, warnings, link: None, board }) } +/// The file `src` (named `name`) holding `bytes`, read by importer plug-in `plugin` with `p`'s +/// `params`, as art to place: its objects in paint order, guides left out, in a group whose natural +/// box is the bounds of what they draw. It is embedded: an importer reads the file once, so there is +/// nothing to link to. +fn plugin_art(name: String, src: &str, bytes: &[u8], plugin: &vectorcraft_plugins::Plugin, p: &Value, cmd: &str) -> Result { + let (format, mut doc, warnings) = fileio::importer::read_for_place(src, bytes, plugin, p, cmd)?; + let layers = std::mem::take(&mut doc.layers); + let nodes = art_of(layer_art(&layers)); + let natural = shown_bounds(&doc.symbol_boxes(), &nodes) + .filter(|r| r.width() > 0.0 || r.height() > 0.0) + .ok_or_else(|| bad(cmd, format!("`{name}` has no art to place")))?; + Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip: None }, natural, warnings, link: None, board: None }) +} + /// A PSD or PSB file's layers, read as `document.open` reads them into `doc`, as art to place: an /// image for each layer and a group for each layer group, bottom first, with the layer's name, /// visibility, opacity, blend mode and opacity mask. The art's natural box is the file's canvas, @@ -992,7 +1017,7 @@ fn read_queue(doc: u64, p: Value, queued: Vec) -> Result { let thumbnail = p.get("thumbnail").and_then(Value::as_f64); let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]); for mut q in queued { - for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices"] { + for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices", "importer", "params"] { if let Some(v) = p.get(k) { q[k] = v.clone(); } diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..94a0a95c4a 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -92,6 +92,9 @@ pub fn describe(p: &Plugin) -> Value { Kind::Exporter | Kind::Importer => { v["format"] = json!(export::format_id(&m.id)); v["extensions"] = json!(m.extensions); + if m.place { + v["place"] = json!(true); + } } Kind::Filter => {} } @@ -1270,7 +1273,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), diff --git a/crates/engine/tests/plugin_place.rs b/crates/engine/tests/plugin_place.rs new file mode 100644 index 0000000000..7908dc86a7 --- /dev/null +++ b/crates/engine/tests/plugin_place.rs @@ -0,0 +1,282 @@ +//! Importer plug-ins whose manifests set `place` (docs/plugins.md › Importers) through `file.place`: +//! which files they are given, the group their objects become in the open document, and what happens +//! when they fail, decline or are canceled. +//! +//! A test binary of its own: installed plug-ins are process-wide, and the unit tests that check the +//! exact list of formats would see these ones. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::cmd::fileio; +use vectorcraft_engine::{EngineError, Session}; +use vectorcraft_plugins::wat::{self as tpl, Given}; + +/// An importer's output: a red rectangle "A" from (10, 20) to (110, 70) under a line "B" from +/// (10, 20) to (60, 20), and a warning. +const ART: &str = r#"{"objects":[{"type":"path","name":"A","path":{"subpaths":[{"closed":true,"anchors":[{"p":[10,20]},{"p":[110,20]},{"p":[110,70]},{"p":[10,70]}]}]},"fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]},{"type":"path","name":"B","path":{"subpaths":[{"closed":false,"anchors":[{"p":[10,20]},{"p":[60,20]}]}]}}],"warnings":["1 layer merged"]}"#; + +/// An importer's output: the rectangle "A" of [`ART`] and a guide "G" from (500, 500) to (900, 500). +const GUIDED: &str = r#"{"objects":[{"type":"path","name":"A","path":{"subpaths":[{"closed":true,"anchors":[{"p":[10,20]},{"p":[110,20]},{"p":[110,70]},{"p":[10,70]}]}]},"fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]},{"type":"path","name":"G","guide":true,"path":{"subpaths":[{"closed":false,"anchors":[{"p":[500,500]},{"p":[900,500]}]}]}}]}"#; + +/// The `vc_run` body of an importer that never returns. +const SPINS: &str = "(loop $l (br $l)) (i64.const 0)"; + +/// The manifest of an importer `id` reading `extensions` (a JSON list) that places its files. +fn placing(id: &str, extensions: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"importer","extensions":{extensions},"place":true}}"#) +} + +/// Installs the plug-in written in WAT `src` → its `plugin.list` entry. +fn install(s: &mut Session, src: &str) -> Value { + let wasm = wat::parse_str(src).unwrap_or_else(|e| panic!("bad test WAT: {e}")); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap() +} + +/// `file.place` of a file `name` holding `bytes`, with more params `extra`. +fn place(s: &mut Session, name: &str, bytes: &[u8], extra: Value) -> Result { + let mut p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + s.execute("file.place", &p) +} + +/// A session with a new document holding one rectangle, selected. +fn with_document() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 400.0, "y": 400.0, "width": 20.0, "height": 10.0})).unwrap(); + s +} + +/// The active document's undo and redo steps, layers and content. +fn state(s: &mut Session) -> (usize, usize, usize, Value) { + let content = s.execute("document.inspect", &json!({})).unwrap(); + let d = s.doc().unwrap(); + (d.history.undo.len(), d.history.redo.len(), d.doc.layers.len(), content) +} + +/// A placed group: its name, the names of its children, and its bounds as `(x0, y0, x1, y1)`. +type Placed = (Option, Vec>, (f64, f64, f64, f64)); + +/// The group `id` of the active document. +fn object(s: &Session, id: u64) -> Placed { + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).expect("placed"); + let kids = match &n.kind { + NodeKind::Group { children, clip: false } => children.iter().map(|c| c.name.clone()).collect(), + other => panic!("not a group: {other:?}"), + }; + let b = n.geometric_bounds_with(&d.symbol_boxes()).unwrap(); + (n.name.clone(), kids, (b.x0, b.y0, b.x1, b.y1)) +} + +/// A file only a placing importer reads is placed as one group named after the file, its objects in +/// the order the importer returned them and centered on `at`, embedded (also with `link: true`), as +/// one undo step that undo takes back whole. +#[test] +fn a_placing_importer_places_one_group_as_one_undo_step() { + let mut s = with_document(); + let entry = install(&mut s, &tpl::returning(&placing("test.place.one", r#"["tpo"]"#), ART)); + assert_eq!((&entry["place"], &entry["permissions"]), (&json!(true), &json!(["import.read"]))); + let formats = s.execute("document.formats", &json!({})).unwrap(); + let listed = formats["formats"].as_array().unwrap().iter().find(|f| f["id"] == "plugin.test.place.one").expect("listed"); + assert_eq!(listed["place"], json!(true)); + + let before = state(&mut s); + let r = place(&mut s, "Shapes.tpo", b"?", json!({"at": [300, 400], "link": true})).unwrap(); + assert_eq!( + (&r["format"], &r["linked"], &r["warnings"], &r["name"]), + (&json!("plugin.test.place.one"), &json!(false), &json!(["1 layer merged"]), &json!("Shapes.tpo")) + ); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let id = ids[0].as_u64().unwrap(); + let (name, kids, bounds) = object(&s, id); + assert_eq!((name.as_deref(), kids), (Some("Shapes.tpo"), vec![Some("A".to_string()), Some("B".to_string())])); + assert_eq!(bounds, (250.0, 375.0, 350.0, 425.0)); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(id)]); + let after = state(&mut s); + assert_eq!(after.0, before.0 + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + let undone = state(&mut s); + assert_eq!((undone.0, undone.1, undone.2), (before.0, 1, before.2)); + assert_eq!((&undone.3["layers"], &undone.3["history"]), (&before.3["layers"], &before.3["history"])); +} + +/// `rect` fits the group in with its aspect, Template puts it on a new template layer, Replace swaps +/// the selected object at its center and stacking place, and `file.place.info` and the place cursor +/// read the file the same way. +#[test] +fn placing_follows_rect_template_and_replace() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.ways", r#"["tpw"]"#), ART)); + let r = place(&mut s, "a.tpw", b"?", json!({"rect": [0, 0, 50, 50]})).unwrap(); + assert_eq!(object(&s, r["ids"][0].as_u64().unwrap()).2, (0.0, 12.5, 50.0, 37.5)); + + let layers = s.doc().unwrap().doc.layers.len(); + let r = place(&mut s, "b.tpw", b"?", json!({"template": true})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.len(), layers + 1); + let layer = d.layer_of(NodeId(r["ids"][0].as_u64().unwrap())).and_then(|l| d.node(l)).unwrap(); + assert!(matches!(layer.kind, NodeKind::Layer { template: true, .. }) && layer.locked); + + let rect = s.execute("shape.rectangle", &json!({"x": 400.0, "y": 100.0, "width": 20.0, "height": 10.0})).unwrap(); + let old = NodeId(rect["id"].as_u64().unwrap()); + let (parent, index, _) = s.doc().unwrap().doc.position(old).unwrap(); + let r = place(&mut s, "c.tpw", b"?", json!({"replace": true})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + assert!(d.node(old).is_none()); + assert_eq!(d.position(id).map(|(p, i, _)| (p, i)), Some((parent, index))); + assert_eq!(object(&s, id.0).2, (360.0, 80.0, 460.0, 130.0)); + + let info = s.execute("file.place.info", &json!({"name": "d.tpw", "dataBase64": vectorcraft_format::base64_encode(b"?")})).unwrap(); + assert_eq!((&info["format"], &info["width"], &info["height"]), (&json!("plugin.test.place.ways"), &json!(100.0), &json!(50.0))); + let q = s.execute("file.place.queue", &json!({"files": [{"name": "e.tpw", "dataBase64": vectorcraft_format::base64_encode(b"?")}]})).unwrap(); + assert_eq!((&q["count"], &q["files"][0]["format"], &q["skipped"]), (&json!(1), &json!("plugin.test.place.ways"), &json!([]))); +} + +/// Guides the importer returns are left out of the placed group, and its box is that of the art +/// left, so a guide beside the art doesn't move it; output of guides alone places nothing. +#[test] +fn guides_are_left_out_of_what_is_placed() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.guided", r#"["tpg"]"#), GUIDED)); + let r = place(&mut s, "a.tpg", b"?", json!({"at": [300, 400]})).unwrap(); + let (_, kids, bounds) = object(&s, r["ids"][0].as_u64().unwrap()); + assert_eq!((kids, bounds), (vec![Some("A".to_string())], (250.0, 375.0, 350.0, 425.0))); + let info = s.execute("file.place.info", &json!({"name": "b.tpg", "dataBase64": vectorcraft_format::base64_encode(b"?")})).unwrap(); + assert_eq!((&info["width"], &info["height"]), (&json!(100.0), &json!(50.0))); + + let guides = r#"{"objects":[{"type":"path","guide":true,"path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,0]},{"p":[100,0]}]}]}}]}"#; + install(&mut s, &tpl::returning(&placing("test.place.guides", r#"["tpq"]"#), guides)); + let before = state(&mut s); + let e = place(&mut s, "c.tpq", b"?", json!({})).unwrap_err().to_string(); + assert!(e.contains("`c.tpq` has no art to place"), "{e}"); + assert_eq!(state(&mut s), before); +} + +/// The importer is told it places the file (`_context.mode`), with the file's extension and name, +/// and is given its parameters. +#[test] +fn the_importer_is_told_it_places() { + let mut s = with_document(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + let manifest = placing("test.place.mode", r#"["tpm"]"#).replace(r#""place":true"#, &format!(r#""place":true,"params":{params}"#)); + for (i, needle) in [r#""mode":"place""#, r#""extension":"tpm""#, r#""name":"Shapes""#, r#""density":10.0"#].into_iter().enumerate() { + // ART when the parameters hold the needle; the file, which isn't JSON, otherwise. + let wasm = wat::parse_str(tpl::when_given(&manifest, Given::Params, needle, ART)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "replace": i > 0})).unwrap(); + let r = place(&mut s, "Shapes.tpm", b"not json", json!({"params": {"density": 12}})); + assert_eq!(r.map(|r| r["format"].clone()).map_err(|e| e.to_string()), Ok(json!("plugin.test.place.mode")), "{needle}"); + } + let before = state(&mut s); + let e = place(&mut s, "Shapes.tpm", b"", json!({"params": {"density": "lots"}})).unwrap_err(); + assert!(matches!(e, EngineError::BadParams { .. }), "{e}"); + assert_eq!(state(&mut s), before); +} + +/// Built-in formats keep their files: an importer that lists `svg` places an `.svg` only when +/// `importer` names it. An importer whose manifest doesn't set `place` opens its files and places +/// none: File › Place doesn't read them, and naming it is an error, as is naming it for a file of an +/// extension it doesn't list. +#[test] +fn built_in_formats_and_open_only_importers_keep_their_files() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.svg", r#"["tps","svg"]"#), ART)); + install(&mut s, &tpl::returning(&tpl::importer("test.place.openonly", r#"["tpx"]"#, "{}"), ART)); + let svg = br#""#; + assert_eq!(place(&mut s, "a.svg", svg, json!({})).unwrap()["format"], "svg"); + assert_eq!(place(&mut s, "b.svg", svg, json!({"importer": "plugin.test.place.svg"})).unwrap()["format"], "plugin.test.place.svg"); + assert_eq!(place(&mut s, "c.tps", svg, json!({})).unwrap()["format"], "svg", "an SVG named as the importer's file"); + + let before = state(&mut s); + let e = place(&mut s, "d.tpx", b"?", json!({})).unwrap_err().to_string(); + assert!(e.contains("not a format VectorCraft reads"), "{e}"); + let e = place(&mut s, "d.tpx", b"?", json!({"importer": "plugin.test.place.openonly"})).unwrap_err().to_string(); + assert!(e.contains("doesn't place them") && e.contains("Test test.place.openonly"), "{e}"); + let e = place(&mut s, "d.tpx", b"?", json!({"importer": "plugin.test.place.svg"})).unwrap_err().to_string(); + assert!(e.contains(".tps, .svg") && e.contains("d.tpx"), "{e}"); + let e = place(&mut s, "d.tps", b"?", json!({"importer": 3})).unwrap_err().to_string(); + assert!(e.contains("`importer` must be"), "{e}"); + assert_eq!(state(&mut s), before); + // The open-only importer still opens its files. + let r = s.execute("document.open", &json!({"name": "d.tpx", "dataBase64": vectorcraft_format::base64_encode(b"?")})).unwrap(); + assert_eq!(r["format"], "plugin.test.place.openonly"); +} + +/// File › Place's dialog lists a placing importer's extensions, under its name and in "All placeable +/// files", and not an open-only importer's; relinking an image keeps the built-in filters. A file only +/// a placing importer reads is dropped onto the canvas to be placed rather than opened. +#[test] +fn the_place_dialog_lists_placing_importers() { + let mut s = Session::new(); + install(&mut s, &tpl::returning(&placing("test.place.list", r#"["tpl","svg"]"#), ART)); + install(&mut s, &tpl::returning(&tpl::importer("test.place.listopen", r#"["tpy"]"#, "{}"), ART)); + let filters: Vec<_> = fileio::place_dialog_filters().collect(); + assert!(filters.contains(&("Test test.place.list", &["tpl"][..])), "{filters:?}"); + let all = filters.first().unwrap(); + assert_eq!(all.0, "All placeable files"); + assert!(all.1.contains(&"tpl") && !all.1.contains(&"tpy"), "{all:?}"); + assert_eq!(all.1.iter().filter(|e| **e == "svg").count(), 1); + assert!(!filters.iter().any(|(_, exts)| exts.contains(&"tpy"))); + assert!(!fileio::place_filters().any(|(_, exts)| exts.contains(&"tpl"))); + assert!(fileio::places_with_importer("x.TPL") && !fileio::opens_with_importer("x.tpl")); + assert!(!fileio::places_with_importer("x.tpy") && fileio::opens_with_importer("x.tpy")); + assert!(!fileio::places_with_importer("x.svg")); +} + +/// Nothing is placed, and the document keeps its content and undo steps, when the importer declines, +/// returns output that doesn't pass the checks, traps or is canceled, or when the file is larger +/// than an importer reads: that file is refused from its size, before it is read. +#[test] +fn failures_place_nothing() { + let mut s = with_document(); + let far = r#"{"objects":[{"type":"path","path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,0]},{"p":[9000000,0]}]}]}}]}"#; + let cases = [ + ("test.place.fail.declines", r#"{"error":"Not a drawing."}"#, "Not a drawing."), + ("test.place.fail.notjson", "not json", "JSON"), + ("test.place.fail.empty", r#"{"objects":[]}"#, "the importer returned no objects"), + ("test.place.fail.key", r#"{"objects":[],"layers":[]}"#, "not `layers`"), + ("test.place.fail.far", far, "4000000"), + ( + "test.place.fail.point", + r#"{"objects":[{"type":"path","path":{"subpaths":[{"closed":false,"anchors":[{"p":[5,5]}]}]}}]}"#, + "no art to place", + ), + ]; + for (id, output, _) in cases { + install(&mut s, &tpl::returning(&placing(id, r#"["tpf"]"#), output)); + } + install(&mut s, &tpl::module(&placing("test.place.fail.traps", r#"["tpf"]"#), "(unreachable)", "", 1)); + install(&mut s, &tpl::module(&placing("test.place.fail.spins", r#"["tpf"]"#), SPINS, "", 1)); + let before = state(&mut s); + for (id, _, why) in cases { + let e = place(&mut s, "x.tpf", b"?", json!({"importer": format!("plugin.{id}")})).unwrap_err().to_string(); + assert!(e.contains(why) && e.contains("x.tpf"), "{id}: {e}"); + assert_eq!(state(&mut s), before, "{id}"); + } + assert!(place(&mut s, "x.tpf", b"?", json!({"importer": "plugin.test.place.fail.traps"})).is_err()); + assert_eq!(state(&mut s), before, "trapped"); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || place(&mut s, "x.tpf", b"?", json!({"importer": "plugin.test.place.fail.spins"}))); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!(state(&mut s), before, "canceled"); + + // A file one byte past the limit, without data in it: the size alone refuses it. + let dir = std::env::temp_dir().join(format!("vc-plugin-place-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let big = dir.join("big.tpf"); + std::fs::File::create(&big).unwrap().set_len(vectorcraft_plugins::import::MAX_INPUT_BYTES as u64 + 1).unwrap(); + let e = s.execute("file.place", &json!({"path": big.to_string_lossy(), "importer": "plugin.test.place.fail.declines"})).unwrap_err().to_string(); + assert!(e.contains("can't place `big.tpf`") && e.contains("larger than"), "{e}"); + let e = s.execute("file.place", &json!({"path": big.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("larger than"), "by its extension: {e}"); + assert_eq!(state(&mut s), before, "too large"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/plugins/src/import.rs b/crates/plugins/src/import.rs index 599470e0aa..453ed75f41 100644 --- a/crates/plugins/src/import.rs +++ b/crates/plugins/src/import.rs @@ -7,6 +7,10 @@ //! sorts first opens it ([`for_extension`]). File › Open With and `document.open {importer}` pick an //! importer by its format id (`plugin.`), also for an extension a built-in format reads. //! +//! An importer whose manifest sets `place` also reads its files for File › Place (`file.place`), +//! by the same rules among the importers that set it ([`placing`]): its objects become one group in +//! the open document, and it is told so in `_context.mode` ([`Mode::Place`]). +//! //! The host hands the importer the file's bytes as they are, at most [`MAX_INPUT_BYTES`] of them, //! and reads back the objects of the new document in the same form filters return them //! ([`crate::objects`]): `{"objects": [...], "warnings"?: ["…"]}`, or `{"error": "…"}` to decline. @@ -61,6 +65,38 @@ pub fn for_extension(ext: &str) -> Vec> { installed().into_iter().filter(|p| p.manifest().extensions.contains(&ext)).collect() } +/// The installed importers whose manifests set `place` and that list extension `ext` (any case, +/// leading dot allowed), by plug-in id: the first is the one File › Place uses. +pub fn placing(ext: &str) -> Vec> { + for_extension(ext).into_iter().filter(|p| p.manifest().place).collect() +} + +/// The error of importer `m`, whose manifest doesn't set `place`, asked to place a file. +pub fn not_placing(m: &crate::Manifest) -> Error { + let shown = crate::permissions::display_text(&m.name, crate::permissions::MAX_SHOWN_NAME); + Error::Params(format!("“{shown}” opens files but doesn't place them: its manifest doesn't set `place`")) +} + +/// What an import is for, which the importer is told as `_context.mode`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// File › Open: the objects become a new document (`"import"`). + Import, + /// File › Place: the objects become one group in the open document (`"place"`). Only an + /// importer whose manifest sets `place` runs for it. + Place, +} + +impl Mode { + /// Its name in `_context.mode`. + pub fn name(self) -> &'static str { + match self { + Mode::Import => "import", + Mode::Place => "place", + } + } +} + /// What an importer returned. #[derive(Clone, Debug, PartialEq)] pub struct Imported { @@ -93,15 +129,24 @@ pub fn limits(plugin: &Plugin) -> Limits { /// Runs importer `plugin` on `file`, the bytes of the file being opened, with `params` (checked /// against its manifest: missing ones take their defaults) for the file `source`. pub fn run(plugin: &Plugin, file: &[u8], params: &Value, source: Source) -> Result { + run_as(plugin, file, params, source, Mode::Import) +} + +/// [`run`] for `mode`. [`Mode::Place`] is refused for an importer whose manifest doesn't set `place` +/// ([`not_placing`]), before it runs. +pub fn run_as(plugin: &Plugin, file: &[u8], params: &Value, source: Source, mode: Mode) -> Result { let m = plugin.manifest(); if m.kind != Kind::Importer { return Err(not_importer(m)); } + if mode == Mode::Place && !m.place { + return Err(not_placing(m)); + } if file.len() > MAX_INPUT_BYTES { return Err(too_large()); } let mut params = Value::Object(m.resolve_params(params)?); - params["_context"] = json!({"mode": "import", "extension": source.extension, "name": source.name}); + params["_context"] = json!({"mode": mode.name(), "extension": source.extension, "name": source.name}); let params = serde_json::to_vec(¶ms).map_err(|e| Error::Params(e.to_string()))?; decode(&plugin.run_limited(file, ¶ms, &limits(plugin))?) } diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..8c8888a478 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -333,6 +333,11 @@ pub struct Manifest { /// the one an exporter's files get. Only exporters and importers declare them. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub extensions: Vec, + /// An importer whose files File › Place also reads (`file.place`), into the open document as one + /// group ([`crate::import::Mode::Place`]): `true` when the manifest has `"place": true`. Only an + /// importer sets it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub place: bool, /// How much a run may compute: only a filter may be [`Budget::Heavy`]. #[serde(default, skip_serializing_if = "Budget::is_light")] pub budget: Budget, @@ -379,6 +384,7 @@ impl Manifest { inputs: Vec::new(), params: Vec::new(), extensions: Vec::new(), + place: false, budget: Budget::Light, paint_output: false, commands: Vec::new(), @@ -426,6 +432,9 @@ impl Manifest { return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into())); } self.validate_extensions()?; + if self.place && self.kind != Kind::Importer { + return Err(Error::Manifest("`place` is only for an importer (`kind` \"importer\")".into())); + } match (self.budget, self.kind) { (Budget::Light, _) | (Budget::Heavy, Kind::Filter) => {} (Budget::Heavy, Kind::Effect) => { @@ -1050,6 +1059,33 @@ mod tests { } } + /// Only an importer sets `place`, to a boolean, and it asks for no permission beyond + /// `import.read`; false, the default, isn't written back. + #[test] + fn only_an_importer_places_its_files() { + let m = Manifest::parse(br#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":true}"#).unwrap(); + assert!(m.place); + assert_eq!(m.permissions(), [Permission::ImportRead]); + assert_eq!(serde_json::to_value(&m).unwrap()["place"], json!(true)); + for open_only in [ + r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"]}"#, + r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":false}"#, + ] { + let m = Manifest::parse(open_only.as_bytes()).unwrap(); + assert!(!m.place && serde_json::to_value(&m).unwrap().get("place").is_none(), "{open_only}"); + } + for (bad, says) in [ + (r#"{"id":"a","name":"x","kind":"filter","place":true}"#, "`place` is only for an importer"), + (r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"place":true}"#, "`place` is only for an importer"), + (r#"{"id":"a","name":"x","kind":"effect","place":true}"#, "`place` is only for an importer"), + (r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":"yes"}"#, "invalid type"), + (r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":1}"#, "invalid type"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + /// A filter may ask for a heavy budget; a live effect runs while the document is drawn and an /// exporter has an export's budget, so they can't. Light, the default, isn't written back. #[test] diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4561f3dc73..f5d07b0397 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -716,6 +716,7 @@ impl PluginIntField { inputs: Vec::new(), params: vec![("seed".into(), vectorcraft_plugins::ParamSpec::Int { min, max, default: 0 }.into())], extensions: Vec::new(), + place: false, budget: Default::default(), paint_output: false, commands: Vec::new(), diff --git a/crates/ui-egui/src/dialogs/tests_plugin_import.rs b/crates/ui-egui/src/dialogs/tests_plugin_import.rs index 7dd035c1e1..118e0f62cf 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_import.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_import.rs @@ -225,6 +225,54 @@ fn a_dropped_file_only_an_importer_reads_opens() { app.run("plugin.remove", json!({"id": "test.ui.dropshare"})).unwrap(); } +/// A file only an importer that places its files reads, dropped on the canvas, is placed there as +/// one group by that importer, as one undo step; dropped where the platform gives no position, it +/// opens as its own document, as a vector file does. +#[test] +fn a_dropped_file_a_placing_importer_reads_is_placed_on_the_canvas() { + use crate::place::{DropTarget, drop_files}; + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(800.0, 600.0))); + let on_canvas = Some(egui::pos2(400.0, 300.0)); + let manifest = tpl::importer("test.ui.dropplace", r#"["tdp"]"#, "{}").replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + assert!(manifest.contains(r#""place":true"#), "{manifest}"); + install(&mut app, &tpl::returning(&manifest, RECT)); + + let target = app.drop_target("Drawing.tdp", on_canvas, false); + assert!(matches!(target, DropTarget::Place(_)), "{target:?}"); + assert_eq!(app.drop_target("Drawing.tdp", None, false), DropTarget::Open); + let steps = app.session.active().unwrap().history.undo.len(); + drop_files(&mut app, vec![(target, ("Drawing.tdp".into(), None, b"?".to_vec()))]); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1, "one undo step"); + let [id] = st.selection.objects[..] else { panic!("one placed object: {:?}", st.selection.objects) }; + let n = st.doc.node(id).unwrap(); + assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }) && n.name.as_deref() == Some("Drawing.tdp"), "{n:?}"); + + app.run("plugin.remove", json!({"id": "test.ui.dropplace"})).unwrap(); +} + +/// A text file or DXF drawing placed with the importer `importer` names goes to that importer, +/// without the text or DXF import options File › Place asks for those formats. +#[test] +fn a_named_placing_importer_skips_built_in_import_options() { + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let manifest = tpl::importer("test.ui.namedplace", r#"["txt","dxf"]"#, "{}").replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::returning(&manifest, RECT)); + for name in ["Notes.txt", "Plan.dxf"] { + let steps = app.session.active().unwrap().history.undo.len(); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(b"0\nSECTION\n"), "importer": "plugin.test.ui.namedplace"}); + let r = app.run("file.place", p).unwrap(); + assert!(app.ui.dialog.is_none(), "{name}: no import options dialog"); + assert_eq!(r["format"], "plugin.test.ui.namedplace", "{name}: {r}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "{name}"); + } + app.run("plugin.remove", json!({"id": "test.ui.namedplace"})).unwrap(); +} + /// The extensions File › Open's filters leave out of importers' (`fileio::opens_as_other`) are the /// ones File › Open installs, imports, checks or loads as something other than a document. #[test] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..d35c134eeb 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7864,6 +7864,8 @@ variable-list-end {0}, {1} {0} i {1} @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` és {_1}; aquest amfitrió admet els nivells d’API de complements de l’1 al {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` només pot ser true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` només és per a un efecte dinàmic (`kind` "effect") amb `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` només és per a un importador (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` «{shown}» obre fitxers però no els col·loca: el seu manifest no defineix `place` @msg `grant` must be a list of permission names `grant` ha de ser una llista de noms de permisos @msg `grant` names an unknown permission `{shown}` `grant` esmenta un permís desconegut `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` un complement del tipus `{_1}` necessita el permís `{_2}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..5c4fafbb50 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7474,6 +7474,8 @@ axis Y Axis osa Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` je {_1}; tento hostitel podporuje úrovně API zásuvných modulů 1 až {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` může být jen true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` je jen pro živý efekt (`kind` "effect") s `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` je jen pro importér (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` „{shown}“ otevírá soubory, ale neumísťuje je: jeho manifest nenastavuje `place` @msg `grant` must be a list of permission names `grant` musí být seznam názvů oprávnění @msg `grant` names an unknown permission `{shown}` `grant` uvádí neznámé oprávnění `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` zásuvný modul druhu `{_1}` potřebuje oprávnění `{_2}` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..55aca3499b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -686,6 +686,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` er {_1}; denne vært implementerer plug-in-API-niveau 1 til {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` må kun være true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` er kun til en live-effekt (`kind` "effect") ved `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` er kun til en importør (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` »{shown}« åbner filer, men placerer dem ikke: dens manifest angiver ikke `place` @msg `grant` must be a list of permission names `grant` skal være en liste med tilladelsesnavne @msg `grant` names an unknown permission `{shown}` `grant` angiver en ukendt tilladelse `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` et plug-in af typen `{_1}` kræver tilladelsen `{_2}` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..ff6b4f7d60 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7057,6 +7057,8 @@ axis Y Axis Y-Achse @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` ist {_1}; dieser Host unterstützt die Plug-in-API-Stufen 1 bis {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` darf nur true sein @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` gilt nur für einen Live-Effekt (`kind` "effect") mit `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` gilt nur für einen Importer (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` „{shown}“ öffnet Dateien, platziert sie aber nicht: sein Manifest setzt `place` nicht @msg `grant` must be a list of permission names `grant` muss eine Liste von Berechtigungsnamen sein @msg `grant` names an unknown permission `{shown}` `grant` nennt eine unbekannte Berechtigung `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` ein Plug-in der Art `{_1}` braucht die Berechtigung `{_2}` diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..12a0aec632 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7464,6 +7464,8 @@ axis Y Axis Άξονας Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} το `api` είναι {_1}· αυτός ο κεντρικός υπολογιστής υποστηρίζει τα επίπεδα API προσθέτων 1 έως {API_LEVEL} @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 `place` is only for an importer (`kind` "importer") το `place` ισχύει μόνο για εισαγωγέα (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` το «{shown}» ανοίγει αρχεία αλλά δεν τα τοποθετεί: το manifest του δεν ορίζει `place` @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}` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..57c30dd117 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7450,6 +7450,8 @@ axis Y Axis Eje Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` es {_1}; este host admite los niveles de API de plugins de 1 a {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` solo puede ser true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` solo es para un efecto dinámico (`kind` "effect") con `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` solo es para un importador (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` «{shown}» abre archivos pero no los coloca: su manifiesto no establece `place` @msg `grant` must be a list of permission names `grant` debe ser una lista de nombres de permisos @msg `grant` names an unknown permission `{shown}` `grant` nombra un permiso desconocido `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` un plugin de tipo `{_1}` necesita el permiso `{_2}` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..f704e930ad 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7541,6 +7541,8 @@ axis Y Axis Y-akseli @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` on {_1}; tämä isäntä tukee laajennus-API:n tasoja 1 ja {API_LEVEL} välillä @msg `paintOutput` may only be true `paintOutput` voi olla vain true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` on vain reaaliaikaiselle tehosteelle (`kind` "effect") tasolla `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` on vain tuojalle (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` ”{shown}” avaa tiedostoja mutta ei sijoita niitä: sen manifesti ei aseta `place`-avainta @msg `grant` must be a list of permission names `grant` on oltava luettelo käyttöoikeuksien nimistä @msg `grant` names an unknown permission `{shown}` `grant` nimeää tuntemattoman käyttöoikeuden `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` lajin `{_1}` laajennus tarvitsee käyttöoikeuden `{_2}` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..4ce7261b75 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7470,6 +7470,8 @@ axis Y Axis Axe Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` vaut {_1} ; cet hôte prend en charge les niveaux d’API de module externe 1 à {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` ne peut valoir que true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` est réservé à un effet dynamique (`kind` "effect") avec `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` est réservé à un importateur (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` Le plug-in {shown} ouvre des fichiers mais ne les place pas, car son manifeste ne définit pas `place` @msg `grant` must be a list of permission names `grant` doit être une liste de noms d’autorisations @msg `grant` names an unknown permission `{shown}` `grant` nomme une autorisation inconnue `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` un module externe de type `{_1}` a besoin de l’autorisation `{_2}` diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..2bfc813007 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6658,6 +6658,8 @@ arrowhead Feather पंख @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` {_1} है; यह होस्ट प्लग-इन API स्तर 1 से {API_LEVEL} तक का समर्थन करता है @msg `paintOutput` may only be true `paintOutput` केवल true हो सकता है @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` केवल `api` 2 पर लाइव इफ़ेक्ट (`kind` "effect") के लिए है +@msg `place` is only for an importer (`kind` "importer") `place` केवल इम्पोर्टर (`kind` "importer") के लिए है +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}” फ़ाइलें खोलता है पर उन्हें प्लेस नहीं करता: उसका मैनिफ़ेस्ट `place` सेट नहीं करता @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}` अनुमति चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..5808f8dfd8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7459,6 +7459,8 @@ axis Y Axis Y tengely @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} az `api` értéke {_1}; ez a gazdaprogram az 1 és {API_LEVEL} közötti bővítmény-API-szinteket támogatja @msg `paintOutput` may only be true A `paintOutput` értéke csak true lehet @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 a `paintOutput` csak élő effektushoz (`kind` "effect") használható, `api` 2 mellett +@msg `place` is only for an importer (`kind` "importer") a `place` csak importálóhoz (`kind` "importer") használható +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` „{shown}” megnyitja a fájlokat, de nem helyezi el őket: a jegyzéke nem állítja be a `place` kulcsot @msg `grant` must be a list of permission names a `grant` értékének engedélynevek listájának kell lennie @msg `grant` names an unknown permission `{shown}` a `grant` ismeretlen engedélyt nevez meg: `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` egy `{_1}` fajtájú bővítménynek szüksége van a(z) `{_2}` engedélyre diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..81d99f4312 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -568,6 +568,8 @@ @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` bernilai {_1}; host ini menerapkan API plug-in tingkat 1 sampai {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` hanya boleh true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` hanya untuk efek langsung (`kind` "effect") pada `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` hanya untuk pengimpor (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}” membuka berkas tetapi tidak menempatkannya: manifesnya tidak menetapkan `place` @msg `grant` must be a list of permission names `grant` harus berupa daftar nama izin @msg `grant` names an unknown permission `{shown}` `grant` menyebut izin yang tidak dikenal `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` plug-in berjenis `{_1}` memerlukan izin `{_2}` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..2eb0115d39 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7096,6 +7096,8 @@ axis Y Axis Asse Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` è {_1}; questo host supporta i livelli API dei plug-in da 1 a {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` può essere solo true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` vale solo per un effetto dinamico (`kind` "effect") con `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` vale solo per un importatore (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` «{shown}» apre file ma non li inserisce: il suo manifest non imposta `place` @msg `grant` must be a list of permission names `grant` deve essere un elenco di nomi di autorizzazioni @msg `grant` names an unknown permission `{shown}` `grant` indica un’autorizzazione sconosciuta `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` un plug-in di tipo `{_1}` richiede l’autorizzazione `{_2}` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..7c48013363 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7171,6 +7171,8 @@ axis Y Axis Y 軸 @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` は {_1} です。このホストが対応するプラグイン API レベルは 1 から {API_LEVEL} です @msg `paintOutput` may only be true `paintOutput` には true のみ指定できます @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` は `api` 2 のライブ効果 (`kind` "effect") 専用です +@msg `place` is only for an importer (`kind` "importer") `place` はインポーター (`kind` "importer") 専用です +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` 「{shown}」はファイルを開きますが配置はしません: マニフェストで `place` が設定されていません @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}` が必要です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..da5ad6fffe 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9577,6 +9577,8 @@ axis Y Axis Y ღერძი @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` არის {_1}; ეს ჰოსტი პლაგინის API-ის დონეებს 1-დან {API_LEVEL}-მდე უჭერს მხარს @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 `place` is only for an importer (`kind` "importer") `place` მხოლოდ იმპორტერისთვისაა (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` „{shown}“ ხსნის ფაილებს, მაგრამ არ ათავსებს: მის მანიფესტში `place` არ არის მითითებული @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}` diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..7005da106e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7068,6 +7068,8 @@ axis Y Axis Y축 @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api`가 {_1}입니다. 이 호스트는 플러그인 API 수준 1부터 {API_LEVEL}까지 지원합니다 @msg `paintOutput` may only be true `paintOutput`에는 true만 지정할 수 있습니다 @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput`은 `api` 2의 라이브 효과(`kind` "effect")에만 쓸 수 있습니다 +@msg `place` is only for an importer (`kind` "importer") `place`는 임포터(`kind` "importer")에만 쓸 수 있습니다 +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}”은(는) 파일을 열지만 배치하지는 않습니다: 매니페스트에 `place`가 설정되어 있지 않습니다 @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}` 권한이 필요합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..deeaeb899c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -532,6 +532,8 @@ liquify-list-end {0}, {1} {0} en {1} @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` is {_1}; deze host implementeert plug-in-API-niveaus 1 tot {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` mag alleen true zijn @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` is alleen voor een live-effect (`kind` "effect") bij `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` is alleen voor een importer (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` „{shown}” opent bestanden maar plaatst ze niet: het manifest stelt `place` niet in @msg `grant` must be a list of permission names `grant` moet een lijst met namen van machtigingen zijn @msg `grant` names an unknown permission `{shown}` `grant` noemt een onbekende machtiging `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` een plug-in van het soort `{_1}` heeft de machtiging `{_2}` nodig diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..87e302d111 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7329,6 +7329,8 @@ axis Y Axis Oś Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` ma wartość {_1}; ten host obsługuje poziomy API wtyczek od 1 do {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` może mieć tylko wartość true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` dotyczy tylko efektu na żywo (`kind` "effect") z `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` dotyczy tylko importera (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` „{shown}” otwiera pliki, ale ich nie umieszcza: jego manifest nie ustawia `place` @msg `grant` must be a list of permission names `grant` musi być listą nazw uprawnień @msg `grant` names an unknown permission `{shown}` `grant` wymienia nieznane uprawnienie `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` wtyczka rodzaju `{_1}` potrzebuje uprawnienia `{_2}` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..c0ba4962ef 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7373,6 +7373,8 @@ axis Y Axis Eixo Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` é {_1}; este host aceita os níveis de API de plug-in de 1 a {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` só pode ser true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` é só para um efeito dinâmico (`kind` "effect") com `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` é só para um importador (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}” abre arquivos, mas não os insere: seu manifesto não define `place` @msg `grant` must be a list of permission names `grant` deve ser uma lista de nomes de permissões @msg `grant` names an unknown permission `{shown}` `grant` cita uma permissão desconhecida `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` um plug-in do tipo `{_1}` precisa da permissão `{_2}` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..bda625997c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7096,6 +7096,8 @@ axis Y Axis Ось Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` равно {_1}; этот хост поддерживает уровни API модулей от 1 до {API_LEVEL} @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 `place` is only for an importer (`kind` "importer") `place` допустим только для импортёра (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` «{shown}» открывает файлы, но не помещает их: его манифест не задаёт `place` @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}` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..f5a2cbdd69 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7486,6 +7486,8 @@ axis Y Axis Y-axel @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` är {_1}; den här värden stöder plugin-API-nivå 1 till {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` får bara vara true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` gäller bara en liveeffekt (`kind` "effect") med `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` gäller bara en importör (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` ”{shown}” öppnar filer men placerar dem inte: dess manifest anger inte `place` @msg `grant` must be a list of permission names `grant` måste vara en lista med behörighetsnamn @msg `grant` names an unknown permission `{shown}` `grant` anger en okänd behörighet `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` ett plugin av typen `{_1}` behöver behörigheten `{_2}` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..1ac316d616 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7546,6 +7546,8 @@ axis Y Axis Y ekseni @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` değeri {_1}; bu ana bilgisayar 1 ile {API_LEVEL} arasındaki eklenti API düzeylerini destekler @msg `paintOutput` may only be true `paintOutput` yalnızca true olabilir @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` yalnızca `api` 2 düzeyindeki canlı efekt (`kind` "effect") içindir +@msg `place` is only for an importer (`kind` "importer") `place` yalnızca içe aktarıcı (`kind` "importer") içindir +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}” dosyaları açar ama yerleştirmez: bildirimi `place` ayarlamaz @msg `grant` must be a list of permission names `grant` izin adlarından oluşan bir liste olmalıdır @msg `grant` names an unknown permission `{shown}` `grant` bilinmeyen bir izin adlandırıyor: `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` `{_1}` türündeki bir eklentinin `{_2}` iznine ihtiyacı vardır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..7c303c5753 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7078,6 +7078,8 @@ axis Y Axis Вісь Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` дорівнює {_1}; цей хост підтримує рівні API модулів від 1 до {API_LEVEL} @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 `place` is only for an importer (`kind` "importer") `place` дозволено лише для імпортера (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` «{shown}» відкриває файли, але не розміщує їх: його маніфест не задає `place` @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}` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..45ab19d693 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7125,6 +7125,8 @@ axis Y Axis Trục Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` là {_1}; máy chủ này hỗ trợ các mức API plug-in từ 1 đến {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` chỉ có thể là true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` chỉ dành cho hiệu ứng trực tiếp (`kind` "effect") ở `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` chỉ dành cho trình nhập (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}” mở tệp nhưng không đặt chúng: tệp kê khai của nó không đặt `place` @msg `grant` must be a list of permission names `grant` phải là danh sách tên quyền @msg `grant` names an unknown permission `{shown}` `grant` nêu một quyền không xác định `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` plug-in loại `{_1}` cần quyền `{_2}` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..dd9933c6b8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7306,6 +7306,8 @@ axis Y Axis Y 轴 @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` 为 {_1};此主机支持的增效工具 API 级别为 1 到 {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` 只能为 true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` 仅适用于 `api` 2 的实时效果 (`kind` "effect") +@msg `place` is only for an importer (`kind` "importer") `place` 仅适用于导入器 (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}” 只打开文件而不置入:其清单未设置 `place` @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}` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..654eb171a7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7127,6 +7127,8 @@ axis Y Axis Y 軸 @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` 為 {_1};此主機支援的增效模組 API 層級為 1 到 {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` 只能為 true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` 僅適用於 `api` 2 的即時效果 (`kind` "effect") +@msg `place` is only for an importer (`kind` "importer") `place` 僅適用於匯入器 (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` 「{shown}」只開啟檔案而不置入:其資訊清單未設定 `place` @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}` diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index a36d85f8a2..9c724c8b29 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -205,7 +205,10 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result Result Result Result<(), String> { let paths = if app.services.pick_open_multi.is_some() { crate::picks::open_many(app) } else { - crate::picks::open(app, &crate::FilePick { filters: crate::FilePick::filters(fileio::place_filters()), ..Default::default() }) + crate::picks::open(app, &crate::FilePick { filters: crate::FilePick::filters(fileio::place_dialog_filters()), ..Default::default() }) .into_iter() .collect() }; diff --git a/docs/gaps.md b/docs/gaps.md index 549d74f46b..259a740404 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -905,6 +905,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi It is given at most 128 MiB of the file and returns paths and compound paths, checked as a filter's output is, which become a new document; nothing opens when it fails, declines or is cancelled. Engine, unit and headless Open With regressions. +- **Done:** importer plug-ins that place files (`"place": true`). File › Place lists their files, and `file.place` reads + a file with one when `importer` names it or no built-in format reads the file; its objects are placed as one group, + embedded, as one undo step, and nothing is placed when it fails, declines or is cancelled. Engine regressions. - **Done:** exporter plug-ins (`"kind": "exporter"`). A plug-in adds a write-only file format that File › Export › Export As lists after the built-in ones and `document.export` writes (`plugin.`, or a path ending in one of its extensions). It is given the document as the native file's JSON and its parameters, with a larger budget than a diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..5236cc7e25 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13296,7 +13296,13 @@ with `read: true`, and `openExtensions` holds the extensions File › Open opens extension, with the installed importer that lists the extension (the one whose id sorts first, when several do). `importer` names the importer to use, which must list the file's extension, also one a built-in format reads, such as `svg`. The importer is given at most 128 MiB of the file; its objects become a new document whose artboard is -their bounds, Save then asks for a name, and `warnings` holds the importer's warnings. `plugin.run` of an importer is +their bounds, Save then asks for a name, and `warnings` holds the importer's warnings. An importer whose manifest sets +`place` (`place: true` in `document.formats` and `plugin.list`) also places its files: `file.place`, `file.place.info` +and `file.place.queue` take `importer?: "plugin."` (one that sets `place` and lists the file's extension) and +`params?`, and without `importer` a file no built-in format reads goes to the first such importer by id that lists its +extension. The importer is given at most 128 MiB of the file (a larger file is refused from its size, before it is read) +and `_context.mode` `"place"`; its objects, guides left out, are placed as one group named after the file, in the order +it returned them, as one undo step, embedded whatever `link` says (`linked: false`). `plugin.run` of an importer is an error that names `document.open`. In the app, File › Open With lists the installed importers, and `file.openWith {importer, path?, params?}` opens `path`, or a file picked among the importer's extensions, with one (on the web it opens File › Open's picker) and adds it to Open Recent. With `path` the reply is `document.open`'s result; diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..9a17420c8d 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -51,8 +51,26 @@ by its extension, and the importer lists the file's extension; when several do, also one a built-in format reads (an importer that lists `svg` opens an `.svg` only this way). A damaged file of a built-in format reports that format's error, and the file is not handed to an importer. The importer's objects become a new document whose artboard is their bounds (at least 1 pt wide and high, and within ±4,000,000 pt); the document keeps -no path, so Save asks for a name. File › Place reads only the built-in formats, and a file only an importer reads opens -as a new document when it is dropped on the canvas. These rules are VectorCraft's own. +no path, so Save asks for a name. A file only an importer reads opens as a new document when it is dropped on the +canvas, unless an importer that places its files reads it (below). These rules are VectorCraft's own. + +An importer whose manifest has `"place": true` also places its files. `document.formats` and `plugin.list` mark it with +`place: true`. `file.place`, `file.place.info` and `file.place.queue` read a file with it by the rules above, among the +importers that set `place`: when no built-in format reads the file, the first such importer by id that lists its +extension reads it, and `"importer": "plugin."` names one, which must set `place` and list the file's extension, +also one a built-in format reads. `"params"?: {…}` holds its parameters, which take their defaults when left out. The +importer is given at most 128 MiB of the file (a larger file is refused from its size, before it is read) and +`_context.mode` `"place"`, and returns its objects as it does for File › Open. They are placed in the open document as +one group named after the file, in the order the importer returned them, at the place, size or object `at`, `rect`, +`replace` and `template` give, as one undo step; guides are left out, and the group's box is the bounds of what the +other objects draw. The file is embedded whatever `link` +says, as a format that can't be linked is, and the reply's `linked` is `false`. A decline, invalid output, a trap or +Cancel places nothing and leaves the document and its undo steps as they were. An importer without `place` is not used +by File › Place, and naming it is an error. In the app, File › Place lists a placing importer's extensions under "All +placeable files" and a filter of its own, named after the importer, and on the web its files dropped on the canvas are +placed there (the desktop opens a dropped document, as it does an SVG); the importer then runs with its parameters' +defaults. A file placed with `importer` goes to that importer without the import options File › Place shows for a +text file, a DXF drawing, a PDF or a PSD file. These rules are VectorCraft's own. In the app, installed filters appear under **Object › Plug-ins**, next to **Install Plug-in…** and **Reload Plug-ins**; live effects under **Effect › Plug-ins** and in the Appearance panel's effect menu. A plug-in with @@ -565,6 +583,11 @@ the module's start function, in a run that isn't a filter's run on a document, o without the dot (`["plt"]`); the first is the one Export As gives the file. A built-in format keeps an extension both list (`svg`): `document.export` then writes the exporter's format only when asked for by its format id, and `document.open` reads a file with the importer only when `importer` names it. +- `place` (importers only): `true` lets File › Place read the importer's files too ([using plug-ins](#using-plug-ins)); + `false`, the default, keeps it to File › Open. A value that isn't `true` or `false`, or the key on another kind, is + refused when the plug-in is installed. It asks for no permission beyond `import.read`: the importer is given the file + and its parameters alone, and the host places what it returns. Hosts from before the key ignore it, so there the + importer opens its files and places none. - `commands` (filters and live effects; not heavy filters): up to 32 commands of the plug-in's own ([Commands](#commands)), each `{"id": "grow", "label": "Grow", "params"?: {…}}`. An `id` is 1–32 characters from `a-z 0-9 _` that starts with a letter, and appears once. A `label` is 1–64 printable characters; menus show it with @@ -737,7 +760,7 @@ toward the 64 MiB output cap. "_context": {"mode": "filter", "bounds": [10, 0, 75, 60], "artboard": [0, 0, 612, 792], "documentData": {"pens": 4}}} ``` -`mode` is `"filter"`, `"effect"`, `"export"`, `"import"` or `"command"` (a [command](#commands) run, whose +`mode` is `"filter"`, `"effect"`, `"export"`, `"import"`, `"place"` or `"command"` (a [command](#commands) run, whose `command` is the command's id); `bounds` the selection's geometric bounds (a live effect: the reference box of the effect, the object's bounds or those of the previous effect's result); `artboard` (filters) the artboard under the selection's centre, else the first; `documentData` (filters) what the plug-in last kept with the document (`null` until @@ -747,7 +770,8 @@ it keeps something; see Output). A live effect's `item` says where it sits: `"ob the extension of the file being written (one the exporter lists) and its name without the extension (the document's name when the export is not given a path), which some formats keep in their header. An import's `_context` is `{"mode": "import", "extension": "plt", "name": "Poster"}`: the extension of the file being opened and its name without the -extension. +extension. A place's `_context` is the same with `"mode": "place"`; the importer is given nothing of the document the +file is placed in. ### Output @@ -854,7 +878,9 @@ with the export's own). A decline (`{"error": …}`), a missing `dataBase64` or An **importer** returns `{"objects": [...], "warnings"?: ["…"]}`: new paths and compound paths (no `id`) in the filters' object form, checked as a filter's new objects are, with warnings capped as an exporter's are and shown with the open's own. An output with no objects, with keys other than `objects`, `warnings` and `error`, or with an object -that fails the checks opens nothing, and neither does a decline (`{"error": …}`). +that fails the checks opens nothing, and neither does a decline (`{"error": …}`). An importer that places its files +returns the same output when `_context.mode` is `"place"`; an output that fails, or whose objects other than guides draw +nothing of any width or height, places nothing. ## Writing a plug-in in Rust @@ -885,9 +911,8 @@ per change of their input, parameters or paints (results are cached), not per fr ## Not in v1 -- Tool plug-ins (pointer events on the canvas, a guide line or rectangle, geometry back), panel plug-ins, and - importers that place files (File › Place reads only the built-in formats) or make type, images, layers or - artboards. +- Tool plug-ins (pointer events on the canvas, a guide line or rectangle, geometry back), panel plug-ins, importers + that make type, images, layers or artboards, and placed importer files that stay linked to their file. - Live effects that change opacity, blending or effects (at `api` 2 one may [paint](#painted-live-effects) the pieces it returns), and filters that change type, images or symbol instances (a filter at `api` 2 reads them, see [`inputs`](#reading-type-images-and-symbols)). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..652019e0fb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2645,6 +2645,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Exporter plug-ins (G17):** a WebAssembly plug-in of kind `exporter` adds a write-only file format. File › Export › Export As lists it after the built-in formats, with Use Artboards greyed out (the plug-in writes the whole document) and its parameters in a generated dialog once the file is picked; `document.export` writes it by its format id, `plugin.`, or by one of its extensions, and built-in formats keep theirs. The plug-in is given the native file's JSON (large images without their data) and `_context` (`mode`, `extension`, `name`), with 10 G instructions plus 4,000 per byte of input and 300 s, and Background Export's Cancel stops it between two slices of that budget. A decline or invalid output writes nothing; its warnings come back with the export's. Regressions: `crates/engine/tests/plugin_export.rs`, `crates/plugins/tests/abi.rs`, `crates/ui-egui/src/dialogs/tests_plugin_export.rs`. Scores and hours unchanged. - **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. +- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size before it is read) and `_context.mode` `"place"`, and its objects are placed as one group named after the file, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. - **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged. From 38cfc3073e525074a44ebb532550adcba27c45b8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:28:41 -0800 Subject: [PATCH 047/101] Tests: the Shape Builder's freeform fill keeps its stops without points The test now gives the tool's freeform fill Lines mode first, so the fill has a freeform state with no points when its stops are edited. It checks that the supplied stops and the mode survive the edit and the recolor of the selected stop. Without the guard that skips recoloring from an empty point list, the stops edit resets the first stop to white and the test fails. --- crates/ui-egui/src/panels/gradient/tests.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 7f8515dcca..7aa1b36559 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -64,21 +64,27 @@ fn a_swatch_color_on_a_stop_or_a_point_keeps_its_model_in_a_cmyk_document() { } /// While the Shape Builder paints with a freeform fill, which lies on no object, the panel shows -/// that fill's stops, and a swatch color recolors the selected stop instead of a point. +/// that fill's stops, and a swatch color recolors the selected stop instead of a point. Lines +/// mode gives the fill a freeform state without points, which the stops edit keeps. #[test] fn the_shape_builders_freeform_fill_is_edited_by_its_stops() { use egui_kittest::kittest::Queryable; let mut app = app(json!({"color": "#000000"})); app.select_tool("shapeBuilder"); - app.run("paint.editGradient", json!({"stroke": false, "kind": "freeform"})).unwrap(); + app.run("paint.editGradient", json!({"stroke": false, "kind": "freeform", "mode": "lines"})).unwrap(); let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); app.run("paint.editGradient", json!({"stroke": false, "stops": stops})).unwrap(); + let Paint::Gradient(g) = active_paint(&app) else { panic!("the tool's fill is not a gradient") }; + assert_eq!(g.freeform.as_ref().map(|f| (f.points.len(), f.mode)), Some((0, FreeformMode::Lines))); + assert_eq!(g.gradient.stops[0].color, Color::rgb8(255, 0, 0), "the stops edit keeps the supplied stops"); app.run("gradient.selectStop", json!({"index": 1})).unwrap(); let orange = Color::rgb8(255, 128, 0); assert!(recolor_selected(&mut app, orange, &json!({})), "the selected stop takes the color"); let Paint::Gradient(g) = active_paint(&app) else { panic!("the tool's fill is not a gradient") }; assert_eq!(g.gradient.kind, GradientKind::Freeform); + assert_eq!(g.gradient.stops[0].color, Color::rgb8(255, 0, 0)); assert_eq!(g.gradient.stops[1].color, orange); + assert_eq!(g.freeform.map(|f| f.mode), Some(FreeformMode::Lines)); let mut fonts = false; let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(280.0, 640.0)).with_accessibility_check(false).build_ui_state( move |ui, app: &mut VectorcraftApp| { From e2334a21652950b6804ce078eb47785aaf9506a9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:39:29 -0800 Subject: [PATCH 048/101] Smart Pen: the tool is in the Pen tool's flyout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Smart Pen Tool joins the Pen group in both shipped toolbars, after the Quick Pen, and stays in Object › Plug-ins › Smart Pen. The All Tools drawer lists it once, under Draw, and Edit › Keyboard Shortcuts › Tools lists it once. It has no default shortcut, and the Pen keeps P. A toolbar the user already edited keeps its saved layout; Reset Toolbar adds the tool. A group torn off the Tools panel's toolbar now shows the tools of the current layout's group that starts with the same tool, after toolbar edits, Reset Toolbar, a switch between Basic and Advanced, loading the preferences and switching workspaces, as groups torn off a toolbar made with New Toolbar already did. A strip with no such group keeps its tools. Part of #8326 --- crates/mcp/src/tests.rs | 12 +++ crates/tools/src/addons.rs | 34 ++++-- crates/tools/src/catalog.rs | 2 + crates/ui-egui/src/control/tests.rs | 4 +- crates/ui-egui/src/edit_toolbar.rs | 34 ++++++ crates/ui-egui/src/edit_toolbar/tests.rs | 131 ++++++++++++++++++++++- crates/ui-egui/src/menus/run.rs | 6 +- crates/ui-egui/src/state.rs | 1 + crates/ui-egui/src/toolbar.rs | 6 +- crates/ui-egui/src/toolbar/tests.rs | 7 +- crates/ui-egui/src/workspaces.rs | 1 + docs/control-protocol.md | 4 +- docs/mcp.md | 4 +- docs/target-app-parity.md | 8 +- docs/ui-parity.md | 4 +- 15 files changed, 232 insertions(+), 26 deletions(-) diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index c8756cefc7..9b27b976de 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1599,6 +1599,18 @@ fn headless_backend_methods() { assert_eq!(with_enclosing[0][1]["label"], "Enclosing Lasso Tool"); assert!(with_enclosing[0][1]["shortcut"].is_null()); assert_eq!(h.call("ui.tool.select", json!({"tool": enclosing})).unwrap()["tool"], enclosing); + // The Smart Pen Tool is listed once, at the end of the Pen tool's group. + let smart_pen = vectorcraft_tools::addons::smart_pen::ID; + let with_smart_pen: Vec<_> = + groups.iter().map(|group| group.as_array().unwrap()).filter(|group| group.iter().any(|entry| entry["id"] == smart_pen)).collect(); + assert_eq!(with_smart_pen.len(), 1, "{smart_pen} is in one group"); + let ids: Vec<_> = with_smart_pen[0].iter().map(|entry| entry["id"].clone()).collect(); + assert_eq!(ids.first(), Some(&json!("pen"))); + assert_eq!(ids[ids.len().saturating_sub(2)..], [json!("quickPen"), json!(smart_pen)]); + let entry = with_smart_pen[0].iter().find(|entry| entry["id"] == smart_pen).unwrap(); + assert_eq!(entry["label"], "Smart Pen Tool"); + assert!(entry["shortcut"].is_null()); + assert_eq!(h.call("ui.tool.select", json!({"tool": smart_pen})).unwrap()["tool"], smart_pen); let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso"); assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool"))); assert!(h.call("ui.resize", json!({})).is_err()); diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index c0223aedb9..1a240419be 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -1,9 +1,9 @@ //! The tools of VectorCraft's built-in add-ons. They aren't in the toolbars as they ship: the All //! Tools drawer lists them (under their add-on's heading) so they can be added, and each add-on's -//! submenu selects them. Tool gestures emit engine commands. Two tools are the exceptions: the Trim -//! at Crossings Tool is in the Scissors tool's group and the Enclosing Lasso Tool is in the Lasso -//! tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and the All Tools drawer show them, as -//! well as in their add-ons' submenus. +//! submenu selects them. Tool gestures emit engine commands. Three tools are the exceptions: the +//! Trim at Crossings Tool is in the Scissors tool's group, the Enclosing Lasso Tool is in the Lasso +//! tool's group and the Smart Pen Tool is in the Pen tool's group ([`crate::TOOL_GROUPS`]), where +//! the toolbars and the All Tools drawer show them, as well as in their add-ons' submenus. pub mod anchor_eraser; pub mod box3d; @@ -35,9 +35,6 @@ pub const PATH_TOOLS: &[ToolInfo] = &[ ToolInfo { id: tangent_circle::ID, label: "Tangent Circle Tool", shortcut: None, icon: "circle" }, ]; -/// Smart Pen's tool, a flyout group of its own. -pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart Pen Tool", shortcut: None, icon: "spline-pointer" }]; - 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" }]; @@ -47,10 +44,10 @@ pub const POLYGONAL_LASSO: &[ToolInfo] = &[ToolInfo { id: polygonal_lasso::ID, l /// 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). const HEADED: &[(&[ToolInfo], &str)] = - &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (CONTOUR, "Contour"), (BOX_3D, "3D Box"), (POLYGONAL_LASSO, "Polygonal Lasso")]; + &[(PATH_TOOLS, "Path Precision Tools"), (CONTOUR, "Contour"), (BOX_3D, "3D Box"), (POLYGONAL_LASSO, "Polygonal Lasso")]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]). -pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, CONTOUR, BOX_3D, POLYGONAL_LASSO]; +pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, CONTOUR, BOX_3D, POLYGONAL_LASSO]; /// The heading the All Tools drawer lists tool `id` under: its add-on's name. pub fn heading(id: &str) -> Option<&'static str> { @@ -92,7 +89,6 @@ mod tests { assert!(!crate::TOOL_GROUPS.iter().any(|g| g.iter().any(|x| x.id == t.id)), "{} is not in the toolbar's groups", t.id); } assert!(PATH_TOOLS.iter().all(|t| heading(t.id) == Some("Path Precision Tools"))); - assert_eq!(heading(smart_pen::ID), Some("Smart Pen")); assert_eq!(heading(contour::ID), Some("Contour")); assert_eq!(heading(box3d::ID), Some("3D Box")); assert_eq!(heading(polygonal_lasso::ID), Some("Polygonal Lasso")); @@ -134,4 +130,22 @@ mod tests { assert!(heading(id).is_none(), "not listed again under the add-on"); assert_eq!(crate::catalog::all_tools().filter(|t| t.id == id).count(), 1); } + + /// The Smart Pen Tool is in the Pen tool's group, after the Pen family's own tools, with no + /// default shortcut, listed once, and still made by its add-on. + #[test] + fn smart_pen_is_in_the_pen_group_once() { + let id = smart_pen::ID; + let groups: Vec<_> = crate::TOOL_GROUPS.iter().filter(|g| g.iter().any(|t| t.id == id)).collect(); + assert_eq!(groups.len(), 1); + let ids: Vec<_> = groups[0].iter().map(|t| t.id).collect(); + assert_eq!(ids.first(), Some(&"pen"), "the Pen stays the group's default"); + assert_eq!(ids[ids.len().saturating_sub(2)..], [crate::quickpen::ID, id], "right after the Quick Pen, last"); + let info = crate::tool_info(id).expect("catalogued"); + assert_eq!((info.label, info.shortcut), ("Smart Pen Tool", None)); + assert_eq!(crate::tool_info("pen").and_then(|t| t.shortcut), Some("P"), "the Pen 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"); + assert_eq!(crate::catalog::all_tools().filter(|t| t.id == id).count(), 1); + } } diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 2dc0774aa2..c839287732 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -35,6 +35,8 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("deleteAnchor", "Delete Anchor Point Tool", Some("-"), "tool-pen-delete"), t("anchorPoint", "Anchor Point Tool", Some("Shift+C"), "tool-anchor"), t(crate::quickpen::ID, "Quick Pen Tool", Some("Alt+P"), "tool-quick-pen"), + // Smart Pen's tool, kept out of `addons::GROUPS` so that `all_tools` lists it once. + t(crate::addons::smart_pen::ID, "Smart Pen Tool", None, "spline-pointer"), ], &[t("curvature", "Curvature Tool", Some("Shift+~"), "tool-curvature")], &[ diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 96c4880d39..f627c63a1a 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -613,7 +613,9 @@ fn control_lists_and_selects_optional_addon_tools() { let listed = input_request(&mut app, "ui.tool.list", json!({})); assert_eq!(listed["ok"], true); let groups = listed["result"].as_array().unwrap(); - for tool in vectorcraft_tools::addons::GROUPS.iter().flat_map(|group| group.iter()) { + // The add-on tools that ship in a toolbar group as well. + let in_toolbar_groups = [vectorcraft_tools::addons::smart_pen::ID].map(|id| vectorcraft_tools::tool_info(id).expect("catalogued")); + for tool in vectorcraft_tools::addons::GROUPS.iter().flat_map(|group| group.iter()).chain(in_toolbar_groups) { let matching: Vec<_> = groups.iter().flat_map(|group| group.as_array().unwrap()).filter(|entry| entry["id"] == tool.id).collect(); assert_eq!(matching.len(), 1, "{}", tool.id); assert_eq!(matching[0]["label"], tool.label); diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index 5c1fa8f6ed..f0aa5b3621 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -153,9 +153,42 @@ fn edit(app: &mut VectorcraftApp, f: impl FnOnce(&mut Vec) -> R f(&mut cats)?; prune(&mut cats); *slot = (cats != shipped(advanced)).then_some(cats); + keep_strips(&mut app.ui); Ok(slots_json(app)) } +/// Give each group torn off the Tools panel's toolbar the tools of the current layout's group +/// with the same first tool, as [`crate::custom_toolbars::keep_strips`] does for a toolbar made +/// with New Toolbar. A strip with no such group keeps its tools. +pub(crate) fn keep_strips(ui: &mut crate::state::UiState) { + if ui.floating_flyouts.is_empty() { + return; + } + let groups = layout_groups(ui); + for f in &mut ui.floating_flyouts { + if let Some(group) = f.tools.first().and_then(|k| group_of(&groups, k)) { + f.tools = group; + } + } +} + +/// The tools of the current layout's group of several tools that starts with `key`, if there is +/// one ([`keep_strips`]). +pub(crate) fn layout_group(ui: &crate::state::UiState, key: &str) -> Option> { + group_of(&layout_groups(ui), key) +} + +/// The groups of the Tools panel's current layout, as Edit Toolbar left it. +fn layout_groups(ui: &crate::state::UiState) -> Vec> { + let edited = if ui.toolbar_advanced { &ui.toolbar_edits.advanced } else { &ui.toolbar_edits.basic }; + let cats = edited.clone().unwrap_or_else(|| shipped(ui.toolbar_advanced)); + cats.iter().flat_map(|c| c.slots.iter()).map(|s| s.iter().filter_map(|id| tool_info(id).map(|t| t.id)).collect()).collect() +} + +fn group_of(groups: &[Vec<&'static str>], key: &str) -> Option> { + groups.iter().find(|s| s.len() > 1 && s.first() == Some(&key)).map(|s| s.iter().map(|id| id.to_string()).collect()) +} + /// Change the toolbar made with New Toolbar called `name` with `f`, and the groups torn off it with /// it ([`crate::custom_toolbars::keep_strips`]). Returns its slots. fn edit_custom(app: &mut VectorcraftApp, name: &str, f: impl FnOnce(&mut Vec) -> Result<(), String>) -> Result { @@ -311,6 +344,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option return None, diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 0973a752b2..bfde6f06d5 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -233,6 +233,128 @@ fn a_saved_toolbar_without_enclosing_lasso_keeps_its_layout() { assert!(slot.is_some_and(|s| s.contains(&id)), "Reset Toolbar adds it"); } +/// The Smart Pen Tool is in the Pen tool's flyout in both toolbars, after the Pen family's own +/// tools, once in the All Tools drawer (under Draw) and in Keyboard Shortcuts' list, with no +/// shortcut; its button's tip names it; Reset Toolbar keeps it there. +#[test] +fn smart_pen_is_in_the_pen_flyout() { + let mut app = app(); + let id = vectorcraft_tools::addons::smart_pen::ID; + for advanced in [false, true] { + if advanced { + app.run("window.toolbarAdvanced", json!({})).unwrap(); + } + let s = slots(&app); + let slot = slot_of(&app, "pen").map(|i| s[i].clone()).expect("a Pen slot"); + assert_eq!(slot.first(), Some(&"pen"), "advanced: {advanced}"); + assert_eq!(slot[slot.len().saturating_sub(2)..], ["quickPen", id], "advanced: {advanced}"); + assert_eq!(s.iter().filter(|ids| ids.contains(&id)).count(), 1, "advanced: {advanced}"); + } + assert_eq!(heading(id), "Draw"); + assert_eq!(sections().iter().flat_map(|(_, tools)| tools.iter()).filter(|t| t.id == id).count(), 1, "listed once in the drawer"); + let rows = app.run("shortcuts.list", json!({"query": id})).unwrap(); + let rows: Vec<_> = rows.as_array().unwrap().iter().filter(|r| r["id"] == format!("tool:{id}")).collect(); + assert_eq!(rows.len(), 1, "listed once in Keyboard Shortcuts"); + assert_eq!((&rows[0]["group"], &rows[0]["shortcut"]), (&json!("Tools"), &Value::Null)); + let info = vectorcraft_tools::tool_info(id).expect("catalogued"); + assert_eq!((info.label, info.shortcut), ("Smart Pen Tool", None)); + assert_eq!(crate::toolbar::tip(info), "Smart Pen Tool"); + app.run("tool.select", json!({"tool": id})).unwrap(); + assert_eq!(app.session.tool_id(), id); + let shown = slot_of(&app, id).map(|i| crate::toolbar::shown_tool(&app, &slots(&app)[i])); + assert_eq!(shown, Some(id), "the slot's button shows the tool once chosen"); + app.run("toolbar.removeTool", json!({"tool": id})).unwrap(); + assert!(slot_of(&app, id).is_none(), "it can be taken out"); + app.run("toolbar.addTool", json!({"tool": id})).unwrap(); + assert!(slot_of(&app, id).is_some(), "the drawer adds it back"); + app.run("toolbar.removeTool", json!({"tool": id})).unwrap(); + app.run("toolbar.reset", json!({})).unwrap(); + let after_reset = slot_of(&app, "pen").map(|i| slots(&app)[i].contains(&id)); + assert_eq!(after_reset, Some(true), "Reset Toolbar puts it back"); +} + +/// A toolbar edited and saved before the Smart Pen Tool joined the Pen group keeps its saved +/// layout, in both toolbars: the tool stays in the drawer until Reset Toolbar or a drag adds it, +/// and a toolbar that already had it in a slot of its own keeps it there, once. +#[test] +fn a_saved_toolbar_without_smart_pen_keeps_its_layout() { + let id = vectorcraft_tools::addons::smart_pen::ID; + let category = |slots: &[&[&str]]| ToolbarCategory { + name: Some("Draw".into()), + slots: slots.iter().map(|s| s.iter().map(|t| t.to_string()).collect()).collect(), + }; + for advanced in [false, true] { + let edits = |saved: Vec| { + if advanced { ToolbarEdits { basic: None, advanced: Some(saved) } } else { ToolbarEdits { basic: Some(saved), advanced: None } } + }; + let mut app = app(); + if advanced { + app.run("window.toolbarAdvanced", json!({})).unwrap(); + } + app.ui.toolbar_edits = edits(vec![category(&[&["pen", "addAnchor"]])]); + app.ui = std::mem::take(&mut app.ui).sanitized(); + assert_eq!(slots(&app), [["pen", "addAnchor"]], "advanced: {advanced}"); + assert!(slot_of(&app, id).is_none(), "advanced: {advanced}"); + app.run("toolbar.reset", json!({})).unwrap(); + let slot = slot_of(&app, "pen").map(|i| slots(&app)[i].clone()); + assert!(slot.is_some_and(|s| s.contains(&id)), "Reset Toolbar adds it; advanced: {advanced}"); + app.ui.toolbar_edits = edits(vec![category(&[&["pen", "addAnchor"], &[id]])]); + app.ui = std::mem::take(&mut app.ui).sanitized(); + assert_eq!(slots(&app), [vec!["pen", "addAnchor"], vec![id]], "advanced: {advanced}"); + } +} + +/// A Pen group torn off the toolbar before the Smart Pen Tool joined it gets the tool when Reset +/// Toolbar runs, and a torn-off group follows edits to its group in the toolbar. +#[test] +fn a_torn_off_group_follows_the_toolbar() { + let id = vectorcraft_tools::addons::smart_pen::ID; + let old: Vec = ["pen", "addAnchor", "deleteAnchor", "anchorPoint", "quickPen"].map(String::from).into(); + let strip = |tools: &[String]| vec![crate::state::FloatingFlyout { tools: tools.to_vec(), pos: [0.0, 0.0] }]; + let has_it = |app: &VectorcraftApp| { + let tools = &app.ui.floating_flyouts[0].tools; + tools.starts_with(&old) && tools.last().is_some_and(|t| t == id) + }; + for advanced in [false, true] { + let mut app = app(); + if advanced { + app.run("window.toolbarAdvanced", json!({})).unwrap(); + } + // Read with the preferences. + app.ui.floating_flyouts = strip(&old); + app.ui = std::mem::take(&mut app.ui).sanitized(); + assert!(has_it(&app), "advanced: {advanced}: {:?}", app.ui.floating_flyouts); + // Applied with a workspace. + let w = crate::workspaces::Workspace { floating_flyouts: strip(&old), toolbar_advanced: advanced, ..Default::default() }; + crate::workspaces::apply(&mut app.ui, &w); + assert!(has_it(&app), "advanced: {advanced}: {:?}", app.ui.floating_flyouts); + // With a toolbar edited without the tool, until Reset Toolbar. + let saved = ToolbarCategory { name: Some("Draw".into()), slots: vec![old.clone()] }; + app.ui.toolbar_edits = if advanced { + ToolbarEdits { basic: None, advanced: Some(vec![saved]) } + } else { + ToolbarEdits { basic: Some(vec![saved]), advanced: None } + }; + app.ui = std::mem::take(&mut app.ui).sanitized(); + assert_eq!(app.ui.floating_flyouts[0].tools, old, "advanced: {advanced}"); + app.run("toolbar.reset", json!({})).unwrap(); + assert!(has_it(&app), "advanced: {advanced}: {:?}", app.ui.floating_flyouts); + app.run("toolbar.removeTool", json!({"tool": "addAnchor"})).unwrap(); + let strip = &app.ui.floating_flyouts[0].tools; + assert!(!strip.iter().any(|t| t == "addAnchor") && strip.iter().any(|t| t == id), "advanced: {advanced}: {strip:?}"); + } + // A strip shows the group of the layout shown, after an edit in the other layout too. + let mut app = app(); + app.run("window.floatTools", json!({"tool": "lasso", "floating": true})).unwrap(); + let basic = app.ui.floating_flyouts[0].tools.clone(); + app.run("window.toolbarAdvanced", json!({})).unwrap(); + let advanced = slot_of(&app, "lasso").map(|i| slots(&app)[i].iter().map(|t| t.to_string()).collect::>()); + assert_eq!(Some(&app.ui.floating_flyouts[0].tools), advanced.as_ref()); + app.run("toolbar.removeTool", json!({"tool": "addAnchor"})).unwrap(); + app.run("window.toolbarAdvanced", json!({})).unwrap(); + assert_eq!(app.ui.floating_flyouts[0].tools, basic); +} + #[test] fn the_commands_add_move_remove_and_reset_tools() { let mut app = app(); @@ -846,8 +968,9 @@ fn a_saved_toolbar_without_trim_at_crossings_keeps_its_layout() { } /// The add-ons' tools are in neither toolbar as they ship (the Trim at Crossings Tool, in the -/// Scissors tool's group, and the Enclosing Lasso Tool, in the Lasso tool's group, aside): the -/// drawer lists them under their add-on's heading, and they can be added from there. +/// Scissors tool's group, the Enclosing Lasso Tool, in the Lasso tool's group, and the Smart Pen +/// Tool, in the Pen tool's group, aside): the drawer lists them under their add-on's heading, and +/// they can be added from there. #[test] fn addon_tools_are_in_the_drawer_not_the_toolbars() { let mut app = app(); @@ -866,7 +989,6 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { "slideAnchor", "sharedEdge", "tangentCircle", - "smartPen", contour, box3d, polygonal @@ -882,11 +1004,10 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { sections().iter().find(|(_, tools)| tools.iter().any(|t| t.id == id)).map(|(h, tools)| (*h, tools.iter().map(|t| t.id).collect::>())) }; assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..8].to_vec()))); - assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"]))); assert_eq!(listed(contour), Some(("Contour", vec![contour]))); assert_eq!(listed(box3d), Some(("3D Box", vec![box3d]))); assert_eq!(listed(polygonal), Some(("Polygonal Lasso", vec![polygonal]))); - for tool in ["extendPath", "smartPen", contour, box3d, polygonal] { + for tool in ["extendPath", contour, box3d, polygonal] { app.run("toolbar.addTool", json!({"tool": tool})).unwrap(); assert!(slot_of(&app, tool).is_some(), "{tool}"); } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index aa9451d3f9..20ce2933fd 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -612,7 +612,11 @@ fn run_ui_part5(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option flag(&mut app.ui.toolbar_advanced), + "window.toolbarAdvanced" => { + let on = flag(&mut app.ui.toolbar_advanced); + crate::edit_toolbar::keep_strips(&mut app.ui); + on + } "window.toolsBesideCanvas" => opt_bool(p, "on").map(|on| { let on = on.unwrap_or(!app.ui.tools_beside_canvas); app.ui.tools_beside_canvas = on; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f8bce4e088..f3c0ed772c 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1261,6 +1261,7 @@ impl UiState { sanitize_toolbar_pos(&mut self.toolbar_pos); sanitize_toolbar_pos(&mut self.control_bar_float_pos); crate::edit_toolbar::sanitize(&mut self.toolbar_edits); + crate::edit_toolbar::keep_strips(&mut self); // `read_preferences` converted the file's older layouts already; this covers a state read // any other way. What it reports lost was dropped there. let _ = crate::layout_migration::migrate_ui(&mut self); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index a4846cd35b..a3499f5040 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -49,7 +49,7 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[ &["pencil", "smooth", "pathEraser", "join"], &["eraser", "scissors", "knife", "trimAtCrossings", "mirrorCut", "lineCut", "rectCut"], &["paintbrush", "blobBrush"], - &["pen", "addAnchor", "deleteAnchor", "anchorPoint", "quickPen"], + &["pen", "addAnchor", "deleteAnchor", "anchorPoint", "quickPen", "smartPen"], &["curvature"], ], ), @@ -1100,6 +1100,10 @@ fn flyout(app: &mut VectorcraftApp, ctx: &egui::Context) { let released_on_bar = input.bar.as_ref().is_some_and(|b| ctx.input(|i| i.pointer.primary_released()) && at.is_some_and(|p| b.rect.contains(p))); let dragged_off = input.bar.as_ref().is_some_and(egui::Response::dragged) && press_travel(ctx).is_some_and(|d| d.length() > TEAR); if released_on_bar || dragged_off { + // A flyout opened before the layout changed shows the tools it was opened with; the strip + // gets the group's tools now. + let current = tools.first().filter(|_| toolbar.is_none()).and_then(|key| crate::edit_toolbar::layout_group(&app.ui, key)); + let tools = current.unwrap_or(tools); // The strip is far narrower than the flyout: it floats with its bar under the pointer. let at = at.unwrap_or(resp.response.rect.right_center()); // (Past the frame's 1 pt border.) diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 4c8c25392d..1f52fece74 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -883,7 +883,12 @@ fn loaded_floating_flyouts_keep_known_tools_one_strip_per_group() { ..Default::default() }; let ui = ui.sanitized(); - assert_eq!(ui.floating_flyouts.iter().map(|f| f.tools.join(",")).collect::>(), ["pen,addAnchor"]); + // The one strip left shows the current layout's Pen group. + let pen = BASIC.iter().flat_map(|(_, slots)| slots.iter()).find(|s| s.first() == Some(&"pen")).map(|s| s.join(",")); + assert_eq!(ui.floating_flyouts.iter().map(|f| f.tools.join(",")).collect::>(), pen.into_iter().collect::>()); + // A strip whose group isn't in the layout keeps its known tools. + let ui = crate::state::UiState { floating_flyouts: vec![f(&["curvature", "nope", "addAnchor"])], ..Default::default() }.sanitized(); + assert_eq!(ui.floating_flyouts.iter().map(|f| f.tools.join(",")).collect::>(), ["curvature,addAnchor"]); } #[test] diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index c409b6b71a..c7efa332dc 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -278,6 +278,7 @@ pub fn apply(ui: &mut UiState, w: &Workspace) { } ui.flyout = None; ui.workspace = w.name.clone(); + crate::edit_toolbar::keep_strips(ui); } /// Keep the layout of the current workspace as it is now, so switching back brings it back. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dafab93a58..427ee3dcae 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -450,7 +450,9 @@ Floating tool groups: dragging or clicking the tear-off bar down a tool group's that opened it over the bar) floats the group as a strip of tool buttons, moved by the same bar and put back in the toolbar by the × at its top; `window.floatTools {tool, floating?}` does the same for the group of the current layout holding `tool` (omitted toggles; a tool alone in its slot is an error). While a group floats, the presses -that open its flyout raise the strip instead. The strips (`ui.floating_flyouts` in `ui.inspect`: the group's tools +that open its flyout raise the strip instead. A strip shows the tools of the current layout's group that starts +with the same tool, also after `toolbar.addTool`, `toolbar.removeTool`, `toolbar.reset`, `window.toolbarAdvanced`, loading the +preferences or switching workspaces; a strip with no such group keeps its tools. The strips (`ui.floating_flyouts` in `ui.inspect`: the group's tools and the strip's top-left corner) are saved with the preferences and in user workspaces; the built-in workspaces float none. diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..b031f71214 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14975,8 +14975,8 @@ than 50000 anchors as it is. Smart Pen is a built-in add-on: one tool that draws paths and edits their points, handles and segments without switching tools. Its commands are `addon.pen.*`; in the desktop app it lives in Object › Plug-ins › Smart Pen, in its -panel (`window.panel {panel: "smartPen"}`) and in the Smart Pen Tool (`smartPen`), which the toolbars don't show until -it is added from the All Tools drawer (or chosen with `tool.select`); it has no shortcut. Each gesture and each command is +panel (`window.panel {panel: "smartPen"}`) and in the Smart Pen Tool (`smartPen`), which both shipped toolbars show in +the Pen tool's group, after the Quick Pen (`ui.tool.list` lists it there); it has no shortcut. Each gesture and each command is one undo step; an edit that changes nothing makes no step. The standard Pen tool is unchanged. The tool (`smartPen`), option `next`: `"straight"` (default) or `"curved"`, the segment a click adds: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..8cb71c0365 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2886,7 +2886,8 @@ ends), `addons::shared_edge` in `vectorcraft-tools`, `cmd::addons::pathtools::sh ## Smart Pen add-on (2026-10-30) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Smart Pen selects the -Smart Pen Tool (kept out of the shipped toolbars, listed in the All Tools drawer, no shortcut) and opens its panel. The +Smart Pen Tool (in the Pen tool's group in both shipped toolbars, after the Quick Pen, and under Draw in the All Tools +drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut) and opens its panel. The tool draws with a straight or curved next segment (a curve after a straight segment leaves it tangent), smooth drags with Alt, Shift and Space, Tab to switch a segment, a rubber band, closing, joining and continuing open ends; and edits without switching tools: point select, move, Alt-click remove keeping shape, Shift+Alt-click plain delete, double-click @@ -2895,7 +2896,10 @@ insert. The panel sets the next segment and runs Remove Points Keep Shape, Make Close or Join. Kernels: `vectorcraft_pathops::addons::pen` and the shared `addons::segment_reshape`. Tests: `addons::pen` and `addons::segment_reshape` in `vectorcraft-pathops`, `addons::smart_pen` in `vectorcraft-tools`, `cmd::addons::pen::tests` in `vectorcraft-engine` (each command one undo step, bad params refused, the tool's gestures -through the session) and `addons::pen::tests` in `vectorcraft-ui-egui` (the submenu, the panel). Commands: `docs/mcp.md` +through the session), `addons::pen::tests` in `vectorcraft-ui-egui` (the submenu, the panel), and for the toolbars +`smart_pen_is_in_the_pen_flyout` and `a_saved_toolbar_without_smart_pen_keeps_its_layout` in `edit_toolbar::tests` +in `vectorcraft-ui-egui`, `smart_pen_is_in_the_pen_group_once` in `addons::tests` in `vectorcraft-tools` and +`headless_backend_methods` in `vectorcraft-mcp`. Commands: `docs/mcp.md` › Smart Pen add-on. ## Color Effects add-on (2026-10-30) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..00e75dba5d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -549,7 +549,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › New Symbols from Layers makes a symbol of each layer's art named after the layer (the highlighted layers when two or more are, else all); Convert Layers to Symbols also replaces each layer's art with an instance in place; empty layers skipped, one undo step | done | #4927; `addon.document.symbolsFromLayers`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | -| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | +| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool (also in the Pen tool's group in both shipped toolbars, after the Quick Pen; the All Tools drawer lists it under Draw; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.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 nine tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool, Tangent Circle Tool, Trim at Crossings Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped (except Trim at Crossings, which both shipped toolbars and the drawer show in the Scissors tool's group), 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°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush, Extend Path or Tangent Circle 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 | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.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 › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | @@ -562,7 +562,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): 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 | -| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool, which the All Tools drawer lists under its own heading but neither toolbar shows as shipped (no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point); an Alt-drag away from paths selects the points inside a marquee | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | +| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool (also in the Pen tool's group in both shipped toolbars, after the Quick Pen; the All Tools drawer lists it under Draw; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point); an Alt-drag away from paths selects the points inside a marquee | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.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 three tools (Anchor Eraser Brush, Extend Path, Measure & Inspect), 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 runs Add Points at / Split at Crossings; 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` and their tests; not a feature of the reference app, so it is not scored | | Artwork Cleanup add-on (VectorCraft addition): Object › Plug-ins › Artwork Cleanup opens its panel, which checks the selection or the document for 16 kinds of issue, lists them with counts, and shows or fixes the picked rows or all of them, each fix one undo step; Simplify Anchors (Keep Shape), Rejoin Path Pieces and Deep Ungroup open their options first | done | `addon.cleanup.*`, `crates/ui-egui/src/addons/cleanup.rs` and its tests; not a feature of the reference app, so it is not scored | | Artwork Cleanup add-on text tools (VectorCraft addition): the panel's Text row, which the panel can hide, and Object › Plug-ins › Artwork Cleanup set the alignment of point type keeping its place, break type into lines (Shift-click: paragraphs), words or glyphs, split type at the cursor, reset a text transform (Alt-click: and its horizontal scale), combine point type, remove line or paragraph breaks and replace missing fonts, each one undo step | done | `addon.cleanup.*` text commands, `crates/ui-egui/src/addons/cleanup.rs` and its tests; a VectorCraft addition, so it is not scored | From c1f1b662c8fdfb4279a130d6db5594ea039a6b26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:23:20 -0800 Subject: [PATCH 049/101] Plug-ins: every filter step of a batch keeps its parameters A batch that ran several filters remembered only the last one, so the earlier filters' dialogs opened with older parameters or their defaults. Each plugin.run step of a command.batch or Action Batch is now noted in the order it ran: the last one stays the filter Apply Last Filter runs, and a filter that ran twice keeps its newer parameters. A later install, removal or reload drops a filter's parameters only when it may have changed that filter: a removal of its id, an install that reports its id (or whose result is unknown), or a reload. Installing another plug-in later in the batch keeps them. --- crates/ui-egui/src/dialogs/plugin.rs | 54 ++++++++++++++---------- crates/ui-egui/src/tests/last_filter.rs | 56 +++++++++++++++++++++++++ docs/plugins.md | 2 +- 3 files changed, 90 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 02d7ca9dd3..0cd94a4c55 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -190,34 +190,37 @@ pub(crate) fn before_command() -> u64 { } /// After command `id` with `params` ran with result `r`, the registry at revision `before` when it -/// started: a `plugin.run` that succeeded, or the last `plugin.run` step of a batch that succeeded -/// (`command.batch`, or `action.batch` on at least one file or data set), is noted as the filter -/// that ran last ([`record`]). +/// started: a `plugin.run` that succeeded, or each `plugin.run` step of a batch that succeeded +/// (`command.batch`, or `action.batch` on at least one file or data set) in the order they ran, is +/// noted ([`record`]), so the last one is the filter that ran last. pub(crate) fn after_command(app: &mut VectorcraftApp, id: &str, params: &Value, r: &Result, before: u64) { let Ok(reply) = r else { return }; // Action Batch returns success even when files or data sets fail, and runs every step on each // one that doesn't. let played = |v: &Value| v.get("count").and_then(Value::as_u64).unwrap_or(0) > v.get("failed").and_then(Value::as_u64).unwrap_or(0); - let ran = match id { - CMD => Some(params), + match id { + CMD => record(app, params), "command.batch" | "action.batch" if id == "command.batch" || played(reply) => { let steps = params.get("commands").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); - let Some(at) = steps.iter().rposition(|s| step_id(s) == Some(CMD)) else { return }; - let p = steps[at].get("params").unwrap_or(&Value::Null); - // The plug-in installed under the id now is the one that ran when no later step changed - // the plug-ins, or when it was installed before the batch (installing gives a new serial). - let changed_later = steps[at + 1..].iter().any(|s| step_id(s).is_some_and(|c| REGISTRY_CHANGES.contains(&c))); - let installed_before = p.get("id").and_then(Value::as_str).and_then(registry::get).is_some_and(|q| q.serial() <= before); - if changed_later && !installed_before { - forget(app, p); - return; + // `command.batch` returns each step's result; Action Batch returns none. + let results = reply.get("results").and_then(Value::as_array); + // Every filter step is noted in the order the steps ran, so the last one is the filter + // that ran last and a filter that ran twice keeps its newest parameters. + for (at, s) in steps.iter().enumerate().filter(|(_, s)| step_id(s) == Some(CMD)) { + let p = s.get("params").unwrap_or(&Value::Null); + let ran = p.get("id").and_then(Value::as_str).unwrap_or_default(); + // The plug-in installed under the id now is the one that ran when no later step may + // have changed it, or when it was installed before the batch (installing gives a new + // serial). + let changed_later = (at + 1..steps.len()).any(|i| may_change(&steps[i], results.and_then(|r| r.get(i)), ran)); + let installed_before = registry::get(ran).is_some_and(|q| q.serial() <= before); + match changed_later && !installed_before { + true => forget(app, p), + false => record(app, p), + } } - Some(p) } - _ => None, - }; - if let Some(p) = ran.cloned() { - record(app, &p); + _ => {} } } @@ -226,8 +229,17 @@ fn step_id(s: &Value) -> Option<&str> { s.get("command").and_then(Value::as_str) } -/// The commands that install, remove or reload plug-ins. -const REGISTRY_CHANGES: [&str; 3] = ["plugin.install", "plugin.remove", "plugin.reload"]; +/// Whether batch step `s`, which returned `result` if the batch reports it, may have installed, +/// removed or reloaded plug-in `id`: a removal names its id, an install reports the id it installed, +/// and a reload, or an install whose result is not known, may change any plug-in. +fn may_change(s: &Value, result: Option<&Value>, id: &str) -> bool { + match step_id(s) { + Some("plugin.remove") => s.get("params").and_then(|p| p.get("id")).and_then(Value::as_str) == Some(id), + Some("plugin.install") => result.and_then(|r| r.get("id")).and_then(Value::as_str).is_none_or(|i| i == id), + Some("plugin.reload") => true, + _ => false, + } +} /// Notes the filter `plugin.run` params `p` name as the one that ran last, without parameters or a /// module, so that Apply Last Filter and Last Filter… stay off until a filter runs again. diff --git a/crates/ui-egui/src/tests/last_filter.rs b/crates/ui-egui/src/tests/last_filter.rs index 20b761062f..b546771d83 100644 --- a/crates/ui-egui/src/tests/last_filter.rs +++ b/crates/ui-egui/src/tests/last_filter.rs @@ -199,6 +199,62 @@ fn only_successful_filter_runs_become_the_last_filter() { dialogs::cancel(&mut app); } +/// Every filter step of a batch counts, in the order the steps ran: the last one becomes the last +/// filter, each filter's dialog opens with the parameters it last ran with in the batch, and a +/// filter that ran twice keeps the newer ones. +#[test] +fn every_filter_step_of_a_batch_counts() { + let mut app = app(); + let (a, b) = ("test.ui.last.batch.a", "test.ui.last.batch.b"); + install(&mut app, &filter(a, "Batch A", N)); + install(&mut app, &filter(b, "Batch B", N)); + let steps = json!([ + {"command": "plugin.run", "params": {"id": a, "params": {"n": 4}}}, + {"command": "plugin.run", "params": {"id": b, "params": {"n": 2}}}, + {"command": "plugin.run", "params": {"id": a, "params": {"n": 7}}}, + {"command": "plugin.run", "params": {"id": b, "params": {"n": 6}}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!(app.last_filters.last_id(), Some(b), "the last filter step"); + for (id, n) in [(a, 7), (b, 6)] { + app.run("plugin.dialog", json!({"id": id})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("n"), Some(&json!(n)), "{id}"); + dialogs::cancel(&mut app); + } + + // Filters installed in the batch: installing another plug-in after a filter ran keeps that + // filter's parameters. + let (c, d) = ("test.ui.last.batch.c", "test.ui.last.batch.d"); + let steps = json!([ + {"command": "plugin.install", "params": {"dataBase64": vectorcraft_format::base64_encode(&filter(c, "Batch C", N)), "replace": true}}, + {"command": "plugin.run", "params": {"id": c, "params": {"n": 7}}}, + {"command": "plugin.install", "params": {"dataBase64": vectorcraft_format::base64_encode(&filter(d, "Batch D", N)), "replace": true}}, + {"command": "plugin.run", "params": {"id": d, "params": {"n": 2}}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!(app.last_filters.last_id(), Some(d), "the last filter step"); + for (id, n) in [(c, 7), (d, 2)] { + app.run("plugin.dialog", json!({"id": id})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("n"), Some(&json!(n)), "{id}"); + dialogs::cancel(&mut app); + } + + // The same over an Action Batch, with the filters in the other order. + app.run("dataset.new", json!({"name": "a"})).unwrap(); + let steps = json!([ + {"command": "plugin.run", "params": {"id": b, "params": {"n": 1}}}, + {"command": "plugin.run", "params": {"id": a, "params": {"n": 9}}}, + ]); + let r = app.run("action.batch", json!({"source": "datasets", "commands": steps})).unwrap(); + assert_eq!((r["count"].clone(), r["failed"].clone()), (json!(1), json!(0)), "{r}"); + assert_eq!(app.last_filters.last_id(), Some(a), "the last Action Batch filter step"); + for (id, n) in [(a, 9), (b, 1)] { + app.run("plugin.dialog", json!({"id": id})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get("n"), Some(&json!(n)), "{id}"); + dialogs::cancel(&mut app); + } +} + /// Installing the plug-in again, even the same module, another module with its id, one whose /// manifest no longer takes the parameters, and removing it turn both items off, and the new /// module's dialog opens with its own defaults. Installing another plug-in keeps them. diff --git a/docs/plugins.md b/docs/plugins.md index fe3e2a4161..7a881396f0 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -64,7 +64,7 @@ the filter that last ran again with the same parameters on the selection, withou **Last Filter…** (`plugin.lastFilter`), which opens that filter's dialog with those parameters, its OK running it as a new run. Once a filter has run they read **Apply** followed by the filter's name and the filter's name with an ellipsis. A run counts once it succeeds: from its menu item, its dialog's OK, a shortcut, `plugin.run` or a -`command.batch` step (the last such step of the batch), an Action Batch (`action.batch`) step once a file or data set +`command.batch` step (each such step in the order the batch ran them, so the last one runs again), an Action Batch (`action.batch`) step once a file or data set ran it, and a background run once its result is applied. A preview, Cancel, a failed or canceled run, a plug-in's own commands and live effects don't count, and neither does a batch step whose filter the batch installed when a later step of the batch installs, removes or From 63143460ebf0c1392f686f20516e31ef92035c83 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:26:07 -0800 Subject: [PATCH 050/101] Pathfinder: effects journal every option they use, and Outline follows Precision - effect.apply with some Pathfinder Options in params journals all three options the effect used. The journal entry used to keep only the ones given, so a replay took the others from the preferences at that time. The journal now merges an object a command resolved with the object the call gave, key by key. - A Pathfinder effect's stored precision that is not a number (true, false, "1abc") evaluates and scales as the 0.01 pt default. It used to read true as 1 pt, false as the 0.001 pt bound and "1abc" as 1 pt. Commands still refuse such a value with an error. - Outline, the panel operation and the effect, applies Precision. Its tolerance for crossings that count as one point, and for coincident edges, is multiplied by precision / 0.01, so the default leaves the output unchanged. - Pathfinder Options' precision range is the Pathfinder effects' range constant rather than a copy of it. Docs: params text, docs/mcp.md, docs/target-app-parity.md. --- crates/effects/src/group.rs | 15 +++++++++++---- crates/effects/src/params.rs | 9 ++++++--- crates/effects/src/tests.rs | 20 ++++++++++++++++++++ crates/engine/src/cmd/pathops.rs | 6 +++--- crates/engine/src/session/execute.rs | 12 +++++++++++- crates/engine/src/tests/pathops.rs | 25 +++++++++++++++++++++++++ crates/pathops/src/pathfinder.rs | 11 +++++++---- crates/pathops/tests/it/ops.rs | 17 +++++++++++++++++ docs/mcp.md | 10 +++++++--- docs/target-app-parity.md | 2 +- 10 files changed, 108 insertions(+), 19 deletions(-) diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 55e3ad6fe3..bebf0e46be 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -66,7 +66,7 @@ pub const PATHFINDER_EFFECT_PRECISION: std::ops::RangeInclusive = 0.001..=1 /// The documentation of [`PATHFINDER_OPTION_KEYS`], as a literal for `concat!`. macro_rules! options_doc { () => { - "precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing; results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)" + "precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing, and a stored value that is not a number evaluates as 0.01; results are refit to within it and pieces thinner than it are dropped; Outline treats crossings closer together than a tolerance multiplied by precision / 0.01 as one point), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)" }; } @@ -102,14 +102,21 @@ impl Default for PathfinderEffectOptions { } } +/// The `precision` stored in a Pathfinder effect's parameters `p`, out of range or not, when it is a +/// JSON number. A value of another type (`true`, `"1 pt"`) is not a precision. +pub(crate) fn stored_precision(p: &Value) -> Option { + p.get("precision").and_then(Value::as_f64).filter(|v| v.is_finite()) +} + impl PathfinderEffectOptions { - /// The options in `p`: a missing or non-numeric value takes its default and a precision out of - /// range its nearest bound, so a live effect always evaluates. + /// The options in `p`: a missing value, or one of the wrong type (a precision that is not a + /// number), takes its default, and a precision out of range its nearest bound, so a live effect + /// always evaluates. pub fn from_params(p: &Value) -> Self { let d = PathfinderEffectOptions::default(); let (lo, hi) = (*PATHFINDER_EFFECT_PRECISION.start(), *PATHFINDER_EFFECT_PRECISION.end()); PathfinderEffectOptions { - precision: crate::util::num(p, "precision", d.precision).clamp(lo, hi), + precision: stored_precision(p).unwrap_or(d.precision).clamp(lo, hi), remove_redundant_points: crate::util::flag(p, "removeRedundantPoints", d.remove_redundant_points), remove_unpainted: crate::util::flag(p, "removeUnpainted", d.remove_unpainted), } diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index ab588838a6..fed9df7811 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -131,9 +131,12 @@ pub fn scale_effect(e: &mut Effect, s: f64) { let mut keys: Vec<&str> = info.lengths.keys(relative).collect(); keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some())); for k in keys { - let missing = - if k == "precision" && crate::takes_pathfinder_options(&e.id) { crate::PathfinderEffectOptions::default().precision } else { f64::NAN }; - let v = util::num(&merged, k, missing); + // A Pathfinder effect's precision that is not a number scales the precision it evaluates with. + let v = if k == "precision" && crate::takes_pathfinder_options(&e.id) { + crate::group::stored_precision(&merged).unwrap_or(crate::PathfinderEffectOptions::default().precision) + } else { + util::num(&merged, k, f64::NAN) + }; if v.is_finite() { if !e.params.is_object() { e.params = Value::Object(Map::new()); diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 348d21ba38..54636ce6ef 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -2177,3 +2177,23 @@ fn a_pathfinder_effects_precision_is_a_distance_that_scales_with_the_object() { assert_eq!(e.params["precision"].as_f64(), Some(8.0), "{id}"); } } + +#[test] +fn a_pathfinder_effects_stored_precision_that_is_not_a_number_is_the_default() { + let d = PathfinderEffectOptions::default().precision; + for v in [json!(true), json!(false), json!("1abc"), json!("5 pt"), json!(null), json!([2.0])] { + assert_eq!(PathfinderEffectOptions::from_params(&json!({ "precision": v })).precision, d, "{v}"); + } + // A number out of range takes its nearest bound. + assert_eq!(PathfinderEffectOptions::from_params(&json!({"precision": 50.0})).precision, *PATHFINDER_EFFECT_PRECISION.end()); + assert_eq!(PathfinderEffectOptions::from_params(&json!({"precision": 0})).precision, *PATHFINDER_EFFECT_PRECISION.start()); + // Scale Strokes & Effects scales the precision such an effect evaluates with. + for (id, _, _) in PATHFINDER_EFFECTS { + for v in [json!(true), json!("1abc")] { + let mut e = crate::new_effect(id, &json!({ "precision": v })).unwrap(); + crate::scale_effect(&mut e, 3.0); + let scaled = e.params["precision"].as_f64().unwrap_or(f64::NAN); + assert!((scaled - d * 3.0).abs() < 1e-12, "{id} {v}: {scaled}"); + } + } +} diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 1793f17d5c..9c1b31ce1d 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Pathfinder Options…", ["Window", "Pathfinder"], None, - "{precision?: pt 0.001..10 (0.01; how closely the Pathfinder operations follow the paths: results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (false; the results lose the anchors that don't change their shape), removeUnpainted?: bool (false; Divide and Outline leave out the pieces of objects with no fill)} Pathfinder Options, kept in the preferences and used by every later Shape Mode and Pathfinder operation (not Trap); {} reads them → the options", + "{precision?: pt 0.001..10 (0.01; how closely the Pathfinder operations follow the paths: results are refit to within it and pieces thinner than it are dropped; Outline treats crossings closer together than a tolerance multiplied by precision / 0.01 as one point), removeRedundantPoints?: bool (false; the results lose the anchors that don't change their shape), removeUnpainted?: bool (false; Divide and Outline leave out the pieces of objects with no fill)} Pathfinder Options, kept in the preferences and used by every later Shape Mode and Pathfinder operation (not Trap); {} reads them → the options", always, pathfinder_options ), @@ -610,8 +610,8 @@ impl Default for PathfinderOptions { } } -/// The range of Pathfinder Options › Precision (pt). -pub const PATHFINDER_PRECISION_RANGE: std::ops::RangeInclusive = 0.001..=10.0; +/// The range of Pathfinder Options › Precision (pt), which a Pathfinder effect's `precision` shares. +pub const PATHFINDER_PRECISION_RANGE: std::ops::RangeInclusive = vectorcraft_render::effects::PATHFINDER_EFFECT_PRECISION; impl PathfinderOptions { /// These options with those `p` names (`precision` in pt or a string with a unit), or why `p` diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..b372f1f3e2 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -359,9 +359,19 @@ 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. An object noted for an object the params + // give (`effect.apply`'s `params`) is merged by the same rule, so the keys the command + // filled in stay. Value::Object(m) if !note.is_empty() => { for (k, v) in m { + if let (Some(Value::Object(resolved)), Value::Object(given)) = (note.get_mut(k), v) { + for (gk, gv) in given { + if !gv.is_null() || !resolved.contains_key(gk) { + resolved.insert(gk.clone(), gv.clone()); + } + } + continue; + } if !v.is_null() || !note.contains_key(k) { note.insert(k.clone(), v.clone()); } diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 60f223334c..6911059b0a 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1955,6 +1955,31 @@ fn a_pathfinder_effect_keeps_the_options_in_force_when_applied() { assert_eq!(mix, &json!({"mixingRate": 50.0, "precision": 0.5, "removeRedundantPoints": true, "removeUnpainted": true})); } +/// A Pathfinder effect given some of its options in `params` journals every option it used, so +/// replaying the journal with other preferences gives the same effect and art. +#[test] +fn a_pathfinder_effect_given_some_options_journals_every_option_it_used() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 99.5, "width": 100, "height": 50})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.prefs.pathfinder = PathfinderOptions { precision: 1.0, remove_redundant_points: true, remove_unpainted: true }; + s.execute("effect.apply", &json!({"effect": "pathfinder.divide", "params": {"precision": 0.25}})).unwrap(); + let all = json!({"precision": 0.25, "removeRedundantPoints": true, "removeUnpainted": true}); + assert_eq!(first_effect_params(&s), all); + let (id, p) = s.journal.last().unwrap().clone(); + assert_eq!((id.as_str(), &p["params"]), ("effect.apply", &all), "the journal entry gives every option the effect used"); + let mut replay = Session::new(); + for (id, p) in &s.journal { + replay.execute(id, p).unwrap(); + } + assert_eq!(replay.prefs.pathfinder, PathfinderOptions::default()); + let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap(); + assert_eq!(doc(&replay), doc(&s)); +} + /// A live Pathfinder effect evaluates with its own options as the panel's operations do with /// Pathfinder Options: a precision of 1 pt drops a 0.5 pt overlap, Divide leaves out an unfilled /// object's pieces, and Remove Redundant Points drops an anchor that shapes nothing. diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index af7bf90231..6f99a3d917 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -226,7 +226,7 @@ pub fn pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Ve ); subpaths.into_iter().zip(shapes).filter(|(sp, _)| !sp.is_empty()).flat_map(|(sp, s)| one(PathData::new(sp), s.key)).collect() } - PathfinderOp::Outline => outline_edges(&arr, shapes), + PathfinderOp::Outline => outline_edges(&arr, shapes, precision), PathfinderOp::HardMix | PathfinderOp::SoftMix => regions_of(&arr) .into_iter() .filter_map(|r| { @@ -971,13 +971,16 @@ fn along(a: &[PathSeg], b: &[PathSeg], tol: f64) -> bool { covers(a, b) && covers(b, a) } -/// Pathfinder Outline: split every shape's boundary at junctions of the arrangement. -fn outline_edges(arr: &Arrangement, shapes: &[Shape]) -> Vec { +/// Pathfinder Outline: split every shape's boundary at junctions of the arrangement. Junctions +/// closer together than `reach` are one, and coincident edges within ten times it are one edge. +/// `reach` is its value at [`DEFAULT_PRECISION`] times `precision / DEFAULT_PRECISION`, a factor kept +/// within 0.1 to 1000 (Pathfinder Options › Precision's range of 0.001 to 10 pt). +fn outline_edges(arr: &Arrangement, shapes: &[Shape], precision: f64) -> Vec { // Sorted by x (then y), so a segment needs only the junctions inside its control box. let junctions = arr.junctions(); let scale = shapes.iter().filter_map(|s| s.path.control_bounds()).map(|r| r.width().max(r.height())).fold(1.0, f64::max); let tol = scale * 1e-7; - let reach = tol.max(1e-6); + let reach = tol.max(1e-6) * (precision / DEFAULT_PRECISION).clamp(0.1, 1000.0); // (chain, key, source index) let mut chains: Vec<(Vec, u64)> = Vec::new(); for s in shapes { diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index 60410a0d5d..9780f71420 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -237,6 +237,23 @@ fn pf_outline_dedups_shared_edges() { assert!(close(len, 70.0, 1e-9), "len {len}"); } +/// Outline follows Precision: two bars whose left edges cross a square's top edge 0.00005 pt apart +/// leave a piece of that length between the crossings at the default precision, and none at 10 pt, +/// where the two crossings are one junction. +#[test] +fn pf_outline_joins_junctions_closer_than_the_precision() { + let s = vec![shape(rect(0.0, 0.0, 100.0, 100.0), 1), shape(rect(50.0, 90.0, 10.0, 20.0), 2), shape(rect(50.00005, 95.0, 4.99995, 10.0), 3)]; + let shortest = |r: &[Shape]| r.iter().map(|s| s.path.length()).fold(f64::INFINITY, f64::min); + let length = |r: &[Shape]| r.iter().map(|s| s.path.length()).sum::(); + let at_default = pathfinder_with(PathfinderOp::Outline, &s, DEFAULT_PRECISION); + assert_eq!(at_default, pathfinder(PathfinderOp::Outline, &s)); + assert!(shortest(&at_default) < 1e-4, "{at_default:?}"); + let coarse = pathfinder_with(PathfinderOp::Outline, &s, 10.0); + assert!(shortest(&coarse) > 1e-3, "{coarse:?}"); + assert!(coarse.len() < at_default.len(), "{} pieces at 10 pt, {} at the default", coarse.len(), at_default.len()); + assert!(close(length(&coarse), length(&at_default), 1e-6), "{} against {}", length(&coarse), length(&at_default)); +} + #[test] fn regions_and_region_at() { let s = stack(); diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..675792cd6e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6256,7 +6256,9 @@ Pathfinder Options: `object.pathfinder.options {precision?, removeRedundantPoint `prefs.get`/`prefs.set` with key `pathfinder`) reads and sets the options every later Shape Mode and Pathfinder operation uses: `precision` (0.001–10 pt, default 0.01; a string with a unit or a string that is all one number also reads, and any other string, such as `"1abc"`, is an error) is how closely results follow -the paths (they are refit to within it and pieces thinner than it are dropped), `removeRedundantPoints` takes the +the paths (they are refit to within it and pieces thinner than it are dropped; Outline treats crossings closer together +than a small tolerance as one point and edges that lie within ten times it as one edge, and that tolerance is multiplied by +`precision / 0.01`, so 0.01 keeps it as it was and 10 makes it 1,000 times larger), `removeRedundantPoints` takes the anchors that don't change a result's shape off it, and `removeUnpainted` makes Divide and Outline leave out the pieces of objects with no fill (or only hidden fills). Both default to false; `{}` reads the options. Each Shape Mode and Pathfinder command (`object.pathfinder.unite` … `minusBack`) also takes `precision`, `removeRedundantPoints` and @@ -6276,8 +6278,10 @@ mean what they mean for the panel's operations; the other operations ignore `rem on, a compound shape's area counts as filled when the shape has a visible fill of its own, and Divide keeps every piece when the group or compound shape has one. Outline strokes a compound shape's area in the shape's own fill, and gives the edges no paint when the shape has no fill (the shape's own strokes still draw over the result). `effect.apply` -fills the ones `params` leave out from the current Pathfinder Options, and the values join its journal entry. An effect -saved without them evaluates with precision 0.01 and both switches off, as before effects kept them. `effect.setParams +fills the ones `params` leave out from the current Pathfinder Options, and all three values join its journal entry, +those `params` gave and those filled in, so a replay gives the same effect whatever the options are then. An effect +saved without them evaluates with precision 0.01 and both switches off, as before effects kept them. A stored +`precision` that is not a number (`true`, or a string such as `"1abc"`) evaluates and scales as 0.01. `effect.setParams {index, params: {precision?, removeRedundantPoints?, removeUnpainted?}}` edits them as one undo step; values the effect already evaluates with record no undo step and return `{ids: []}`. A precision out of range, or a switch that isn't true or false, is refused with an error and nothing changes. Scale Strokes & Effects scales `precision` with the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..11cbdf74ef 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1707,7 +1707,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Revolve takes type, as its glyph outlines, and groups or layers, whose members sweep about one axis as [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html) describes; a surface can have up to 16,384 profile points, and curves take fewer samples when a surface would pass 163,840 faces (#3617). - Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters). Zig Zag spaces its ridges evenly along each segment, so lines and curves get a regular wave in Corner and Smooth (#1558). Warp › Arc (the effect and Envelope › Make with Warp) bends in the object's real proportions: a circular arc with concentric edges and no fold-over at 100%, so Arc on art that isn't square draws differently from before (#1581, fixes #1578). `effect.apply` and `effect.setParams` give an error for a misspelt or wrongly typed effect parameter instead of running the effect with its default (#1623, #1592). Roughen with Smooth keeps turn-backs smooth instead of making cusps that draw as spikes (#1646, #1643). Scribble draws one zig-zag per region, with no lines across holes and notches; convex shapes are unchanged (#1651, #1648). On the canvas, in Expand Appearance and in exports, Effect → Pathfinder uses the glyph outlines of type in the group, and results painted like the type keep its opacity and blend mode. - Cmd/Ctrl+4 (`pathfinder.repeat`) repeats the last successful Pathfinder panel operation, direct `object.pathfinder.*` command or `command.batch` step (including Actions playback) on the current selection; the panel menu names it. `action.batch`, Trap, compound-shape edits and live effects do not set history. Public references: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html). - - Pathfinder Options ([Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the panel menu's Pathfinder Options… sets Precision (0.001–10 pt: results refit to within it, thinner pieces dropped), Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork (`object.pathfinder.options`, kept in the preferences) for every Shape Mode and Pathfinder operation; the defaults keep the earlier output (`pathops` `precision_drops_pieces_thinner_than_it`, engine `tests_pathops` Pathfinder Options tests, `panels::pathfinder` dialog test). + - Pathfinder Options ([Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the panel menu's Pathfinder Options… sets Precision (0.001–10 pt: results refit to within it, thinner pieces dropped; Outline treats crossings closer together than a tolerance scaled by it as one point, by VectorCraft's own rule, `pf_outline_joins_junctions_closer_than_the_precision`), Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork (`object.pathfinder.options`, kept in the preferences) for every Shape Mode and Pathfinder operation; the defaults keep the earlier output (`pathops` `precision_drops_pieces_thinner_than_it`, engine `tests_pathops` Pathfinder Options tests, `panels::pathfinder` dialog test). - Pathfinder on clip groups (#8093): a clip group's members take part in the Shape Modes and Pathfinder buttons (`object.pathfinder.*`) only where its clipping path shows them, so Divide cuts the visible art along the mask and the hidden art goes; nested clip groups cut by each mask, a member the mask hides gives no piece, a cutting line's hidden part cuts nothing, a selected object the masks hide altogether counts as an empty shape where that changes the result (Intersect, Minus Front, Minus Back, Crop), and the clipping path adds no piece of its own (the public documentation doesn't say what Pathfinder does with masked art; our choice, asked on the issue). A cutting line is clipped by sampling, so a part of the mask much narrower than the mask itself can be missed. Make Compound Shape, Trap and the Pathfinder effects still take the members whole. Tests: `crates/engine/src/tests/pathfinder_clip.rs`. - Pathfinder › Trap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html), [Pathfinder panel](https://helpx.adobe.com/illustrator/using/pathfinder-panel-overview.html)): the Pathfinder panel menu's Trap… (`object.pathfinder.trap`) and Effect › Pathfinder › Trap… (`pathfinder.trap`, live on groups) add, where two objects' visible areas of different solid colours meet, a strip of the darker one's area along the edge, filled with the lighter colour at the Tint Reduction percentage and set to overprint (Reverse Traps: the darker colour spreads instead, but not a rich black); Thickness 0.01–5000 pt across vertical edges, Height/Width scales it across horizontal ones, Traps with Process Color paints a swatch colour's trap with its CMYK equivalent; the effect also has Precision and Remove Redundant Points. The panel's Trap is one undo step and groups the traps above the topmost selected object, selected; with no adjoining edges of different colours it says so and changes nothing. Tests: `crates/pathops/src/trap.rs`, `crates/effects/src/trap.rs`, `group::tests::trap_effect_adds_an_overprinting_strip_above_the_members`, `crates/engine/src/tests/trap.rs`, `panels::pathfinder::tests::trap_opens_its_options_and_ok_traps_the_selection`. - Compound shapes ([Create compound shapes with Pathfinder](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html), [Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the Pathfinder panel menu's Make Compound Shape (every member in Add) and Alt-clicking a Shape Mode (every member in that mode) make the two or more selected paths, compound paths, groups, compound shapes or type a live compound shape (`object.compoundShape.make`): a group whose members each keep a shape mode and stay editable, drawn, printed and exported (SVG, PDF and the rest through the baked document) as the area the modes make from the backmost member up, open paths closed, painted with its own appearance, taken from the topmost member not subtracting. With members selected (Direct Selection, Layers panel, isolation mode) a Shape Mode button sets theirs (`object.compoundShape.setMode`) and is lit for the mode they share; with members in different modes selected, each of the four Shape Mode buttons carries a question mark and screen readers report it as mixed, and a click gives every selected member that mode in one undo step ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=368)); paint given to a member goes to the compound shape. Release Compound Shape gives the members back as they were (`object.compoundShape.release`); Expand Compound Shape and the panel's Expand button turn it into the path or compound path of its area (`object.compoundShape.expand`). Shape Modes and Pathfinders take a compound shape as its area. Saved files keep it (`compound_shape`, `shape_mode`; an unknown mode reads as Add). Blends, envelopes and objects with a warp or another geometry effect are members as they draw (a blend's steps, an envelope's distorted art, the warped outline), and the area follows an edit of the blend, envelope or warp; Release gives them back as they were. Tests: `crates/engine/src/tests/compound_shape.rs`, `group::tests::compound_shapes_draw_the_area_their_shape_modes_make`, `group::tests::nested_compound_shapes_take_part_as_their_area`, `panels::pathfinder::tests::compound_shape_items_follow_the_selection`, `panels::pathfinder::tests::shape_modes_show_a_question_mark_while_the_selected_members_modes_differ`, `panels::pathfinder::tests::members_of_two_compound_shapes_are_compared_together`, `panels::pathfinder::tests::shape_modes_show_no_question_mark_without_mixed_members`, the `CompoundShape` op of the property-test strategies. Not yet: hit-testing by the area (a click hits the members). From 7bd49975d0af59b2b670e36ba16a0065b338ae0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:47:19 -0800 Subject: [PATCH 051/101] Display Print Size: a zoom set as a percentage keeps it at the first reading A floating window whose view was given a zoom with View > Zoom (or view.setZoom) and whose recorded fit matched that zoom counted the zoom as a fit at its display's first reading, so the percentage changed with the display's density. Only a view whose zoom is still the zoom a fit gave it now counts from the reading without a change of zoom. --- crates/ui-egui/src/doc_windows.rs | 5 ++++- crates/ui-egui/src/doc_windows/tests.rs | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 058132f839..2eb8c0e5bb 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -649,7 +649,10 @@ fn take_window_ppi(app: &mut VectorcraftApp, ctx: &egui::Context, ((uid, number) x.was_read |= matches!(shown.ppi, Some(crate::ScreenPpi::Read(_))); let size = shown.body.map(|b| b.size()); let following = view(app, win).is_some_and(|v| v.fitted && shown.fit.is_some_and(|(s, z, c)| Some(s) == size && z == v.zoom && c == v.center)); - app.settle_window_ppi(win, !(following && (first || fitted_now))); + // A zoom set as a percentage (View › Zoom, Actual Size) is not a fit, and the first reading + // keeps its percentage. + let fit = following && view(app, win).is_some_and(|v| v.fit_zoom == Some(v.zoom)); + app.settle_window_ppi(win, !(fit && (first || fitted_now))); // A view that still fits its window keeps fitting it at the zoom the new density gave it. if following && let (Some((s, _, _)), Some(v)) = (shown.fit, view(app, win)) { shown.fit = Some((s, v.zoom, v.center)); diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index fb803249e1..8043b1002f 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -1355,6 +1355,30 @@ fn a_fit_made_while_a_floating_window_is_unread_counts_from_its_last_reading() { assert_eq!(app.print_ppi_of(Some(win)), Some(110.0)); } +/// A zoom set as a percentage on a floating OS window that has not been read yet is not a fit, +/// even when the window recorded that zoom and center as its fit: the first reading of its display +/// keeps the percentage. +#[test] +fn a_zoom_set_before_a_floating_window_is_first_read_keeps_its_percentage() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + app.set_screen_ppi(Some(127.0)); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + let uid = app.session.documents()[1].uid; + let win = (1, 1); + app.run("view.setZoom", json!({"zoom": 100})).unwrap(); + let (zoom, center) = (app.views[1].zoom, app.views[1].center); + let body = egui::Rect::from_min_size(Pos2::ZERO, vec2(500.0, 400.0)); + let mut shown = + Shown { ppi: Some(crate::ScreenPpi::Read(Some(91.0))), body: Some(body), fit: Some((body.size(), zoom, center)), ..Default::default() }; + take_window_ppi(&mut app, &ctx, ((uid, 1), true), win, &mut shown); + let pct = crate::state::zoom_display_percent(app.views[1].zoom, app.print_ppi_of(Some(win))); + assert!((pct - 100.0).abs() < 1e-9, "the first reading keeps 100%: {pct}"); + assert!((app.views[1].zoom * 72.0 - 91.0).abs() < 1e-9, "an inch of the document fills an inch of its display"); +} + /// A floating OS window whose view still fits it, moved between two displays read before, keeps /// fitting it at the zoom the new density gives: the fit this frame keeps is the settled one. #[test] From e6cf6a7dbbe918a6fdec17169a467fdb92a6221a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:51:08 -0800 Subject: [PATCH 052/101] Docs: a batch forgets its filter only when it changes that same plug-in docs/plugins.md said a batch step does not count when a later step installs, removes or reloads any plug-in. The step is dropped only when a later step installs or removes that same plug-in, or reloads plug-ins; installing or removing another plug-in keeps it. --- docs/plugins.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins.md b/docs/plugins.md index 7a881396f0..010c7e8f55 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -67,8 +67,8 @@ ellipsis. A run counts once it succeeds: from its menu item, its dialog's OK, a `command.batch` step (each such step in the order the batch ran them, so the last one runs again), an Action Batch (`action.batch`) step once a file or data set ran it, and a background run once its result is applied. A preview, Cancel, a failed or canceled run, a plug-in's own commands and live effects don't count, -and neither does a batch step whose filter the batch installed when a later step of the batch installs, removes or -reloads plug-ins. Both items are grayed out with no document open, before any filter ran, and once the filter that +and neither does a batch step whose filter the batch installed when a later step of the batch installs or removes +that same plug-in, or reloads plug-ins. Both items are grayed out with no document open, before any filter ran, and once the filter that ran last was removed, installed again (the same module too) or no longer takes those parameters as they are; installing another plug-in keeps them. They don't need a selection: a filter given no objects can still add new ones. The parameters are kept for the session only, for at most 64 filters. Where the two items sit, when they are grayed out and how long the From da5344af2c5559ce6499e1d3163f3034ac9ba10c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:14:02 -0800 Subject: [PATCH 053/101] Recolor with Preset: test that grays of different lightness get different tints The 1 Color Job test now requires a strictly higher tint on the darker of two grays for a linked ink, and different colors for a process swatch, so a flat tint fails it. docs/ui-parity.md gets a Recolor with Preset item and the M3 row in docs/roadmap.md names the preset flow. --- crates/ui-egui/src/tests/recolor.rs | 14 +++++++++----- docs/roadmap.md | 2 +- docs/ui-parity.md | 2 ++ 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index d55b9f1882..9a96a274c3 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -2157,14 +2157,18 @@ fn a_one_color_job_limited_to_document_swatches_links_gray_art_to_the_ink() { for (i, c) in before.iter().enumerate().filter(|(i, _)| !grays.contains(i)) { assert_eq!(after[i].0, c.0, "{kind}: black and white are kept"); } - if linked { - for &a in &grays { - for &b in &grays { - if gray(&before[a].0) < gray(&before[b].0) { - assert!(after[a].2 >= after[b].2, "{kind}: a darker gray takes more ink: {:?} {:?}", after[a], after[b]); + for &a in &grays { + for &b in &grays { + if gray(&before[a].0) < gray(&before[b].0) { + if linked { + assert!(after[a].2 > after[b].2, "{kind}: a darker gray takes more ink: {:?} {:?}", after[a], after[b]); + } else { + assert_ne!(after[a].0, after[b].0, "{kind}: grays of different lightness get different colors: {a} {b}"); } } } + } + if linked { app.run("swatch.edit", json!({"name": "Ink", "color": "cmyk 100 0 0 0"})).unwrap(); let edited = art_paints(&app); for &i in &grays { diff --git a/docs/roadmap.md b/docs/roadmap.md index 27c4f78e25..9f90f7fcd2 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -184,7 +184,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655) | 12–18 | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | +| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); 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 | 3–6 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..c653497fd9 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -580,6 +580,8 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po - [x] Recolor Artwork › Assign: double-click a row's new color to pick it in the Color Picker, in the model it was picked in, with native Lab entry, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#8031, follow-up to #4090/#5113 for #4028). Evidence: `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise numeric entry and actual menu clicks. +- [x] Edit › Edit Colors › Recolor with Preset: the 1, 2 and 3 Color Job and Color Library presets first open a Recolor with Preset dialog whose Limit to Library menu (None, Document Swatches or a library) is applied when Recolor Artwork opens; Cancel opens nothing. A 1 Color Job limited to the document's swatches with a spot or global ink picked turns gray art into tints of that ink linked to its swatch. Evidence: `recolor_with_preset_asks_for_a_library_first` and `a_one_color_job_limited_to_document_swatches_links_gray_art_to_the_ink`. + - [x] Recolor Artwork › Color Theme Picker: with the button beside the tabs on, a click on the canvas takes the color palette of an object or image, a drag takes the palette of the art inside its marquee, and Shift adds more picks; the rows that aren't excluded take the palette as their new colors and the art previews them ([Recolor artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-artwork.html)). The number and order of the picked colors are VectorCraft's own rule (`recolor.pickTheme`). Tests: `theme_picks_give_the_rows_the_palette_of_the_art_picked` and `the_theme_picker_takes_clicks_and_shift_drags_on_the_canvas` in `crates/ui-egui/src/dialogs/recolor.rs`, `theme_picker_*` in `crates/engine/src/tests/recolor.rs`. - [x] Recolor Artwork › Prominent Colors: with art, a bar under the Edit tab's wheel shows the new colors, each as wide as its share of the art; dragging the edge between two parts raises one color's weight and lowers the other's, and the art previews the result; the New Color Group menu has Save All Colors and Save Prominent Colors ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html)). How a share is measured and how a weight moves colors between rows are VectorCraft's own rules (`recolor.weigh`). Tests: `weights_move_the_rows_colors_and_the_art_previews_them`, `dragging_a_prominent_edge_moves_colors_between_rows` and `save_all_and_prominent_colors_make_color_groups` in `crates/ui-egui/src/dialogs/recolor.rs`, `weigh_*` in `crates/engine/src/tests/recolor.rs`. From 1de14d2bdd8e968ad9185e3bffe9aecbb1f3f02b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:23:44 -0800 Subject: [PATCH 054/101] Display Print Size: a floating window keeps its settled fit while a modal is open A floating OS window whose view fits it and whose display changed density while a dialog or other modal was open settled its zoom, but the window kept the fit from before the change, so the next resize did not fit the view again. The window now keeps the settled zoom and center as its fit while a modal blocks it too. --- crates/ui-egui/src/doc_windows.rs | 13 +++++++++-- crates/ui-egui/src/doc_windows/tests.rs | 30 +++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 2eb8c0e5bb..9af012b6ee 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -525,7 +525,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(win) = find(app, (w.uid, w.view)) else { continue }; let raised = raise == Some((w.uid, w.view)); let mut shown = if native { os_window(app, ctx, &w, (win, blocked), raised) } else { app_window(app, ctx, &w, (win, blocked), raised) }; - take_window_ppi(app, ctx, ((w.uid, w.view), native), win, &mut shown); + take_window_fit(app, ctx, ((w.uid, w.view), native), win, &mut shown); if blocked { continue; } @@ -537,7 +537,6 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } x.focused = shown.focused; x.body = shown.body; - x.fit = shown.fit; } over_strip |= shown.over_strip; if shown.close { @@ -613,6 +612,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (win, blocked): (Win, bool) (pressed, rect, fit) } +/// Takes the density of the display that `shown`, floating window `key`'s window `win`, was found on +/// ([`take_window_ppi`]), and keeps the fit `shown` holds after it as the window's fit, also while a +/// modal blocks the window. +fn take_window_fit(app: &mut VectorcraftApp, ctx: &egui::Context, ((uid, number), os): ((u64, u32), bool), win: Win, shown: &mut Shown) { + take_window_ppi(app, ctx, ((uid, number), os), win, shown); + if let Some(x) = app.ui.floating.iter_mut().find(|x| x.uid == uid && x.view == number) { + x.fit = shown.fit; + } +} + /// Takes the density of the display that `shown`, floating window `key`'s ([`views::key`]) window /// `win`, was found on, and whether it is an OS window of its own (`os`), and settles the views /// when the density changed ([`VectorcraftApp::settle_window_ppi`]). A view that still has the diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 8043b1002f..977f061f42 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -1405,3 +1405,33 @@ fn a_fitted_floating_window_moved_to_another_density_keeps_fitting() { assert_ne!(v.zoom, zoom, "the move to a denser display keeps the zoom percentage"); assert_eq!(moved.fit, Some((body.size(), v.zoom, v.center)), "and the fit kept is the settled zoom"); } + +/// A floating OS window whose view fits it, moved to a display of another density while a modal is +/// open, keeps the settled zoom and center as its fit, so the next resize fits it again. +#[test] +fn a_fitted_floating_window_moved_while_a_modal_is_open_keeps_the_settled_fit() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + app.set_screen_ppi(Some(127.0)); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + let uid = app.session.documents()[1].uid; + let win = (1, 1); + take_window_fit(&mut app, &ctx, ((uid, 1), true), win, &mut Shown { ppi: Some(crate::ScreenPpi::Read(Some(91.0))), ..Default::default() }); + app.run("view.fitArtboard", json!({})).unwrap(); + let (zoom, center) = (app.views[1].zoom, app.views[1].center); + let body = egui::Rect::from_min_size(Pos2::ZERO, vec2(500.0, 400.0)); + let fit = Some((body.size(), zoom, center)); + if let Some(x) = app.ui.floating.iter_mut().find(|x| x.uid == uid && x.view == 1) { + x.fit = fit; + } + app.ui.about = true; + assert!(crate::panel_docking::modal_open(&app, &ctx), "a modal is open"); + let mut moved = Shown { ppi: Some(crate::ScreenPpi::Read(Some(150.0))), body: Some(body), fit, ..Default::default() }; + take_window_fit(&mut app, &ctx, ((uid, 1), true), win, &mut moved); + let v = app.views[1]; + assert_ne!(v.zoom, zoom, "the move to a denser display keeps the zoom percentage"); + let kept = app.ui.floating.iter().find(|x| x.uid == uid && x.view == 1).and_then(|x| x.fit); + assert_eq!(kept, Some((body.size(), v.zoom, v.center)), "the window keeps the settled zoom and center as its fit"); +} From 977e896fd0a67b93fc1f6f3f37135e5c41f78387 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:31:23 -0800 Subject: [PATCH 055/101] =?UTF-8?q?Plug-ins:=20File=20=E2=80=BA=20Place=20?= =?UTF-8?q?keeps=20a=20named=20importer=20and=20its=20params=20for=20every?= =?UTF-8?q?=20file?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - file.place with `importer` and `params` and `paths`, or with no file, opened the Place dialog with only the files, so its OK read them with the built-in reader. Each dialog entry now carries the importer and its params, from the paths given, the desktop pick and the web pick, and OK passes them to file.place and file.place.queue. - On the web, each picked file carries its own pick's importer and params. Picked files with other ones, or that arrive while a Place dialog is open, wait for the next dialog. - The Place dialog does not read the start of a PDF, .ai, EPS or PostScript file placed with an importer named to tell whether Link would place it as a document. - A path placed or opened with `importer` named is refused from its size before any of it is read. Before, its first 64 KiB were read first. - docs/plugins.md and docs/mcp.md say when the size check runs, that the web's File › Place reads the picked file in the browser, that File › Place's filters leave out extensions a built-in format reads, and that a dropped file a built-in format reads goes to that format. --- apps/vectorcraft-web/src/web.rs | 16 ++-- crates/engine/src/cmd/fileio/importer.rs | 24 +++-- crates/engine/tests/plugin_place.rs | 41 ++++++++ .../src/dialogs/tests_plugin_import.rs | 94 +++++++++++++++++++ crates/ui-egui/src/place.rs | 62 +++++++++--- crates/ui-egui/src/services.rs | 5 +- crates/ui-egui/src/tests/place.rs | 5 +- docs/mcp.md | 3 +- docs/plugins.md | 20 ++-- docs/target-app-parity.md | 2 +- 10 files changed, 233 insertions(+), 39 deletions(-) diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 9e23e4044f..054c9632cc 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -431,9 +431,12 @@ impl eframe::App for WebShell { match f.bytes_async().await { Ok(bytes) => { match target { - DropTarget::Place(d) => { - place_inbox.lock().unwrap_or_else(|e| e.into_inner()).push(PlaceArrival { name, bytes, drop: Some(d) }) - } + DropTarget::Place(d) => place_inbox.lock().unwrap_or_else(|e| e.into_inner()).push(PlaceArrival { + name, + bytes, + drop: Some(d), + with: serde_json::Value::Null, + }), DropTarget::Open => inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes)), } repaint.request_repaint(); @@ -477,8 +480,9 @@ fn services( }); })), script_inbox: Some(script_inbox), - // File → Place…: the picked files go to the Place dialog. - place_async: Some(Box::new(move || { + // File → Place…: the picked files go to the Place dialog, with the importer plug-in and + // parameters `with` names. + place_async: Some(Box::new(move |with: serde_json::Value| { let inbox = picked.clone(); let ctx = place_ctx.clone(); wasm_bindgen_futures::spawn_local(async move { @@ -493,7 +497,7 @@ fn services( }; let mut arrived = vec![]; for f in files { - arrived.push(PlaceArrival { name: f.file_name(), bytes: f.read().await, drop: None }); + arrived.push(PlaceArrival { name: f.file_name(), bytes: f.read().await, drop: None, with: with.clone() }); } inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(arrived); ctx.request_repaint(); diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index 53af9314a4..d89cfa22b7 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -148,7 +148,8 @@ fn check_data_for(p: &Value, mode: Mode, cmd: &str) -> Result<()> { /// `importer` names, or an extension no built-in format reads that an importer lists) is read up /// to [`import::MAX_INPUT_BYTES`]: past that, it is an error, unless the start of the file shows a /// built-in format and no importer was named, which is read whole as any other file is. A file past -/// the limit that isn't read whole is reported from its size, without reading it. +/// the limit that isn't read whole is reported from its size: with `importer` named, before any of +/// it is read, and otherwise after the start of it is read to look for a built-in format. pub(super) fn read_path(path: &str, p: &Value) -> Result> { read_path_for(path, p, Mode::Import, C) } @@ -157,21 +158,32 @@ pub(super) fn read_path(path: &str, p: &Value) -> Result> { #[cfg(not(target_arch = "wasm32"))] fn read_path_for(path: &str, p: &Value, mode: Mode, cmd: &str) -> Result> { let explicit = named(p, cmd)?.is_some(); - if !explicit && !importer_reads(&extension(path), mode) { + if explicit { + return read_for_importer(path, mode); + } + if !importer_reads(&extension(path), mode) { return super::read_file(path); } let head = super::read_file_head(path, SNIFF_BYTES)?; if head.len() < SNIFF_BYTES { return Ok(head); } - if !explicit && detect(path, &head).is_some() { + if detect(path, &head).is_some() { return super::read_file(path); } - let size = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.len(); - if size > import::MAX_INPUT_BYTES as u64 { + read_for_importer(path, mode) +} + +/// The file at `path` for an importer: refused from its size, before any of it is read, when it is +/// past [`import::MAX_INPUT_BYTES`]. +#[cfg(not(target_arch = "wasm32"))] +fn read_for_importer(path: &str, mode: Mode) -> Result> { + super::may_read(path)?; + let meta = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + if meta.is_file() && meta.len() > import::MAX_INPUT_BYTES as u64 { return Err(too_large(path, mode)); } - // The file can grow after the size is read. + // The file can grow after the size is read; anything but a regular file is refused here. let file = super::read_file_head(path, import::MAX_INPUT_BYTES + 1)?; if file.len() > import::MAX_INPUT_BYTES { return Err(too_large(path, mode)); diff --git a/crates/engine/tests/plugin_place.rs b/crates/engine/tests/plugin_place.rs index 7908dc86a7..e5996c7a36 100644 --- a/crates/engine/tests/plugin_place.rs +++ b/crates/engine/tests/plugin_place.rs @@ -280,3 +280,44 @@ fn failures_place_nothing() { assert_eq!(state(&mut s), before, "too large"); let _ = std::fs::remove_dir_all(&dir); } + +/// A file past the limit, placed with `importer` named, is refused from its size before any of it +/// is read: here the file can't be read at all, and the error is still the size. +#[test] +fn a_named_importer_refuses_a_large_file_before_reading_it() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.unread", r#"["tpu"]"#), ART)); + let dir = std::env::temp_dir().join(format!("vc-plugin-place-unread-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let big = dir.join("big.tpu"); + std::fs::File::create(&big).unwrap().set_len(vectorcraft_plugins::import::MAX_INPUT_BYTES as u64 + 1).unwrap(); + // Unix: no read permission. Windows: another handle that shares nothing. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&big, std::fs::Permissions::from_mode(0o000)).unwrap(); + } + #[cfg(windows)] + let _held = { + use std::os::windows::fs::OpenOptionsExt; + std::fs::OpenOptions::new().read(true).share_mode(0).open(&big).unwrap() + }; + // A user that reads the file anyway (root) can't show the order of the checks. + if std::fs::File::open(&big).is_ok() { + let _ = std::fs::remove_dir_all(&dir); + return; + } + let before = state(&mut s); + let e = s.execute("file.place", &json!({"path": big.to_string_lossy(), "importer": "plugin.test.place.unread"})).unwrap_err().to_string(); + assert!(e.contains("can't place `big.tpu`") && e.contains("larger than"), "{e}"); + assert_eq!(state(&mut s), before); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&big, std::fs::Permissions::from_mode(0o644)); + } + #[cfg(windows)] + drop(_held); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/dialogs/tests_plugin_import.rs b/crates/ui-egui/src/dialogs/tests_plugin_import.rs index 118e0f62cf..bd5bfa9971 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_import.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_import.rs @@ -273,6 +273,100 @@ fn a_named_placing_importer_skips_built_in_import_options() { app.run("plugin.remove", json!({"id": "test.ui.namedplace"})).unwrap(); } +/// `file.place` with `paths`, `importer` and `params` opens the Place dialog, and its OK places the +/// files with that importer and those parameters: one file at once, several through the place +/// cursor. The files are SVG files by their extension, which the built-in reader can't read. +#[test] +fn the_place_dialog_places_paths_with_the_importer_and_params_given() { + let dir = tmp_dir("placepaths"); + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + let manifest = tpl::importer("test.ui.placepaths", r#"["svg"]"#, params).replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::when_given(&manifest, Given::Params, r#""density":7.0"#, RECT)); + let paths: Vec = ["a.svg", "b.svg"] + .iter() + .map(|n| { + let p = dir.join(n); + std::fs::write(&p, b"?").unwrap(); + p.to_string_lossy().into_owned() + }) + .collect(); + let given = + |paths: &[String]| json!({"paths": paths, "importer": "plugin.test.ui.placepaths", "params": {"density": 7}, "showImportOptions": false}); + + app.run("file.place", given(&paths[..1])).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::place::KIND)); + let steps = app.session.active().unwrap().history.undo.len(); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(r["format"], "plugin.test.ui.placepaths", "{r} {}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + + app.run("file.place", given(&paths)).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options()["count"], 2, "{}", app.ui.status); + + app.run("plugin.remove", json!({"id": "test.ui.placepaths"})).unwrap(); +} + +/// A PDF file placed with an importer plug-in named is not read to tell whether Link would place it +/// as a document: the Place dialog counts it as a file the importer embeds. The file here doesn't +/// exist, which counts as a document when its start is read. +#[test] +fn the_place_dialog_does_not_read_a_file_a_named_importer_places() { + let dir = tmp_dir("placenamedpdf"); + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let manifest = tpl::importer("test.ui.placepdf", r#"["pdf"]"#, "{}").replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::returning(&manifest, RECT)); + let path = dir.join("missing.pdf").to_string_lossy().into_owned(); + let fields = |app: &mut VectorcraftApp, p: serde_json::Value| { + app.run("file.place", p).unwrap(); + let d = app.ui.dialog.take().expect("the Place dialog"); + (d.fields["__documents"].clone(), d.fields["__others"].clone()) + }; + assert_eq!(fields(&mut app, json!({"paths": [path]})), (json!(true), json!(false))); + assert_eq!(fields(&mut app, json!({"paths": [path], "importer": "plugin.test.ui.placepdf"})), (json!(false), json!(true))); + app.run("plugin.remove", json!({"id": "test.ui.placepdf"})).unwrap(); +} + +/// On the web, `file.place` with `importer` and `params` and no file starts the browser's pick, and +/// the Place dialog's OK places the picked file with that importer and those parameters. Each +/// pick's files keep that pick's importer, also when another pick started before they arrived, and +/// a pick with another importer waits for its own dialog. +#[test] +fn a_web_pick_places_with_the_importer_and_params_given() { + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + let manifest = tpl::importer("test.ui.webpick", r#"["svg"]"#, params).replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::when_given(&manifest, Given::Params, r#""density":7.0"#, RECT)); + let inbox = crate::place::PlaceInbox::default(); + app.services.place_inbox = Some(inbox.clone()); + let started: std::rc::Rc>> = Default::default(); + let starts = started.clone(); + app.services.place_async = Some(Box::new(move |with| starts.borrow_mut().push(with))); + + app.run("file.place", json!({"importer": "plugin.test.ui.webpick", "params": {"density": 7}, "showImportOptions": false})).unwrap(); + app.run("file.place", json!({})).unwrap(); + let arrive = |name: &str, with: serde_json::Value| { + inbox.lock().unwrap().push(crate::place::PlaceArrival { name: name.into(), bytes: b"?".to_vec(), drop: None, with }) + }; + arrive("a.svg", started.borrow()[0].clone()); + arrive("b.svg", started.borrow()[1].clone()); + crate::place::drain(&mut app); + let files = |app: &VectorcraftApp| app.ui.dialog.as_ref().filter(|d| d.kind == crate::dialogs::place::KIND).map(|d| d.fields["files"].clone()); + assert_eq!(files(&app), Some(json!([{"name": "a.svg", "importer": "plugin.test.ui.webpick", "params": {"density": 7}}]))); + let steps = app.session.active().unwrap().history.undo.len(); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(r["format"], "plugin.test.ui.webpick", "{r} {}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + crate::place::drain(&mut app); + assert_eq!(files(&app), Some(json!([{"name": "b.svg"}]))); + + app.run("plugin.remove", json!({"id": "test.ui.webpick"})).unwrap(); +} + /// The extensions File › Open's filters leave out of importers' (`fileio::opens_as_other`) are the /// ones File › Open installs, imports, checks or loads as something other than a document. #[test] diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 9c724c8b29..2ab9cc23e4 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -23,6 +23,9 @@ pub struct PlaceArrival { pub name: String, pub bytes: Vec, pub drop: Option, + /// A picked file's importer plug-in and parameters, from the `file.place` that started the pick + /// (`importer`, `params`; `null` or `{}` without them). + pub with: Value, } pub type PlaceInbox = Arc>>; @@ -223,8 +226,8 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result = match p.get("paths").and_then(Value::as_array) { - Some(a) => a.iter().filter_map(Value::as_str).map(|path| json!({ "path": path })).collect(), - None => return pick(app).map(|_| Value::Null), + Some(a) => a.iter().filter_map(Value::as_str).map(|path| with_importer(json!({ "path": path }), &p)).collect(), + None => return pick(app, &p).map(|_| Value::Null), }; if files.is_empty() { return Err("paths: give at least one file".into()); @@ -280,10 +283,11 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result Result<(), String> { +/// Pick files to place: the Place dialog opens with them (on the web once they arrive), placed with +/// the importer plug-in and parameters `p` names ([`with_importer`]). +fn pick(app: &mut VectorcraftApp, p: &Value) -> Result<(), String> { if let Some(f) = app.services.place_async.as_mut() { - f(); + f(with_importer(json!({}), p)); return Ok(()); } let paths = if app.services.pick_open_multi.is_some() { @@ -296,10 +300,25 @@ fn pick(app: &mut VectorcraftApp) -> Result<(), String> { if paths.is_empty() { return Err("cancelled".into()); } - open_dialog(app, paths.into_iter().map(|path| json!({ "path": path })).collect()); + open_dialog(app, paths.into_iter().map(|path| with_importer(json!({ "path": path }), p)).collect()); Ok(()) } +/// The params of `file.place` that name an importer plug-in and its parameters: a Place dialog file +/// entry carries them, and its file is read and placed with them. +const IMPORTER_KEYS: [&str; 2] = ["importer", "params"]; + +/// Place dialog file entry `file` with the importer plug-in and parameters `p` names +/// ([`IMPORTER_KEYS`]). +fn with_importer(mut file: Value, p: &Value) -> Value { + for k in IMPORTER_KEYS { + if let Some(v) = p.get(k).filter(|v| !v.is_null()) { + file[k] = v.clone(); + } + } + file +} + /// The Place dialog for `files` (`{path}`, or `{name}` with the bytes in [`PlaceState`]). fn open_dialog(app: &mut VectorcraftApp, files: Vec) { let units = app.session.active().map(|d| d.doc.units).unwrap_or_default(); @@ -326,9 +345,13 @@ fn open_dialog(app: &mut VectorcraftApp, files: Vec) { /// object), or a PDF, `.ai`, EPS or PostScript file on disk? A DCS file (an EPS file naming its /// plates) is placed as a linked image instead. Where the platform reads part of a file, only the /// file's start is read; a file longer than that is taken to be at least as long as its binary EPS -/// header says, and one whose header can't be told from it counts as a document. +/// header says, and one whose header can't be told from it counts as a document. A file that names +/// an importer plug-in is none of these, and none of it is read here. fn is_vectorcraft_file(app: &VectorcraftApp, file: &Value) -> bool { use vectorcraft_engine::cmd::place::{DCS_HEAD_BYTES, head_is_dcs}; + if file.get("importer").is_some() { + return false; + } let Some(path) = file.get("path").and_then(Value::as_str) else { return false }; let native = ["vectorcraft", vectorcraft_format::LEGACY_EXTENSION, "vctemplate"]; // The file's start, and the file's length when that is all of it. @@ -357,14 +380,15 @@ fn is_vectorcraft_file(app: &VectorcraftApp, file: &Value) -> bool { } } -/// The engine params naming `file` (a dialog file entry). +/// The engine params naming `file` (a dialog file entry), with the importer plug-in and parameters +/// it carries ([`IMPORTER_KEYS`]). fn source(app: &VectorcraftApp, file: &Value) -> Option { if let Some(path) = file.get("path").and_then(Value::as_str) { - return Some(json!({ "path": path })); + return Some(with_importer(json!({ "path": path }), file)); } let name = file.get("name").and_then(Value::as_str)?; let bytes = app.place.picked.iter().find(|(n, _)| n == name).map(|(_, b)| b)?; - Some(json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) })) + Some(with_importer(json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) }), file)) } /// The Place dialog's line about each of `files`, read at once, or where the files the user places @@ -481,7 +505,9 @@ pub fn confirm(app: &mut VectorcraftApp, d: &crate::state::Dialog) -> Result { let paths: Vec<&Value> = many.iter().filter_map(|s| s.get("path")).collect(); let files: Vec<&Value> = many.iter().filter(|s| s.get("path").is_none()).collect(); - let mut q = json!({ "paths": paths, "files": files, "link": link, "template": template }); + // The files of one dialog come from one `file.place`, with one importer plug-in and its + // parameters, if any. + let mut q = with_importer(json!({ "paths": paths, "files": files, "link": link, "template": template }), &many[0]); if !ask { // Each text file, DXF drawing and embedded PSD file in the cursor takes the options // confirmed last. @@ -770,21 +796,29 @@ pub fn drop_files(app: &mut VectorcraftApp, mut files: Vec<(DropTarget, DropFile } /// Files that arrived to be placed (web): drops go where they were dropped, picked files to the -/// Place dialog. +/// Place dialog. One dialog holds the files of picks with one importer plug-in and its parameters +/// ([`PlaceArrival::with`]); picked files with others, and picked files that arrive while a Place +/// dialog is open, wait in the inbox until it closes. pub fn drain(app: &mut VectorcraftApp) { let arrived: Vec = app.services.place_inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default(); - let mut picked = vec![]; + let open = app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::place::KIND); + let (mut picked, mut with, mut waiting) = (vec![], None::, vec![]); for a in arrived { match a.drop { Some(d) => drop_files(app, vec![(DropTarget::Place(d), (a.name, None, a.bytes))]), + None if open || with.as_ref().is_some_and(|w| *w != a.with) => waiting.push(a), None => { - picked.push(json!({ "name": a.name })); + picked.push(with_importer(json!({ "name": a.name }), &a.with)); app.place.picked.retain(|(n, _)| *n != a.name); + with = Some(a.with); app.place.picked.push((a.name, a.bytes)); } } } + if let (false, Some(q)) = (waiting.is_empty(), app.services.place_inbox.as_ref()) { + q.lock().unwrap_or_else(|e| e.into_inner()).splice(0..0, waiting); + } if !picked.is_empty() { open_dialog(app, picked); } diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 6c38464bd0..4436bfee63 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -131,8 +131,9 @@ pub struct Services { /// Show an open dialog for several files of the pick's types (a script's `File.openDialog` with /// `multiSelect`); returns their paths (none: cancelled). Without it, an open dialog for one. pub pick_open_files: Option, - /// Web: start an async pick of files to place (they arrive via `place_inbox`). - pub place_async: Option>, + /// Web: start an async pick of files to place (they arrive via `place_inbox`), each with the + /// importer plug-in and parameters given ([`place::PlaceArrival::with`]). + pub place_async: Option>, /// Files that arrived asynchronously to be placed (web: picked for Place, or dropped on the /// canvas). pub place_inbox: Option, diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index 4681281dd3..8402fa4f26 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -417,8 +417,9 @@ fn a_file_read_after_another_document_became_active_lands_where_it_was_dropped() DropTarget::Place(d) => d, t => panic!("{t:?}"), }; - let arrive = - |name: &str, drop| inbox.lock().unwrap().push(crate::place::PlaceArrival { name: name.into(), bytes: png(20, 10, 72.0), drop: Some(drop) }); + let arrive = |name: &str, drop| { + inbox.lock().unwrap().push(crate::place::PlaceArrival { name: name.into(), bytes: png(20, 10, 72.0), drop: Some(drop), with: json!(null) }) + }; // Dropped on A; another document opens while the file is read. let on_a = drop_on_active(&app); let want = Xf::new(rect, app.view().unwrap()).to_doc(pos); diff --git a/docs/mcp.md b/docs/mcp.md index 5236cc7e25..09dcf8594c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13300,7 +13300,8 @@ their bounds, Save then asks for a name, and `warnings` holds the importer's war `place` (`place: true` in `document.formats` and `plugin.list`) also places its files: `file.place`, `file.place.info` and `file.place.queue` take `importer?: "plugin."` (one that sets `place` and lists the file's extension) and `params?`, and without `importer` a file no built-in format reads goes to the first such importer by id that lists its -extension. The importer is given at most 128 MiB of the file (a larger file is refused from its size, before it is read) +extension. The importer is given at most 128 MiB of the file (a larger file is refused from its size, with `importer` +before any of it is read or decoded, and without it after its first 64 KiB are read or decoded) and `_context.mode` `"place"`; its objects, guides left out, are placed as one group named after the file, in the order it returned them, as one undo step, embedded whatever `link` says (`linked: false`). `plugin.run` of an importer is an error that names `document.open`. In the app, File › Open With lists the installed importers, and diff --git a/docs/plugins.md b/docs/plugins.md index 9a17420c8d..1e4ac38059 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -59,18 +59,24 @@ An importer whose manifest has `"place": true` also places its files. `document. importers that set `place`: when no built-in format reads the file, the first such importer by id that lists its extension reads it, and `"importer": "plugin."` names one, which must set `place` and list the file's extension, also one a built-in format reads. `"params"?: {…}` holds its parameters, which take their defaults when left out. The -importer is given at most 128 MiB of the file (a larger file is refused from its size, before it is read) and -`_context.mode` `"place"`, and returns its objects as it does for File › Open. They are placed in the open document as +importer is given at most 128 MiB of the file and `_context.mode` `"place"`, and returns its objects as it does for +File › Open. They are placed in the open document as one group named after the file, in the order the importer returned them, at the place, size or object `at`, `rect`, `replace` and `template` give, as one undo step; guides are left out, and the group's box is the bounds of what the other objects draw. The file is embedded whatever `link` says, as a format that can't be linked is, and the reply's `linked` is `false`. A decline, invalid output, a trap or Cancel places nothing and leaves the document and its undo steps as they were. An importer without `place` is not used -by File › Place, and naming it is an error. In the app, File › Place lists a placing importer's extensions under "All -placeable files" and a filter of its own, named after the importer, and on the web its files dropped on the canvas are -placed there (the desktop opens a dropped document, as it does an SVG); the importer then runs with its parameters' -defaults. A file placed with `importer` goes to that importer without the import options File › Place shows for a -text file, a DXF drawing, a PDF or a PSD file. These rules are VectorCraft's own. +by File › Place, and naming it is an error. A larger file is refused from its size. With `importer`, a `path` is refused +before any of it is read and `dataBase64` before any of it is decoded. Without `importer`, the first 64 KiB of the file +are read or decoded first to look for a built-in format. The web's File › Place reads the picked file in the browser +before the 128 MiB limit applies. In the app, File › Place lists a placing importer's extensions under "All placeable +files" and a filter of its own, named after the importer. Extensions that a built-in format reads are left out of both, +and an importer that lists only such extensions gets no filter. On the web, a dropped file that no built-in format +reads, by its extension or its content, is placed on the canvas by the first placing importer by id that lists its +extension (the desktop opens a dropped document, as it does an SVG); a dropped file that a built-in format reads goes +to that format. The importer then runs with its parameters' defaults. A file placed with `importer` goes to that +importer without the import options File › Place shows for a text file, a DXF drawing, a PDF or a PSD file. These rules +are VectorCraft's own. In the app, installed filters appear under **Object › Plug-ins**, next to **Install Plug-in…** and **Reload Plug-ins**; live effects under **Effect › Plug-ins** and in the Appearance panel's effect menu. A plug-in with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 652019e0fb..a836f4d6ba 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2645,7 +2645,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Exporter plug-ins (G17):** a WebAssembly plug-in of kind `exporter` adds a write-only file format. File › Export › Export As lists it after the built-in formats, with Use Artboards greyed out (the plug-in writes the whole document) and its parameters in a generated dialog once the file is picked; `document.export` writes it by its format id, `plugin.`, or by one of its extensions, and built-in formats keep theirs. The plug-in is given the native file's JSON (large images without their data) and `_context` (`mode`, `extension`, `name`), with 10 G instructions plus 4,000 per byte of input and 300 s, and Background Export's Cancel stops it between two slices of that budget. A decline or invalid output writes nothing; its warnings come back with the export's. Regressions: `crates/engine/tests/plugin_export.rs`, `crates/plugins/tests/abi.rs`, `crates/ui-egui/src/dialogs/tests_plugin_export.rs`. Scores and hours unchanged. - **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. -- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size before it is read) and `_context.mode` `"place"`, and its objects are placed as one group named after the file, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. +- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`, and its objects are placed as one group named after the file, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. - **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged. From 23b6184c5b506323574a7348cf7b0bd3cf48cff1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:31:42 -0800 Subject: [PATCH 056/101] Recolor with Preset: reject a color group ui.recolorDialog with preset: true and a group opened the preset dialog and dropped the group, so OK recolored the art without rewriting the group. That call is now an error. The params text and docs/control-protocol.md say so. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/recolor_preset.rs | 5 ++++- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/tests/recolor.rs | 1 + docs/control-protocol.md | 3 ++- 5 files changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 18951b9c90..f2c66fd0e7 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -995,7 +995,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.recolorDialog", "Recolor Artwork…", "", - "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", + "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library; an error with `group`)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", ), ( "ui.recolorUndo", diff --git a/crates/ui-egui/src/dialogs/recolor_preset.rs b/crates/ui-egui/src/dialogs/recolor_preset.rs index a9063c8945..9ebde00787 100644 --- a/crates/ui-egui/src/dialogs/recolor_preset.rs +++ b/crates/ui-egui/src/dialogs/recolor_preset.rs @@ -1,6 +1,6 @@ //! Edit → Edit Colors → Recolor with Preset: before Recolor Artwork opens on a preset (an n-color //! job or Color Library), this dialog asks whether to limit the new colors to a swatch library -//! (`ui.recolorDialog {preset: true, colors?, library?}`). OK opens Recolor Artwork with the +//! (`ui.recolorDialog {preset: true, colors?, library?}`, without `group`). OK opens Recolor Artwork with the //! preset's colors and the library chosen (None: no limit); Cancel opens nothing. //! //! Fields: `colors` (the preset's count, null for Color Library) and `limitTo` (a library id, @@ -27,6 +27,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if st.selection.is_empty() { return Err("select artwork to recolor".into()); } + if p.get("group").is_some_and(|g| !g.is_null()) { + return Err("`group` does not apply to a preset".into()); + } let colors = count(p.get("colors"))?; let limit = library_param(app, p)?; // A dialog this one replaces ends as Cancel ends it, its preview rolled back. diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 27bcf98155..10b0982582 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -996,7 +996,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.recolorDialog", "Recolor Artwork…", "", - "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", + "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library; an error with `group`)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", ), ( "ui.recolorUndo", diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 9a96a274c3..455f98055a 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -2012,6 +2012,7 @@ fn recolor_with_preset_asks_for_a_library_first() { art(&mut app, &["#333333", "#999999"]); assert!(app.run("ui.recolorDialog", json!({"colors": 1, "preset": 1})).is_err(), "`preset` is true or false"); assert!(app.run("ui.recolorDialog", json!({"colors": 0, "preset": true})).is_err(), "a preset has at least one color"); + assert!(app.run("ui.recolorDialog", json!({"colors": 1, "preset": true, "group": "Grays"})).is_err(), "a preset takes no group"); assert_eq!(dialog_kind(&app), None); let entries = crate::menus::menu_entries(&app); let presets: Vec = diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2f19b5fd37..dfe005ba1c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -292,7 +292,8 @@ Recolor Artwork: `ui.recolorDialog {colors?, library?, group?, preset?}` opens t or `"document"`, `""` for the first library; `group`: a colour group, Edit or Apply Color Group). With `preset: true` (the Edit › Edit Colors › Recolor with Preset items) it first opens the `recolorPreset` dialog, which asks whether to limit the colors to a swatch library: its field `limitTo` (a library id, `"document"`, or `""` for None) starts on -`library`, and its OK opens the `recolor` dialog with `colors` and that library. Fields: `rows` (`[{from: [keys], to: key, exclude?, tint?, model?}]` +`library`, and its OK opens the `recolor` dialog with `colors` and that library; `preset: true` with `group` is an +error. Fields: `rows` (`[{from: [keys], to: key, exclude?, tint?, model?}]` as `recolor.reduce` returns them), `colors` (null for Auto), `method`, `preserveWhite`, `preserveBlack`, `preserveGrays`, `limitTo`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`, `sliderMode` (the mode of the color sliders under the rows: `hsb`, `rgb`, `cmyk`, `lab`, or `tint` for a row whose new From ec3fe96195893bf7f75d8b5594274f45b31fc690 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:46:52 -0800 Subject: [PATCH 057/101] Recolor Artwork: roll back the replaced preview before reading the group Opening Recolor Artwork on a color group over its own preview of that group read the group's colors before the preview was rolled back, so the new dialog started on the previewed colors and OK could apply them again. The replaced dialog now ends first, after the parameters are checked, and the group is read from the restored document. --- crates/ui-egui/src/dialogs/recolor.rs | 27 +++++++++++++++++---------- crates/ui-egui/src/tests/recolor.rs | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 2901c69bd9..46c02bbf05 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -200,6 +200,23 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let st = app.session.active().ok_or("no document open")?; let art = !st.selection.is_empty(); let group = p.get("group").and_then(Value::as_str); + if let Some(g) = group + && !st.doc.swatch_groups.iter().any(|x| x.name == g) + { + return Err(format!("no colour group `{g}`")); + } + // Colours alone (no art, no group) become a new colour group. + let new_group = !art && group.is_none(); + if new_group && !matches!(p.get("colors"), Some(Value::Array(cs)) if cs.iter().any(|c| color_value(c).is_some())) { + return Err("select artwork (or a colour group) to recolor".into()); + } + let limit = library_param(app, p)?; + // A dialog this one replaces ends as Cancel ends it, its preview rolled back, before the + // group's colours are read. + if app.ui.dialog.is_some() { + super::cancel(app); + } + let st = app.session.active().ok_or("no document open")?; let group_colors: Option> = match group { Some(g) => { let g = st.doc.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| format!("no colour group `{g}`"))?; @@ -212,17 +229,11 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { (None, Some(Value::Array(cs))) => cs.iter().filter_map(color_value).map(|c| key(&c)).collect(), _ => vec![], }; - // Colours alone (no art, no group) become a new colour group. - let new_group = !art && group.is_none(); - if new_group && assign.is_empty() { - return Err("select artwork (or a colour group) to recolor".into()); - } let count = match p.get("colors").and_then(Value::as_u64) { Some(n) => json!(n.max(1)), None if !assign.is_empty() => json!(assign.len()), None => Value::Null, }; - let limit = library_param(app, p)?; // Without art the rows are the group's colours, as they are. let mut start: Vec = if art { vec![] } else { assign.iter().map(|k| json!({"from": [k], "to": k})).collect() }; number_slots(&mut start); @@ -242,10 +253,6 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { snap(app, &d, &mut rs); d.fields.insert("rows".into(), Value::Array(rs)); // Undo Changes has nothing to undo on a new opening. - // A dialog this one replaces ends as Cancel ends it, its preview rolled back. - if app.ui.dialog.is_some() { - super::cancel(app); - } app.ui.recolor_history = History { opened: Some(snapshot(&d)), ..History::default() }; app.ui.dialog = Some(d); Ok(Value::Null) diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 455f98055a..5f2a79b9e5 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -2054,6 +2054,27 @@ fn recolor_with_preset_asks_for_a_library_first() { dialogs::cancel(&mut app); } +/// Recolor Artwork opened on a colour group over its own preview of that group starts on the +/// group's colours as the rolled-back preview leaves them. +#[test] +fn reopening_a_group_over_its_preview_starts_on_the_groups_colours() { + let mut app = app(); + let ctx = context(); + art(&mut app, &["#ff0000", "#0000ff"]); + let before = group_keys(&app, "Brights"); + app.run("ui.recolorDialog", json!({"group": "Brights"})).unwrap(); + dialog_frame(&mut app, &ctx); + let mut rows = field(&app, "rows"); + rows[1]["to"] = json!("rgb 1 2 3"); + set(&mut app, "rows", rows); + dialog_frame(&mut app, &ctx); + assert_ne!(group_keys(&app, "Brights"), before, "the preview changes the group"); + app.run("ui.recolorDialog", json!({"group": "Brights"})).unwrap(); + assert_eq!(group_keys(&app, "Brights"), before, "the preview is rolled back"); + assert_eq!(field(&app, "__assign"), json!(before), "the new dialog starts on the group's colours"); + dialogs::cancel(&mut app); +} + /// Every paint under `v`, in order: its color, the swatch it is linked to and its tint. fn paints_in(v: &Value, out: &mut Vec<(Color, Option, f64)>) { match v { From 14e5fae4ca623401fdcf9725db92e1fcc7bcd7dd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:03:06 -0800 Subject: [PATCH 058/101] Docs: Overprint Preview's white canvas applies while the artboards show The ui-parity row, the Views evidence line and docs/mcp.md now state the condition that white_canvas() checks: the canvas around the artboards is white in Overprint Preview and Separations Preview while the artboards show. --- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 37332352f4..00c626d6fc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5081,7 +5081,7 @@ of knocking them out. `object.setOverprint {fill?, stroke?, item?, ids?}` sets i characters too; `item` aims at one appearance item) and `attributes.info {ids?}` reads it back (`null` where the objects differ). Overprint Preview (`view.overprintPreview`) and Separations Preview show it; rendering approximates it by darkening (the stronger ink of each plate wins, so a colour overprinting itself stays that colour). While either -preview is on, the canvas around the artboards is white instead of the pasteboard color and the artboards draw no +preview is on and the artboards show, the canvas around the artboards is white instead of the pasteboard color and the artboards draw no shadows; turning it off brings both back. Older files that listed Overprint Black objects in the document get the flags on load. PDF export writes them with `advanced.overprint: "preserve"` (the default): each overprinting fill and stroke sets a graphics state with `/OP true /op true /OPM 1` (`/OPM 0` in PDF/A). With `discardWhiteOverprint` (`document.setup`, on by diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b84699f7a6..fb61721b36 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1633,7 +1633,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Navigator panel options:** the Navigator panel menu's Panel Options… sets the color the view box is drawn in, from a preset list (VectorCraft's own: Light Red, the default, then the layer colors) or a custom color, and Draw Dashed Lines as Solid Lines, off by default, which draws dashed strokes without their dashes in the panel's thumbnail only (`ui.navigatorPanelOptions`; kept with the UI state; behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). - **Attributes panel options:** the Attributes panel menu's Panel Options… sets how many recent URLs the URL menu lists, a whole number from 1 to 30 (10 by default, VectorCraft's own value); the panel keeps the 30 newest URLs of the session, so a lower count hides older URLs without removing them (`ui.attributesPanelOptions`; kept with the UI state; behavior reference: [Create image maps for web graphics](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/create-image-maps-for-web-graphics.html); test `panel_options_set_how_many_recent_urls_the_menu_lists`). - **Navigator View Artboard Contents Only:** the Navigator panel menu's View Artboard Contents Only is on by default, and the thumbnail then shows only the art inside the artboards, with art on the pasteboard and in the gaps between artboards left out; turning it off shows the art outside the artboards too (`ui.navigatorPanelOptions {viewArtboardContentsOnly}`; kept with the UI state, read as on when it was never saved; the fit to the artboards' union and the cut at each artboard's edge are VectorCraft's own rules; behavior references: [Navigate and zoom artwork](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/navigate-and-zoom-artwork.html), [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). -- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard, fits it and synchronizes the Artboard tool selection when that tool is active; ordinary object selection is preserved. Its four buttons are also commands of their own (`view.firstArtboard`, `view.previousArtboard`, `view.nextArtboard`, `view.lastArtboard`), listed in Edit › Keyboard Shortcuts without a default key, so a user can give them keys such as Page Up and Page Down (#5218). Actual Next-button regressions cover keyboard/Properties deletion and Undo in `chrome.rs`. Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, `view.screenMode` from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible under the outlines (#1505, fixes #1486). Outline view draws on a white canvas in every interface brightness and Canvas Color, pasteboard included, with the artboards as their edges and no paper (VectorCraft's own rule), so the black outlines of art on the pasteboard show. Overprint Preview and Separations Preview draw the canvas around the artboards in white, with no artboard shadows (VectorCraft's own rule), and turning them off brings back the pasteboard color and the shadows. +- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard, fits it and synchronizes the Artboard tool selection when that tool is active; ordinary object selection is preserved. Its four buttons are also commands of their own (`view.firstArtboard`, `view.previousArtboard`, `view.nextArtboard`, `view.lastArtboard`), listed in Edit › Keyboard Shortcuts without a default key, so a user can give them keys such as Page Up and Page Down (#5218). Actual Next-button regressions cover keyboard/Properties deletion and Undo in `chrome.rs`. Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, `view.screenMode` from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible under the outlines (#1505, fixes #1486). Outline view draws on a white canvas in every interface brightness and Canvas Color, pasteboard included, with the artboards as their edges and no paper (VectorCraft's own rule), so the black outlines of art on the pasteboard show. While the artboards show, Overprint Preview and Separations Preview draw the canvas around the artboards in white, with no artboard shadows (VectorCraft's own rule), and turning them off brings back the pasteboard color and the shadows. In Presentation Mode, → and ← go to the next and the previous artboard, and a click anywhere goes to the next one, as the status bar navigator's Next and Previous do (`view.goToArtboard`): on the last artboard → and a click leave the view as it is, and so does ← on the first. The arrow keys do not move the selection there, and the tool does not receive a click, so a click selects and draws nothing (behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). Full Screen Mode and Presentation Mode put the window full screen, covering the taskbar and the window's frame, and Normal Screen Mode or Full Screen Mode with Menu Bar puts it back (#4365); a window the user made full screen stays so. An unmodified Escape in either Full Screen Mode exits to Normal Screen Mode after any open popup, focused field, tool gesture, ruler-origin drag, floating Tools panel move, edit mode, drawer, flyout or view rotation has taken its Escape; a later Escape exits when that action is finished. This is a VectorCraft choice for both full screen variants, based on the public [shortcut list](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html); the list does not specify that priority or the return mode. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 244e96035c..e9e22bc7dd 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -540,7 +540,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | | Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | -| Overprint Preview draws a white canvas around the artboards, with no artboard shadows | done | VectorCraft's own rule, in Overprint Preview and in Separations Preview, which turns it on: the canvas outside the artboards is white in every interface brightness, the artboards keep their paper and edges and draw no shadows, and the artboard names and the ruler origin's crosshair are dark gray. Where the Artboard tool's Fade Region Outside Artboard darkens a white canvas (here and in Outline) the names are black, and over a white canvas the Artboard tool's names of its selected artboards are dark blue. With a display profile, translucent art around the artboards is blended with the white canvas. Turning the preview off brings back the pasteboard color and the shadows. Tests `overprint_preview_draws_a_white_canvas_without_shadows`, `outline_names_show_on_the_faded_canvas`, `translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas`, `translucent_pixels_around_the_artboards_are_blended_with_the_white_canvas` | +| Overprint Preview draws a white canvas around the artboards, with no artboard shadows | done | VectorCraft's own rule, in Overprint Preview and in Separations Preview, which turns it on: while the artboards show, the canvas outside the artboards is white in every interface brightness, the artboards keep their paper and edges and draw no shadows, and the artboard names and the ruler origin's crosshair are dark gray. Where the Artboard tool's Fade Region Outside Artboard darkens a white canvas (here and in Outline) the names are black, and over a white canvas the Artboard tool's names of its selected artboards are dark blue. With a display profile, translucent art around the artboards is blended with the white canvas. Turning the preview off brings back the pasteboard color and the shadows. Tests `overprint_preview_draws_a_white_canvas_without_shadows`, `outline_names_show_on_the_faded_canvas`, `translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas`, `translucent_pixels_around_the_artboards_are_blended_with_the_white_canvas` | | Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | From 3d460c1697193bc990534bab1144f0232d6193d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:55:45 -0800 Subject: [PATCH 059/101] Scripts: guide, layer, move and addDocument fixes for the object model - Document.selection and PageItem.selected refuse a path made into a guide while Lock Guides is on, instead of passing the check and then selecting nothing. The locked artboards are measured once per assignment. - An edit whose command selects the objects it changes puts the current layer and the highlighted Layers panel rows back as they were. layer.setCurrent takes keepRows, which leaves the highlighted rows as they are. - move on an object on a locked artboard throws Cannot move, as editable reads false for it. duplicate, with or without a relative object, on a hidden or locked object or an object on a locked artboard throws Cannot duplicate and makes no copy. - When move takes the last path out of a compound path, the empty compound path is deleted in the same undo step. - addDocument writes each warning from reading the profile's file to the Script Console as addDocument: , and a previewMode of PixelPreview throws an error that says it is not available yet. --- crates/engine/src/cmd/layer.rs | 7 +- crates/engine/src/script/dom.rs | 84 ++++++++++++-- crates/engine/src/tests/layers.rs | 7 ++ crates/engine/src/tests/script_dom.rs | 160 ++++++++++++++++++++++++++ docs/mcp.md | 20 +++- 5 files changed, 261 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 73c92877e9..d2258f4e4a 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -66,7 +66,7 @@ pub fn specs() -> Vec { "Set Current Layer", [], None, - "{id} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. Not an undo step → {id, layer}", + "{id, keepRows?: bool} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. `keepRows` true leaves the highlighted rows as they are. Not an undo step → {id, layer}", has_doc, set_current ), @@ -633,10 +633,13 @@ fn duplicate_rows(s: &mut Session, p: &Value) -> Result { fn set_current(s: &mut Session, p: &Value) -> Result { const C: &str = "layer.setCurrent"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; + let keep_rows = switch_or(p, "keepRows", false, C)?; let st = s.doc_mut()?; let layer = st.doc.layer_containing(id).ok_or(EngineError::NoNode(id))?; st.active_layer = Some(layer); - st.layer_rows = vec![id]; + if !keep_rows { + st.layer_rows = vec![id]; + } st.revision += 1; Ok(json!({ "id": id.0, "layer": layer.0 })) } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e073a791ff..8079107fd8 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -583,6 +583,31 @@ fn done_unless_refused(r: std::result::Result) -> std::result:: } } +/// Makes `layer` the current layer of the active document `uid` again, with `rows` the highlighted +/// Layers panel rows, after selecting objects made the layer of the last of them current and +/// cleared the rows. Nothing runs when `layer` is gone. `layer.highlight` puts the rows back when +/// they changed, and then `layer.setCurrent` with `keepRows` makes `layer` current when it is not. +fn restore_layer(h: &Host, uid: u64, layer: Option, rows: &[NodeId]) -> std::result::Result<(), HostError> { + let Some(layer) = layer else { return Ok(()) }; + let rows = { + let s = h.session.borrow(); + let Some(st) = s.active().filter(|st| st.uid == uid) else { return Ok(()) }; + if st.doc.node(layer).is_none() { + return Ok(()); + } + let rows: Vec = rows.iter().copied().filter(|r| st.doc.node(*r).is_some()).collect(); + (st.highlighted_rows() != rows).then(|| rows.iter().map(|r| r.0).collect::>()) + }; + if let Some(rows) = rows { + command(h, "layer.highlight", &json!({"ids": rows, "mode": "set"}))?; + } + let current = h.session.borrow().active().is_some_and(|st| st.active_layer == Some(layer)); + if !current { + command(h, "layer.setCurrent", &json!({"id": layer.0, "keepRows": true}))?; + } + Ok(()) +} + /// Runs `f` with the document `uid` active, and makes the document that was active before active /// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s /// commands changed it (commands given ids select them first), direct-selected anchors, segments, @@ -595,10 +620,11 @@ fn on_doc( keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { - let (index, active, before) = { + let (index, active, before, layer) = { let s = h.session.borrow(); let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - (index, s.active_index(), s.documents()[index].selection.clone()) + let st = &s.documents()[index]; + (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows())) }; let switch = active != Some(index); if switch { @@ -614,6 +640,9 @@ fn on_doc( if let Some(doc) = doc { restored = restore_selection(h, &doc, &before); } + if restored.is_ok() { + restored = restore_layer(h, uid, layer.0, &layer.1); + } } // The document that was active is active again before any error is given: `f`'s error first, // then the selection's, then the switch back's. @@ -854,7 +883,10 @@ impl NewDoc<'_> { if let Some(d) = self.preview { let mode = match d { Data::String(s) if s == "DocumentPreviewMode.DefaultPreview" => "default", - Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => "pixel", + // Pixel Preview is a setting of the app's view, which a script cannot turn on. + Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => { + return Err(HostError::Error("DocumentPreviewMode.PixelPreview is not available yet".into())); + } Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => "overprint", _ => return Err(HostError::Type("previewMode must be a DocumentPreviewMode value".into())), }; @@ -981,6 +1013,10 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { let reason = e["reason"].as_str().unwrap_or_default(); return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}"))); } + // Each warning from reading the profile's file goes to the console. + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut)); + } let s = h.session.borrow(); let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; Ok(doc_ref(h, st.uid)) @@ -1203,10 +1239,16 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); - for d in list { - let item = item_of(h, d)?; + // The document is read once for every object: nothing changes it while the list is checked. + let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); + let locks = d.locked_artboards(); + for v in list { + let item = item_of(h, v)?; + // A path made into a guide is not selected while Lock Guides is on, as the selection + // commands leave it out. let ok = item.doc.uid == doc.uid - && with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id)); + && crate::cmd::select::is_selectable(&d, isolation, &locks, item.id) + && !(guides_locked && crate::is_guide_path(&d, item.id)); if !ok { let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); @@ -1689,7 +1731,8 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s if !editable(d, parent) { return Err(HostError::Error("the layer or group is hidden or locked".into())); } - if !editable(d, item.id) { + // An object on a locked artboard is not moved, as `editable` reads false for it. + if !editable(d, item.id) || on_locked_artboard(h, st, item.id) { let name = d.node(item.id).and_then(typename).unwrap_or("page item"); return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0))); } @@ -1730,14 +1773,30 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul } /// `move(relativeObject, insertionLocation?)`: moves the item into or beside `relativeObject`, a -/// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`). +/// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`). An +/// object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard +/// is refused. fn item_move(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; if matches!(arg(a, 1), Data::Undefined) { return Err(HostError::Type("move needs a relative object".into())); } let to = destination(h, item, arg(a, 1), arg(a, 2), false)?; - place(h, item.doc, item.id, &to)?; + // When the last path leaves a compound path, the compound path is deleted in the same step + // rather than left empty. + let emptied = with_doc(h, item.doc, |_, st| { + let parent = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p))?; + (matches!(parent.kind, NodeKind::Compound { .. }) && parent.children().is_some_and(|c| c.len() == 1) && parent.id != to.parent) + .then_some(parent.id) + }); + match emptied { + None => place(h, item.doc, item.id, &to)?, + Some(compound) => atomically(h, |h| { + place(h, item.doc, item.id, &to)?; + on_doc(h, item.doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": [compound.0]})))?; + Ok(()) + })?, + } Ok(arg(a, 0).clone()) } @@ -1761,6 +1820,13 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER.into())); } + // `edit.duplicate` copies only what it can select. + let refused = with_doc(h, item.doc, |_, st| { + (!editable(&st.doc, item.id) || on_locked_artboard(h, st, item.id)).then(|| st.doc.node(item.id).and_then(typename).unwrap_or("page item")) + }); + if let Some(name) = refused { + return Err(HostError::Error(format!("Cannot duplicate {name} {}", item.id.0))); + } let to = match arg(a, 1) { Data::Undefined => { if !matches!(arg(a, 2), Data::Undefined) { diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index c3bba6803b..2fde78bd10 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -157,6 +157,13 @@ fn clicking_rows_at_any_depth_highlights_them_and_sets_the_current_layer() { let n = rect(&mut s, 50.0); assert_eq!(parent(&s, n), Some(sub)); assert!(s.execute("layer.setCurrent", &json!({"id": 9999})).is_err()); + // `keepRows` makes the layer current and leaves the highlighted rows. + run(&mut s, "layer.setCurrent", json!({"id": b.0})); + run(&mut s, "layer.setCurrent", json!({"id": c.0, "keepRows": true})); + let st = s.doc().unwrap(); + assert_eq!((st.highlighted_rows(), st.current_layer()), (vec![b], Some(layer))); + assert!(s.execute("layer.setCurrent", &json!({"id": a.0, "keepRows": 1})).is_err()); + assert_eq!(s.doc().unwrap().current_layer(), Some(layer), "a bad keepRows changes nothing"); // Shift/Ctrl: several rows. run(&mut s, "layer.highlight", json!({"ids": [a.0, g.0], "mode": "set"})); run(&mut s, "layer.highlight", json!({"ids": [c.0], "mode": "add"})); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index f517312983..e80e973626 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -265,6 +265,25 @@ fn selection_assignment_is_atomic_across_invalid_items() { assert!(e.contains("Cannot select"), "{e}"); } +#[test] +fn a_guide_path_is_not_selected_while_guides_are_locked() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + // The assignment and `selected` refuse the guide path, and the selection stays as it was. + for source in ["app.activeDocument.selection = app.activeDocument.pageItems[0];", "app.activeDocument.pageItems[0].selected = true;"] { + let e = failure(&mut s, source); + assert!(e.contains(&format!("Cannot select PathItem {}", a.0)), "{source}: {e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![b], "{source}"); + } + // With the guides unlocked, the guide path is selected. + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[0];"); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); +} + #[test] fn an_inactive_document_changes_without_switching_tabs() { let (mut s, a, _) = doc(); @@ -454,6 +473,30 @@ fn a_path_inside_a_compound_path_is_not_reordered() { assert_eq!(out, vec![json!([1, 2])]); } +#[test] +fn moving_the_last_path_out_of_a_compound_path_deletes_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + let layer = s.active().unwrap().doc.layers[0].id; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.pageItems[0], m = [d.pageItems[1], d.pageItems[2]];\ + m[0].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\ + m[1].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\ + try { c.name; } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out, vec![json!(3), json!(2), json!("Stale page item")]); + let doc = &s.active().unwrap().doc; + assert!(doc.node(compound).is_none(), "the empty compound path is deleted"); + // Each path went directly above the compound path, the second above the first. + assert_eq!(layer_order(&s), [b, a]); + assert!([a, b].iter().all(|id| doc.parent_of(*id) == Some(layer))); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); +} + #[test] fn a_copy_of_an_object_with_a_large_id_is_the_copy() { let mut s = Session::new(); @@ -610,6 +653,37 @@ fn an_edit_keeps_a_layers_panel_target() { assert_eq!((sel.target, sel.objects.len(), sel.objects.contains(&b)), (Some(layer), 4, true)); } +#[test] +fn an_edit_keeps_the_current_layer() { + let (mut s, a, b) = doc(); + let first = s.active().unwrap().doc.layers[0].id; + let back = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let layer = |s: &Session| (s.active().unwrap().active_layer, s.active().unwrap().highlighted_rows()); + assert_eq!(layer(&s), (Some(back), vec![back])); + // Moving an object of the first layer selects it for the command; the new layer stays current. + log(&mut s, "app.activeDocument.pageItems[0].left = 50;"); + assert_eq!(layer(&s), (Some(back), vec![back])); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + // With nothing selected and no row highlighted, the layer stays current and no row is highlighted. + s.execute("select.none", &json!({})).unwrap(); + s.execute("layer.setCurrent", &json!({"id": back.0})).unwrap(); + s.execute("layer.highlight", &json!({"ids": [], "mode": "set"})).unwrap(); + assert_eq!(layer(&s), (Some(back), vec![])); + log(&mut s, "app.activeDocument.pageItems[1].left = 120;"); + assert_eq!(layer(&s), (Some(back), vec![])); + assert!(s.active().unwrap().selection.objects.is_empty()); + // Targeting a layer makes it current and leaves another layer's row highlighted; both stay. + s.execute("layer.highlight", &json!({"ids": [first.0], "mode": "set"})).unwrap(); + s.execute("layer.target", &json!({"id": back.0})).unwrap(); + assert_eq!(layer(&s), (Some(back), vec![first])); + log(&mut s, "app.activeDocument.pageItems[0].left = 70;"); + assert_eq!(layer(&s), (Some(back), vec![first])); + // Assigning the selection makes the layer of the selected object current, as a click does. + log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[0];"); + assert_eq!(s.active().unwrap().active_layer, Some(first)); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); +} + /// A document with a rectangle at the bottom of the stack, then a dynamic symbol instance of two /// rectangles and an Objects on Path group of one rectangle: (session, instance, group, the /// group's rectangle). @@ -949,6 +1023,43 @@ fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used() { + let dir = std::env::temp_dir().join(format!("vc-script-add-document-warning-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + let file = dir.join("Print.vectorcraft"); + let mut v: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + let broken = format!("Script profile broken {}", std::process::id()); + v["profiles"] = json!({ &broken: {"mime": "application/vnd.iccprofile", "data": "AAAA"} }); + std::fs::write(&file, serde_json::to_vec(&v).unwrap()).unwrap(); + let r = run(&mut s, "vc.log(app.documents.addDocument('Print').typename);").unwrap(); + assert_eq!(r["log"], json!(["Document"])); + let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default(); + let named = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("addDocument: ") && l.contains(&broken)); + assert!(named, "{lines:?}"); + assert_eq!(s.documents().len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn add_document_refuses_pixel_preview() { + let mut s = Session::new(); + let e = failure(&mut s, "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.PixelPreview; app.documents.addDocument('Web', p);"); + assert!(e.contains("DocumentPreviewMode.PixelPreview is not available yet"), "{e}"); + assert!(s.documents().is_empty()); + let out = log( + &mut s, + "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.DefaultPreview; vc.log(app.documents.addDocument('Web', p).typename);", + ); + assert_eq!(out, vec![json!("Document")]); +} + #[test] fn document_preset_values_count_toward_the_data_a_run_passes() { // A 64 KiB title, set once, then read or handed to addDocument 32 times: 2 MiB, over a 1 MiB limit. @@ -1061,6 +1172,55 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +#[test] +fn move_and_duplicate_refuse_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let (order, steps) = (layer_order(&s), undo_steps(&s)); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.PLACEBEFORE);"); + assert!(e.contains(&format!("Cannot move PathItem {}", a.0)), "{e}"); + assert_eq!((layer_order(&s), undo_steps(&s)), (order.clone(), steps)); + // `duplicate` refuses it too, with or without a relative object. + for source in ["app.activeDocument.pageItems[0].duplicate();", "var p = app.activeDocument.pageItems; p[0].duplicate(p[1]);"] { + let e = failure(&mut s, source); + assert!(e.contains(&format!("Cannot duplicate PathItem {}", a.0)), "{source}: {e}"); + } + assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps)); + lock(&mut s, false); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.PLACEBEFORE);"); + assert_eq!(layer_order(&s), [b, a]); +} + +#[test] +fn duplicate_refuses_hidden_or_locked_art() { + let (mut s, a, b) = doc(); + for (on, off) in [ + (json!({"ids": [b.0], "locked": true}), json!({"ids": [b.0], "locked": false})), + (json!({"ids": [b.0], "visible": false}), json!({"ids": [b.0], "visible": true})), + ] { + s.execute("object.setProps", &on).unwrap(); + let (order, steps) = (layer_order(&s), undo_steps(&s)); + // With no argument and with a relative object. + for source in ["app.activeDocument.pageItems[1].duplicate();", "var p = app.activeDocument.pageItems; p[1].duplicate(p[0]);"] { + let e = failure(&mut s, source); + assert!(e.contains(&format!("Cannot duplicate PathItem {}", b.0)), "{on} {source}: {e}"); + } + assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps), "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let order = layer_order(&s); + assert_eq!(order.len(), 3); + assert!(order.contains(&a) && order.contains(&b)); +} + /// Reading `editable` on every member of a group on a locked artboard measures the group once. #[test] fn editable_measures_a_group_on_a_locked_artboard_once() { diff --git a/docs/mcp.md b/docs/mcp.md index 90591ae2ea..c805cacaa9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2637,7 +2637,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the - profile and the reason, and makes no document. + profile and the reason, and makes no document. Each warning from reading the profile's file (a color profile in it + that cannot be used, for example) goes to the Script Console as a line `addDocument: `. A `previewMode` of + `DocumentPreviewMode.PixelPreview` throws an error that says it is not available yet, and no document is made. `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) @@ -2657,7 +2659,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` directly below it. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and - the undo history as they were before the call. `duplicate` on a path inside a compound path throws + the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or + locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an + object, with or without a relative object, throws `Cannot duplicate` and makes no copy. When `move` takes the last + path out of a compound path, the empty compound path is deleted in the same undo step. `duplicate` on a path inside a compound path throws `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a `RasterItem`. The @@ -2671,7 +2676,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem` for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each changed document. A value that changes nothing runs no command, and a change to another document leaves the active - tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine + tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers + panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` @@ -2680,7 +2686,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with - nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, + nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or + with `selected`. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, @@ -6363,8 +6370,9 @@ itself, and each sublayer has its own colour for the selection highlight. `docum report `color`, `template`, `printable`, `preview`, `dimImages` and `clip`), the `currentLayer` (where new art goes) and `layerRows`, the rows highlighted in the panel. -- **Clicking rows** (not undo steps): `layer.setCurrent {id}` is a plain click on any row: it alone is highlighted - and its layer (the row itself when it is a layer or sublayer) becomes current. `layer.highlight {ids, mode?: +- **Clicking rows** (not undo steps): `layer.setCurrent {id, keepRows?}` is a plain click on any row: it alone is + highlighted and its layer (the row itself when it is a layer or sublayer) becomes current; with `keepRows` true the + highlighted rows stay as they are. `layer.highlight {ids, mode?: set|add|toggle}` is Shift-click (a range) and Ctrl/Cmd-click (toggle). Selecting art makes its layer current. Without `ids`, the panel commands below act on the highlighted rows, else on the current layer. - **Selection column**: `layer.selectAll {id, add?}` selects a row's visible, unlocked art (a layer's sublayers' From dc9adb195d0cadbb5153da28cd8e08a76fbe3784 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 14:10:57 -0800 Subject: [PATCH 060/101] Scripts: pageItems lists the art inside blends, envelopes, repeats and intertwines pageItems walked into groups and compound paths only, so the objects inside a blend, an envelope, a repeat or an intertwine were missing from length, [i], index and getByName, although each of them reports that container as its parent. The walk now goes into every container's children. --- crates/engine/src/script/dom.rs | 7 ++++--- crates/engine/src/tests/script_dom.rs | 15 +++++++++++++++ docs/mcp.md | 4 +++- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8079107fd8..cb901014b5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -397,11 +397,12 @@ fn page_items(h: &Host, st: &DocState) -> Rc> { match &n.kind { NodeKind::Layer { children, .. } => walk(children, out), NodeKind::RulerGuide { .. } => {} - NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { + _ => { out.push(n.id); - walk(children, out); + if let Some(children) = n.children() { + walk(children, out); + } } - _ => out.push(n.id), } } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e80e973626..60e3a71521 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -100,6 +100,21 @@ fn page_items_are_live_and_typed_for_all_node_kinds() { ); } +#[test] +fn page_items_list_the_art_inside_a_blend() { + let (mut s, a, b) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].name = 'first';"); + s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 2})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, t = [];\ + for (var i = 0; i < p.length; i++) t.push(p[i].typename);\ + vc.log(t.join(','));\ + vc.log(p.getByName('first').parent.typename); vc.log(p.index('first').typename);", + ); + assert_eq!(out, vec![json!("BlendItem,PathItem,PathItem"), json!("BlendItem"), json!("PathItem")]); +} + #[test] fn page_item_geometry_uses_document_coordinates_with_y_up() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index c805cacaa9..4685f408d7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2643,7 +2643,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) - has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each + lists every object in the document's layers, the objects inside groups, compound paths, blends, envelopes, repeats + and intertwines included, and has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either + collection is true for each entry `[i]` gives. Each page item (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/) has `typename`, `parent`, `name`, `note` (the Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds From b7c98147e905f237df0dc7598836df047e634991 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 15:51:43 -0800 Subject: [PATCH 061/101] Recolor Artwork: find a renamed group's name over its preview Opening Recolor Artwork on a color group while the open dialog previewed a rename of that group failed with "no colour group", because the name was checked against the previewed document before Cancel restored it. The name is now checked against the document without the replaced dialog's preview. An unknown group still fails and leaves the open dialog as it is. --- crates/ui-egui/src/dialogs/recolor.rs | 8 +++++++- crates/ui-egui/src/tests/recolor.rs | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 46c02bbf05..19657a52ca 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -200,8 +200,14 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let st = app.session.active().ok_or("no document open")?; let art = !st.selection.is_empty(); let group = p.get("group").and_then(Value::as_str); + // The group is looked for in the document without the preview of the dialog this one replaces + // (which can rename the group), as that dialog's Cancel below leaves it. + let unpreviewed = match &st.interaction { + Some(it) if app.ui.dialog.is_some() => &it.doc, + _ => &st.doc, + }; if let Some(g) = group - && !st.doc.swatch_groups.iter().any(|x| x.name == g) + && !unpreviewed.swatch_groups.iter().any(|x| x.name == g) { return Err(format!("no colour group `{g}`")); } diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 5f2a79b9e5..766f47b047 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -2075,6 +2075,28 @@ fn reopening_a_group_over_its_preview_starts_on_the_groups_colours() { dialogs::cancel(&mut app); } +/// Recolor Artwork opened on a colour group over a preview that renames it finds the group by its +/// name without the preview; an unknown group leaves the open dialog as it is. +#[test] +fn reopening_a_group_over_a_preview_that_renames_it_finds_the_group() { + let mut app = app(); + let ctx = context(); + art(&mut app, &["#ff0000", "#0000ff"]); + let before = group_keys(&app, "Brights"); + app.run("ui.recolorDialog", json!({"group": "Brights"})).unwrap(); + dialog_frame(&mut app, &ctx); + set(&mut app, "groupName", json!("Renamed")); + dialog_frame(&mut app, &ctx); + let named = |app: &VectorcraftApp, n: &str| app.session.doc().unwrap().doc.swatch_groups.iter().any(|g| g.name == n); + assert!(named(&app, "Renamed") && !named(&app, "Brights"), "the preview renames the group"); + assert!(app.run("ui.recolorDialog", json!({"group": "Nope"})).is_err()); + assert_eq!(field(&app, "groupName"), json!("Renamed"), "an unknown group leaves the dialog open"); + app.run("ui.recolorDialog", json!({"group": "Brights"})).unwrap(); + assert!(named(&app, "Brights") && !named(&app, "Renamed"), "the preview is rolled back"); + assert_eq!(field(&app, "__assign"), json!(before), "the new dialog starts on the group's colours"); + dialogs::cancel(&mut app); +} + /// Every paint under `v`, in order: its color, the swatch it is linked to and its tint. fn paints_in(v: &Value, out: &mut Vec<(Color, Option, f64)>) { match v { From eaf1c48e5e9476146f3579a1367de0cf710e209b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:13:38 -0800 Subject: [PATCH 062/101] Recolor Artwork: reject a library or group that is not a string ui.recolorDialog, with or without a preset, treated a `library` or `group` of another type as omitted, so a preset opened with no limit and OK could recolor the art without the library that was asked for. Both are now an error that opens no dialog. Null still means none. --- crates/ui-egui/src/dialogs/recolor.rs | 18 ++++++++++++------ crates/ui-egui/src/tests/recolor.rs | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 19657a52ca..682954ac7f 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -199,7 +199,11 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { } let st = app.session.active().ok_or("no document open")?; let art = !st.selection.is_empty(); - let group = p.get("group").and_then(Value::as_str); + let group = match p.get("group") { + None | Some(Value::Null) => None, + Some(Value::String(g)) => Some(g.as_str()), + Some(_) => return Err("`group` must be a colour group name".into()), + }; // The group is looked for in the document without the preview of the dialog this one replaces // (which can rename the group), as that dialog's Cancel below leaves it. let unpreviewed = match &st.interaction { @@ -283,12 +287,14 @@ pub(super) fn library_choices(app: &VectorcraftApp) -> (Vec, Vec (keys, shown) } -/// The `limitTo` key of `ui.recolorDialog`'s `library` (none without it, the first library for ""). +/// The `limitTo` key of `ui.recolorDialog`'s `library` (none without it or for null, the first +/// library for ""); a `library` that is not a string is an error. pub(super) fn library_param(app: &VectorcraftApp, p: &Value) -> Result { - match p.get("library").and_then(Value::as_str) { - Some("") => Ok(first_library(app).unwrap_or_default()), - Some(l) => limit_key(app, l), - None => Ok(String::new()), + match p.get("library") { + Some(Value::String(l)) if l.is_empty() => Ok(first_library(app).unwrap_or_default()), + Some(Value::String(l)) => limit_key(app, l), + None | Some(Value::Null) => Ok(String::new()), + Some(_) => Err("`library` must be a library id or name".into()), } } diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 766f47b047..e618b4e830 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -2097,6 +2097,27 @@ fn reopening_a_group_over_a_preview_that_renames_it_finds_the_group() { dialogs::cancel(&mut app); } +/// A `library` or `group` that is not a string is an error, with or without a preset, and opens +/// no dialog. +#[test] +fn recolor_rejects_a_library_or_group_that_is_not_a_string() { + let mut app = app(); + art(&mut app, &["#ff0000", "#0000ff"]); + for p in [ + json!({"colors": 1, "library": 123}), + json!({"preset": true, "colors": 1, "library": 123}), + json!({"preset": true, "colors": 1, "library": true}), + json!({"group": 5}), + json!({"group": ["Brights"]}), + ] { + assert!(app.run("ui.recolorDialog", p.clone()).is_err(), "{p}"); + assert!(app.ui.dialog.is_none(), "{p} opens no dialog"); + } + app.run("ui.recolorDialog", json!({"colors": 1, "library": null, "group": null})).unwrap(); + assert_eq!(field(&app, "limitTo"), json!(""), "a null library is no limit"); + dialogs::cancel(&mut app); +} + /// Every paint under `v`, in order: its color, the swatch it is linked to and its tint. fn paints_in(v: &Value, out: &mut Vec<(Color, Option, f64)>) { match v { From 2089ca34f79a39307c342a4b43130619b58ef4ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:45:17 -0800 Subject: [PATCH 063/101] Gradient panel: a preset from the Presets menu goes to the proxy in front The Presets menu sent gradient.presets.apply without `stroke`, so the command chose the fill or stroke by the Appearance panel's active row. With a fill row active and the Stroke proxy in front, the preset went to the fill the panel was not showing. The menu now passes the proxy in front, as the panel's other controls do; an active row of that kind still takes the preset. --- crates/ui-egui/src/panels/gradient.rs | 7 +- crates/ui-egui/src/panels/gradient/tests.rs | 85 +++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 90 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 945c18ea0d..4664838728 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -449,8 +449,9 @@ const REPEAT_PRESETS: [f64; 6] = [1.0, 2.0, 3.0, 4.0, 5.0, 10.0]; /// The Presets row: a menu of the preset gradients by library (theme), then the /// saved ones; a choice applies to the gradient behind the active proxy, keeping its placement -/// (`gradient.presets.apply`; a solid or no paint becomes the gradient). The menu shows the preset -/// the gradient is, if any. +/// (`gradient.presets.apply`; a solid or no paint becomes the gradient), as the panel's other +/// controls do: an active Appearance row stands for it only when it is a row of the proxy's kind. +/// The menu shows the preset the gradient is, if any. fn presets_row(app: &mut VectorcraftApp, ui: &mut Ui, g: Option<&GradientPaint>) { let shown = g.and_then(|g| app.session.gradient_preset_name(&g.gradient)).unwrap_or_default(); let enabled = crate::menus::enabled(app, "gradient.presets.apply"); @@ -458,7 +459,7 @@ fn presets_row(app: &mut VectorcraftApp, ui: &mut Ui, g: Option<&GradientPaint>) widgets::dim_label(ui, tl!("Presets:")); let chosen = ui.add_enabled_ui(enabled, |ui| widgets::combo(ui, "grad-presets", &shown, 150.0, |ui| preset_list(app, ui, &shown))).inner; if let Some(name) = chosen { - app.run("gradient.presets.apply", json!({ "name": name })).ok(); + app.run("gradient.presets.apply", json!({ "name": name, "stroke": !app.session.fill_active })).ok(); } }); } diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 1a607b8f24..9bb7903362 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -863,6 +863,91 @@ fn the_presets_menu_applies_a_preset_and_shows_it() { assert_eq!(fill(&app).gradient.stops, preset.stops); } +/// The paints of the selected object's appearance rows, in stack order. +fn row_paints(app: &VectorcraftApp) -> Vec { + let st = app.session.active().unwrap(); + let node = st.doc.node(st.selection.subjects()[0]).unwrap(); + node.appearance.items.iter().map(|i| i.paint().clone()).collect() +} + +/// The indices of the selected object's fill (`fill`) or stroke rows. +fn rows_of_kind(app: &VectorcraftApp, fill: bool) -> Vec { + let st = app.session.active().unwrap(); + let node = st.doc.node(st.selection.subjects()[0]).unwrap(); + node.appearance.items.iter().enumerate().filter(|(_, i)| i.is_fill() == fill).map(|(n, _)| n).collect() +} + +/// A selected rectangle with a gradient fill and a gradient stroke. +fn gradient_fill_and_stroke() -> VectorcraftApp { + let mut app = app(json!({"gradient": {}})); + app.run("paint.setStroke", json!({"gradient": {}, "focus": false})).unwrap(); + app +} + +/// With appearance row `active` active and the Fill (`front_fill`) or Stroke proxy in front, +/// chooses Soft Spectrum from the Presets menu and checks that row `target` takes the preset while +/// every other row keeps its paint. +fn assert_preset_goes_to(mut app: VectorcraftApp, active: usize, front_fill: bool, target: usize) { + let soft = app.session.gradient_preset("Soft Spectrum").unwrap().gradient.stops; + app.run("appearance.setActiveItem", json!({ "index": active })).unwrap(); + let before = row_paints(&app); + let mut p = Panel::new(); + p.frame(&mut app, vec![], Modifiers::NONE); + let proxy = + if front_fill { p.widget("fill-proxy").left_top() + vec2(2.0, 2.0) } else { p.widget("stroke-proxy").right_bottom() - vec2(2.0, 2.0) }; + p.click(&mut app, proxy); + assert_eq!(app.session.fill_active, front_fill); + assert_eq!(app.session.appearance_item(), Some(active), "the row stays active"); + let texts = p.frame(&mut app, vec![], Modifiers::NONE); + let combo = p.widget_after(text_at(&texts, "Presets:").expect("the Presets row")); + let texts = p.click(&mut app, combo.center()); + p.click(&mut app, text_at(&texts, "Soft Spectrum").expect("the preset")); + let after = row_paints(&app); + assert_eq!(after.len(), before.len()); + for (n, (was, now)) in before.iter().zip(&after).enumerate() { + if n == target { + assert!(matches!(now, Paint::Gradient(g) if g.gradient.stops == soft), "row {n} takes the preset: {now:?}"); + } else { + assert_eq!(now, was, "row {n} keeps its paint"); + } + } +} + +/// With a fill row active and the Stroke proxy in front, the Presets menu applies the preset to +/// the stroke. +#[test] +fn the_presets_menu_applies_to_the_stroke_in_front_over_an_active_fill_row() { + let app = gradient_fill_and_stroke(); + let (fill_row, stroke_row) = (rows_of_kind(&app, true)[0], rows_of_kind(&app, false)[0]); + assert_preset_goes_to(app, fill_row, false, stroke_row); +} + +/// With a stroke row active and the Fill proxy in front, the Presets menu applies the preset to +/// the fill. +#[test] +fn the_presets_menu_applies_to_the_fill_in_front_over_an_active_stroke_row() { + let app = gradient_fill_and_stroke(); + let (fill_row, stroke_row) = (rows_of_kind(&app, true)[0], rows_of_kind(&app, false)[0]); + assert_preset_goes_to(app, stroke_row, true, fill_row); +} + +/// With the proxy of the active row's kind in front, the Presets menu applies the preset to the +/// active row, not to the topmost row of that kind. +#[test] +fn the_presets_menu_applies_to_the_active_row_of_the_kind_in_front() { + for fill in [true, false] { + let mut app = gradient_fill_and_stroke(); + app.run(if fill { "appearance.addFill" } else { "appearance.addStroke" }, json!({})).unwrap(); + // Without an active row a solid goes to the topmost row of the kind; the other stays a gradient. + app.run(if fill { "paint.setFill" } else { "paint.setStroke" }, json!({"color": "#ff0000", "focus": false})).unwrap(); + let paints = row_paints(&app); + let rows = rows_of_kind(&app, fill); + assert_eq!(rows.len(), 2); + let lower = rows.into_iter().find(|&n| matches!(paints[n], Paint::Gradient(_))).expect("a gradient row under the solid one"); + assert_preset_goes_to(app, lower, fill, lower); + } +} + /// The panel menu saves the gradient as a preset (named in a dialog), which the Presets menu then /// lists under Saved; Delete Gradient Preset removes it, and Hide Presets leaves the row out. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e84ce63592..83c1cc0f83 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2066,6 +2066,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Escape ends that eyedropper's pick, and Brush Options' Key Color pick, without sampling and returns to the tool that started it; the stop keeps its color, and Brush Options stays open with its Key Color until a new Escape cancels it (#8024, [Modify gradients, archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=264)). Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. + The Gradient panel's Presets menu applies the chosen preset to the fill or stroke behind the proxy in front, as the panel's other controls do. The panel's Fill or Stroke toggle chooses whether the panel edits the fill or the stroke ([Gradient panel options](https://web.archive.org/web/20251006210616/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/gradient-tool-and-panel.html)). As VectorCraft's own rule, an active Appearance panel row takes the preset only when it is a fill row and the Fill proxy is in front, or a stroke row and the Stroke proxy is in front (`panels::gradient` tests `the_presets_menu_applies_to_the_stroke_in_front_over_an_active_fill_row`, `the_presets_menu_applies_to_the_fill_in_front_over_an_active_stroke_row` and `the_presets_menu_applies_to_the_active_row_of_the_kind_in_front`). In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. From a1995ad2b5e69fb231070cadb70496f5d652a9b8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 18:23:28 -0800 Subject: [PATCH 064/101] Gradient panel: name the row and proxy in the Presets menu's docs The doc comment on presets_row and the docs line now say that an active fill row takes the preset with the Fill proxy in front, and an active stroke row with the Stroke proxy in front. The docs line describes the help page's Fill or Stroke control as the page does. --- crates/ui-egui/src/panels/gradient.rs | 3 ++- docs/target-app-parity.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 4664838728..2634f0f5c7 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -450,7 +450,8 @@ const REPEAT_PRESETS: [f64; 6] = [1.0, 2.0, 3.0, 4.0, 5.0, 10.0]; /// The Presets row: a menu of the preset gradients by library (theme), then the /// saved ones; a choice applies to the gradient behind the active proxy, keeping its placement /// (`gradient.presets.apply`; a solid or no paint becomes the gradient), as the panel's other -/// controls do: an active Appearance row stands for it only when it is a row of the proxy's kind. +/// controls do: an active Appearance row takes the preset only when that row is a fill row with the +/// Fill proxy in front, or a stroke row with the Stroke proxy in front. /// The menu shows the preset the gradient is, if any. fn presets_row(app: &mut VectorcraftApp, ui: &mut Ui, g: Option<&GradientPaint>) { let shown = g.and_then(|g| app.session.gradient_preset_name(&g.gradient)).unwrap_or_default(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 83c1cc0f83..3470ceeb96 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2066,7 +2066,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Escape ends that eyedropper's pick, and Brush Options' Key Color pick, without sampling and returns to the tool that started it; the stop keeps its color, and Brush Options stays open with its Key Color until a new Escape cancels it (#8024, [Modify gradients, archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=264)). Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - The Gradient panel's Presets menu applies the chosen preset to the fill or stroke behind the proxy in front, as the panel's other controls do. The panel's Fill or Stroke toggle chooses whether the panel edits the fill or the stroke ([Gradient panel options](https://web.archive.org/web/20251006210616/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/gradient-tool-and-panel.html)). As VectorCraft's own rule, an active Appearance panel row takes the preset only when it is a fill row and the Fill proxy is in front, or a stroke row and the Stroke proxy is in front (`panels::gradient` tests `the_presets_menu_applies_to_the_stroke_in_front_over_an_active_fill_row`, `the_presets_menu_applies_to_the_fill_in_front_over_an_active_stroke_row` and `the_presets_menu_applies_to_the_active_row_of_the_kind_in_front`). + The Gradient panel's Presets menu applies the chosen preset to the fill or stroke behind the proxy in front, as the panel's other controls do. The help page describes a Fill or Stroke control on the Gradient panel that toggles whether the fill or the stroke is being edited ([Gradient panel options](https://web.archive.org/web/20251006210616/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/gradient-tool-and-panel.html)). As VectorCraft's own rule, an active Appearance panel row takes the preset only when it is a fill row and the Fill proxy is in front, or a stroke row and the Stroke proxy is in front (`panels::gradient` tests `the_presets_menu_applies_to_the_stroke_in_front_over_an_active_fill_row`, `the_presets_menu_applies_to_the_fill_in_front_over_an_active_stroke_row` and `the_presets_menu_applies_to_the_active_row_of_the_kind_in_front`). In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. From 9872e6b6795edc3551a655cf4c7af8f9102a5847 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 13:24:32 -0800 Subject: [PATCH 065/101] Scripts: page items report their own members, and lists start with the topmost object Scripts that check a member with hasOwnProperty before using it skipped every page item, because the members live on the class prototype. Now hasOwnProperty and propertyIsEnumerable are true for each member of an object's class that is available, and for-in lists its properties but not its methods. Members that only throw "not available yet" stay false. - An empty selection is an empty list instead of null. - pageItems lists art topmost first, as the CMYKColor example reads the frontmost path as pathItems[0] (https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/). A document's selection lists the selected objects in that order too, whatever order they were picked in. That selection order is VectorCraft's own rule. - A collection read with a name, such as pageItems["Logo"], gives what getByName gives, as https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/ shows. A name nothing has throws Not found, and assigning to such a name throws the same error. - activeDocument, documents and selection can be named without app., as that page describes for the application's members. - move() with the object itself and PLACEBEFORE or PLACEAFTER leaves it where it is and adds no undo step. - move() keeps a compound path whose last path moves out, so a script that holds it can still read it. - Assigning opacity to an object in a hidden or locked layer throws Cannot edit and changes nothing. - name takes a number or a Boolean as its text. - String() of an object gives its class and name, such as [PathItem Logo]. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 162 ++++++-- crates/engine/src/script/mod.rs | 8 +- crates/engine/src/tests/script_dom.rs | 358 +++++++++++++++--- crates/engine/src/tests/script_run.rs | 3 +- .../tests/it/script_host_vs_scriptcheck.rs | 25 +- crates/js/src/builtins.rs | 4 +- crates/js/src/host_classes.rs | 133 ++++++- crates/js/src/host_tests.rs | 41 ++ crates/js/src/interp.rs | 20 +- crates/js/src/realm.rs | 10 + docs/mcp.md | 33 +- docs/target-app-parity.md | 2 +- 12 files changed, 661 insertions(+), 138 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index cb901014b5..bef71437d4 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -13,11 +13,21 @@ //! changed document; a change that changes nothing runs no command. A change to a document that is //! not the active one makes it active for the command and makes the other one active again after. //! +//! Collections are counted from 0, and `pageItems` lists art topmost first, as +//! reads the frontmost path as +//! `pathItems[0]`. A document's selection lists the selected objects in the same order, not in the +//! order they were selected (). +//! A collection read with a name, `pageItems["name"]`, gives the object `getByName` gives, as that +//! page describes, and throws `Not found` when none has the name; `"name" in pageItems` is false then, +//! and assigning to such a name throws the same error. As that page also describes, a script may name +//! `activeDocument`, `documents` and `selection` without `app.`; assigning one of those names makes it +//! a variable of the script's own. +//! //! VectorCraft's own rules, which the help pages do not state: -//! - Collections list documents in tab order and art in paint order (bottom first), counted from 0. -//! `pageItems` lists every object, with the objects inside groups and compound paths after the -//! group or compound path, and leaves out layers and ruler guides. An index out of range gives -//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches. +//! - Collections list documents in tab order. `pageItems` lists every object, with the objects +//! inside groups and compound paths after the group or compound path, and leaves out layers and +//! ruler guides. An index out of range gives `undefined`; `index` and `getByName` throw +//! `Not found` when nothing matches. //! - Script coordinates are points with Y up from the bottom of the first artboard //! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of //! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run. @@ -26,6 +36,8 @@ //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. //! - Members the help pages list that are not here yet throw an error that says so. +//! - Assigning `opacity` to an object in a hidden or locked layer throws `Cannot edit` and changes +//! nothing. An object that is hidden or locked itself, or is in a hidden or locked group, takes it. use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; @@ -206,7 +218,8 @@ fn method(link: &Link, f: Member) -> HostMember { } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document or page item `this` is still there. +/// the check that a document or page item `this` is still there. `hasOwnProperty` is false for it, +/// so a script that checks for the member first skips it. fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); @@ -224,7 +237,7 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM } Err(HostError::Error(message.clone())) }); - (name.to_string(), HostMember::Property { get: f.clone(), set: f }) + (name.to_string(), HostMember::Unavailable(f)) } fn text(s: impl Into) -> Data { @@ -386,14 +399,14 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { } } -/// The ids of a document's page items in paint order ([`State`] keeps the lists of the last -/// documents read). +/// The ids of a document's page items, topmost first, each group or compound path before the +/// objects in it ([`State`] keeps the lists of the last documents read). fn page_items(h: &Host, st: &DocState) -> Rc> { if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) { return ids; } fn walk(nodes: &[Arc], out: &mut Vec) { - for n in nodes { + for n in nodes.iter().rev() { match &n.kind { NodeKind::Layer { children, .. } => walk(children, out), NodeKind::RulerGuide { .. } => {} @@ -742,10 +755,15 @@ fn app_ref(_: &Host, _: &[Data]) -> Answer { Ok(host_ref("Application", &[])) } +/// `documents[i]`, and `documents["name"]` as `getByName` reads it. fn docs_at(h: &Host, a: &[Data]) -> Answer { let s = h.session.borrow(); let at = match arg(a, 1) { Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)), + Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) { + None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())), + found => found, + }, _ => None, }; Ok(at.map_or(Data::Undefined, |st| doc_ref(h, st.uid))) @@ -1214,18 +1232,22 @@ fn doc_selection(h: &Host, a: &[Data]) -> Answer { selection_of(h, doc.uid) } -/// The selection of the document `uid`: `null` when nothing is selected, otherwise a new list of -/// the selected objects. +/// The selection of the document `uid`: a new list of the selected objects, topmost first as +/// `pageItems` lists them, empty when nothing is selected. fn selection_of(h: &Host, uid: u64) -> Answer { let s = h.session.borrow(); let st = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - let ids: Vec = st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect(); - if ids.is_empty() { - return Ok(Data::Null); - } - if ids.len() > MAX_LISTED { + let picked: HashSet = st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect(); + if picked.len() > MAX_LISTED { return Err(HostError::Range(format!("the selection has more than {MAX_LISTED} objects"))); } + let ids: Vec = if picked.is_empty() { + Vec::new() + } else { + let all = page_items(h, st); + h.charge_call(all.len() as u64)?; + all.iter().copied().filter(|i| picked.contains(i)).collect() + }; h.charge_call(16 * ids.len() as u64)?; Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) } @@ -1320,8 +1342,21 @@ fn items_parent(h: &Host, a: &[Data]) -> Answer { Ok(doc_ref(h, doc.uid)) } +/// Whether an indexer was called for `name in collection` ([`vectorcraft_js::HostClass::index`]), +/// where a name nothing has gives `undefined` instead of the `Not found` error a read throws. +fn probing(a: &[Data]) -> bool { + matches!(arg(a, 2), Data::Bool(true)) +} + +/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. fn items_at(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; + if let Data::String(_) = arg(a, 1) { + return match items_by_name(h, a) { + Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), + r => r, + }; + } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) @@ -1418,8 +1453,15 @@ fn set_props(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Node) -> Ok(Data::Undefined) } +/// `name = value`: a number or a Boolean becomes the text `String(value)` gives. fn item_set_name(h: &Host, a: &[Data]) -> Answer { - let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("name must be a string".into())) }; + let name = match arg(a, 1) { + Data::String(s) => s.clone(), + Data::Number(n) => vectorcraft_js::number_to_string(*n), + Data::Bool(b) => b.to_string(), + _ => return Err(HostError::Type("name must be a string".into())), + }; + let name = &name; if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } @@ -1479,6 +1521,14 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still // replaces the one the graph keeps for its series or kind. let item = this_item(h, a)?; + let refused = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked)); + d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item")) + }); + if let Some(name) = refused { + return Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))); + } let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0)); let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v); set_props(h, a, |_| false, json!({"opacity": v})) @@ -1693,9 +1743,9 @@ struct Destination { } /// The object a relative object of `move` or `duplicate` names: a page item or a layer of the -/// same document as `item`. A copy (`copy`) may go directly above or below `item` itself, as -/// `layer.move` puts copies. -fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result { +/// same document as `item`. An object may go directly above or below itself: a copy goes there, as +/// `layer.move` puts copies, and a move there leaves the object where it is. +fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result { let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); @@ -1714,7 +1764,7 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s let d = &st.doc; let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let inside = d.ancestry(target).is_some_and(|a| a.iter().any(|i| *i == item.id && *i != target)); - if inside || (target == item.id && !(copy && beside)) { + if inside || (target == item.id && !beside) { return Err(HostError::Error("an object cannot go into itself".into())); } let (parent, beside) = match how { @@ -1776,27 +1826,16 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul /// `move(relativeObject, insertionLocation?)`: moves the item into or beside `relativeObject`, a /// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`). An /// object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard -/// is refused. +/// is refused. Moving an object directly above or below itself leaves it where it is, and a compound +/// path whose last path moves out stays, empty. fn item_move(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; if matches!(arg(a, 1), Data::Undefined) { return Err(HostError::Type("move needs a relative object".into())); } - let to = destination(h, item, arg(a, 1), arg(a, 2), false)?; - // When the last path leaves a compound path, the compound path is deleted in the same step - // rather than left empty. - let emptied = with_doc(h, item.doc, |_, st| { - let parent = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p))?; - (matches!(parent.kind, NodeKind::Compound { .. }) && parent.children().is_some_and(|c| c.len() == 1) && parent.id != to.parent) - .then_some(parent.id) - }); - match emptied { - None => place(h, item.doc, item.id, &to)?, - Some(compound) => atomically(h, |h| { - place(h, item.doc, item.id, &to)?; - on_doc(h, item.doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": [compound.0]})))?; - Ok(()) - })?, + let to = destination(h, item, arg(a, 1), arg(a, 2))?; + if to.beside != Some(item.id) { + place(h, item.doc, item.id, &to)?; } Ok(arg(a, 0).clone()) } @@ -1835,7 +1874,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { } None } - target => Some(destination(h, item, target, arg(a, 2), true)?), + target => Some(destination(h, item, target, arg(a, 2))?), }; let id = atomically(h, |h| { let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?; @@ -1894,6 +1933,31 @@ fn layer_typename(h: &Host, a: &[Data]) -> Answer { Ok(text("Layer")) } +/// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name. +fn named_text(class: &str, name: Answer) -> Answer { + match name? { + Data::String(n) => Ok(text(format!("[{class} {n}]"))), + _ => Ok(text(format!("[{class} ]"))), + } +} + +fn item_to_string(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(format!("[{} {}]", typename(n).unwrap_or("PageItem"), n.name.as_deref().unwrap_or(""))))) +} + +fn doc_to_string(h: &Host, a: &[Data]) -> Answer { + named_text("Document", doc_name(h, a)) +} + +fn layer_to_string(h: &Host, a: &[Data]) -> Answer { + named_text("Layer", layer_name(h, a)) +} + +/// `toString()` of an object without a name: `[Class]`. +fn class_text(name: &'static str) -> HostMember { + HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]"))))) +} + fn typename_of(name: &'static str) -> HostMember { HostMember::Get(Rc::new(move |_| Ok(text(name)))) } @@ -1948,6 +2012,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", get(l, app_selection)), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), + ("toString", class_text("Application")), ]); application.push(later(l, "Application", "beep")); let preset = { @@ -1957,7 +2022,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), h.charge_call(64)?; new_preset(&h) }); - let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"))]; + let mut members = vec![("typename".to_string(), typename_of("DocumentPreset")), ("toString".to_string(), class_text("DocumentPreset"))]; members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k)))); HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) } }; @@ -1975,6 +2040,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("getByName", method(l, docs_by_name)), ("add", method(l, docs_add)), ("addDocument", method(l, docs_add_document)), + ("toString", class_text("Documents")), ]), Some(function(l, docs_at)), ), @@ -1991,6 +2057,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("convertCoordinate", method(l, doc_convert)), ("pageItems", get(l, doc_page_items)), ("selection", property(l, doc_selection, doc_set_selection)), + ("toString", method(l, doc_to_string)), ]); document.extend( ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] @@ -2008,6 +2075,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("index", method(l, items_index)), ("getByName", method(l, items_by_name)), ("removeAll", method(l, items_remove_all)), + ("toString", class_text("PageItems")), ]), Some(function(l, items_at)), )); @@ -2034,6 +2102,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("move", method(l, item_move)), ("remove", method(l, item_remove)), ("zOrder", method(l, item_z_order)), + ("toString", method(l, item_to_string)), ]); page_item.extend( [ @@ -2061,8 +2130,19 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ); classes.push(class("PageItem", None, page_item, None)); classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); - classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); - realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) + classes.push(class( + "Layer", + None, + named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]), + None, + )); + realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?; + // The application's members a script may name without `app.`. + realm.define_host_globals(vec![ + ("activeDocument".into(), function(l, app_active)), + ("documents".into(), function(l, app_documents)), + ("selection".into(), function(l, app_selection)), + ]) } #[cfg(test)] diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index affacab584..c162f5e010 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1583,16 +1583,10 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { /// program. A message the script supplied itself ([`RunError::authored`]) is given as it is. fn explained(e: &RunError) -> String { const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"]; - const APP_MEMBERS: &[&str] = &["activeDocument", "documents", "selection"]; let message = &e.message; let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next()); let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f)); - if e.kind == RunErrorKind::Thrown - && !e.authored - && let Some(member) = first.filter(|f| APP_MEMBERS.contains(f)) - { - format!("{message} (use `app.{member}`)") - } else if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object { + if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object { format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)") } else { message.to_string() diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 60e3a71521..8d015d8727 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -82,14 +82,15 @@ fn page_items_are_live_and_typed_for_all_node_kinds() { "var p = app.activeDocument.pageItems, t = [];\ for (var i = 0; i < p.length; i++) t.push(p[i].typename);\ vc.log(t.join(','));\ - vc.log(p[1].parent.typename); vc.log(p[0].parent.typename); vc.log(p.parent.typename);\ - p[3].remove(); vc.log(p.length); vc.log(p[-1] === undefined && p[1.5] === undefined && p[99] === undefined);\ - vc.log(p[1] instanceof PathItem && p[1] instanceof PageItem);", + vc.log(p[3].parent.typename); vc.log(p[0].parent.typename); vc.log(p.parent.typename);\ + p[1].remove(); vc.log(p.length); vc.log(p[-1] === undefined && p[1.5] === undefined && p[99] === undefined);\ + vc.log(p[2] instanceof PathItem && p[2] instanceof PageItem);", ); + // Topmost first, each group before the objects in it. assert_eq!( out, vec![ - json!("GroupItem,PathItem,PathItem,PathItem,TextFrame"), + json!("TextFrame,PathItem,GroupItem,PathItem,PathItem"), json!("GroupItem"), json!("Layer"), json!("Document"), @@ -120,7 +121,7 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { let (mut s, _, _) = doc(); let out = log( &mut s, - "var i = app.activeDocument.pageItems[0];\ + "var i = app.activeDocument.pageItems[1];\ vc.log(i.geometricBounds); vc.log(i.position); vc.log([i.left, i.top, i.width, i.height]);\ app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; vc.log(i.position);\ app.coordinateSystem = CoordinateSystem.DOCUMENTCOORDINATESYSTEM;\ @@ -198,7 +199,7 @@ fn page_item_properties_join_one_undo_step() { let steps = undo_steps(&s); let out = log( &mut s, - "var i = app.activeDocument.pageItems[0];\ + "var i = app.activeDocument.pageItems[1];\ i.name = 'box'; i.opacity = 40; i.locked = true; i.locked = false; i.hidden = true; i.hidden = false;\ vc.log([i.name, i.opacity, i.locked, i.hidden, i.editable, i.zOrderPosition]);\ vc.log(app.activeDocument.pageItems.getByName('box').name);", @@ -209,7 +210,7 @@ fn page_item_properties_join_one_undo_step() { assert_eq!((n.name.as_deref(), (n.opacity * 100.0).round()), (Some("box"), 40.0)); assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); let steps = undo_steps(&s); - log(&mut s, "var i = app.activeDocument.pageItems[0]; i.name = 'box'; i.opacity = 40; i.hidden = false;"); + log(&mut s, "var i = app.activeDocument.pageItems[1]; i.name = 'box'; i.opacity = 40; i.hidden = false;"); assert_eq!(undo_steps(&s), steps, "values that change nothing add no step"); for (source, part) in [ ("app.activeDocument.pageItems[0].opacity = 101;", "opacity"), @@ -251,7 +252,7 @@ fn assigning_the_reported_opacity_changes_nothing() { let (mut s, a, _) = doc(); s.execute("object.setProps", &json!({"id": a.0, "opacity": 100.0 / 3.0})).unwrap(); let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); - let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; vc.log(i.opacity); i.opacity = i.opacity;"); + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.opacity); i.opacity = i.opacity;"); assert_eq!(out, vec![json!(33.3333)]); assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); assert_eq!(undo_steps(&s), steps); @@ -267,10 +268,10 @@ fn selection_assignment_is_atomic_across_invalid_items() { s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); let out = log( &mut s, - "var d = app.activeDocument, p = d.pageItems; vc.log(d.selection === null);\ + "var d = app.activeDocument, p = d.pageItems; vc.log(d.selection instanceof Array && d.selection.length === 0);\ d.selection = [p[1], p[0], p[1]]; vc.log(d.selection.length); vc.log(app.selection[0].selected);\ p[0].selected = false; vc.log(d.selection.length);\ - d.selection = p[0]; vc.log(d.selection.length);", + d.selection = p[1]; vc.log(d.selection.length);", ); assert_eq!(out, vec![json!(true), json!(2), json!(true), json!(1), json!(1)]); assert_eq!(s.active().unwrap().selection.objects, vec![a]); @@ -288,14 +289,14 @@ fn a_guide_path_is_not_selected_while_guides_are_locked() { s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); // The assignment and `selected` refuse the guide path, and the selection stays as it was. - for source in ["app.activeDocument.selection = app.activeDocument.pageItems[0];", "app.activeDocument.pageItems[0].selected = true;"] { + for source in ["app.activeDocument.selection = app.activeDocument.pageItems[1];", "app.activeDocument.pageItems[1].selected = true;"] { let e = failure(&mut s, source); assert!(e.contains(&format!("Cannot select PathItem {}", a.0)), "{source}: {e}"); assert_eq!(s.active().unwrap().selection.objects, vec![b], "{source}"); } // With the guides unlocked, the guide path is selected. s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); - log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[0];"); + log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[1];"); assert_eq!(s.active().unwrap().selection.objects, vec![a]); } @@ -303,7 +304,7 @@ fn a_guide_path_is_not_selected_while_guides_are_locked() { fn an_inactive_document_changes_without_switching_tabs() { let (mut s, a, _) = doc(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); - log(&mut s, "var d = app.documents[0]; d.pageItems[0].name = 'far'; d.selection = d.pageItems[1];"); + log(&mut s, "var d = app.documents[0]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];"); assert_eq!(s.active_index(), Some(1)); let first = &s.documents()[0]; assert_eq!(first.doc.node(a).unwrap().name.as_deref(), Some("far")); @@ -315,7 +316,7 @@ fn move_duplicate_and_zorder_obey_parent_order() { let (mut s, a, b) = doc(); let out = log( &mut s, - "var p = app.activeDocument.pageItems, first = p[0];\ + "var p = app.activeDocument.pageItems, first = p[1];\ first.zOrder(ZOrderMethod.BRINGTOFRONT); vc.log(first.zOrderPosition);\ var c = first.duplicate(); vc.log(c.zOrderPosition); vc.log(p.length); vc.log(app.activeDocument.selection.length);\ c.zOrder(ZOrderMethod.SENDTOBACK); vc.log(c.zOrderPosition);", @@ -341,31 +342,31 @@ fn move_and_duplicate_place_by_element_placement() { let steps = undo_steps(&s); // Before puts it directly above the relative object, after directly below. let r = - log(&mut s, "var p = app.activeDocument.pageItems; var a = p[0], c = p[2]; vc.log(a.move(c, ElementPlacement.PLACEBEFORE) === undefined);"); + log(&mut s, "var p = app.activeDocument.pageItems; var a = p[2], c = p[0]; vc.log(a.move(c, ElementPlacement.PLACEBEFORE) === undefined);"); assert_eq!(r, vec![json!(false)]); assert_eq!(layer_order(&s), [b, c, a]); - log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[0], ElementPlacement.PLACEAFTER);"); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[2], ElementPlacement.PLACEAFTER);"); assert_eq!(layer_order(&s), [a, b, c]); // At the end of a container is under its contents, at the beginning on top. - log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[0].parent, ElementPlacement.PLACEATEND);"); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[0].parent, ElementPlacement.PLACEATEND);"); assert_eq!(layer_order(&s), [c, a, b]); - log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[0].parent, ElementPlacement.PLACEATBEGINNING);"); + log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[2].parent, ElementPlacement.PLACEATBEGINNING);"); assert_eq!(layer_order(&s), [a, b, c]); assert_eq!(undo_steps(&s), steps + 4, "one step for each run that changed the order"); // Moving to where it is runs nothing. let steps = undo_steps(&s); - log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[1], ElementPlacement.PLACEBEFORE);"); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.PLACEBEFORE);"); assert_eq!(undo_steps(&s), steps); // Into a group, and a copy beside an object. s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); s.execute("select.none", &json!({})).unwrap(); - log(&mut s, "var p = app.activeDocument.pageItems; p[3].move(p[0], ElementPlacement.INSIDE);"); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.INSIDE);"); let inside: Vec = s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect(); assert_eq!(inside, [a, b, c]); let out = log( &mut s, - "var g = app.activeDocument.pageItems[0], a = app.activeDocument.pageItems[1];\ + "var g = app.activeDocument.pageItems[0], a = app.activeDocument.pageItems[3];\ var copy = a.duplicate(g, ElementPlacement.PLACEATEND); vc.log(copy.parent.typename); vc.log(copy.zOrderPosition);", ); assert_eq!(out, vec![json!("GroupItem"), json!(1)]); @@ -387,7 +388,7 @@ fn move_and_duplicate_place_by_element_placement() { // A locked group takes nothing. s.execute("object.setProps", &json!({"ids": [g.0], "locked": true})).unwrap(); rect(&mut s, 0.0, 0.0, 5.0, 5.0); - let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[p.length - 1].move(p[0], ElementPlacement.INSIDE);"); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.INSIDE);"); assert!(e.contains("hidden or locked"), "{e}"); } @@ -396,17 +397,21 @@ fn a_copy_goes_beside_its_source() { let (mut s, a, b) = doc(); let out = log( &mut s, - "var a = app.activeDocument.pageItems[0], c = a.duplicate(a, ElementPlacement.PLACEAFTER);\ + "var a = app.activeDocument.pageItems[1], c = a.duplicate(a, ElementPlacement.PLACEAFTER);\ vc.log([c.zOrderPosition, a.zOrderPosition]);", ); assert_eq!(out, vec![json!([1, 2])]); let order = layer_order(&s); assert_eq!(order[1..], [a, b]); - // An object cannot go beside itself, and a copy cannot go into its source. - assert!(failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1], ElementPlacement.PLACEAFTER);").contains("into itself")); + // An object moved directly above or below itself stays where it is with no undo step, and it + // cannot go into itself; a copy cannot go into its source. + let (order, steps) = (layer_order(&s), undo_steps(&s)); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1], ElementPlacement.PLACEAFTER); p[0].move(p[0], ElementPlacement.PLACEBEFORE);"); + assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps)); + assert!(failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1], ElementPlacement.PLACEATBEGINNING);").contains("into itself")); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.group", &json!({})).unwrap(); - let e = failure(&mut s, "var p = app.activeDocument.pageItems, g = p[1]; g.duplicate(g, ElementPlacement.INSIDE);"); + let e = failure(&mut s, "var p = app.activeDocument.pageItems, g = p[0]; g.duplicate(g, ElementPlacement.INSIDE);"); assert!(e.contains("into itself"), "{e}"); } @@ -425,7 +430,7 @@ fn a_copy_that_cannot_be_placed_is_deleted() { // A Live Paint group takes no type, so the copy is refused after it was made. let out = log( &mut s, - "var p = app.activeDocument.pageItems, n = p.length, g = p[0], t = p[n - 1], m = '';\ + "var p = app.activeDocument.pageItems, n = p.length, g = p[1], t = p[0], m = '';\ try { t.duplicate(g, ElementPlacement.INSIDE); } catch (e) { m = e.message; }\ vc.log(m); vc.log(p.length === n);", ); @@ -489,7 +494,7 @@ fn a_path_inside_a_compound_path_is_not_reordered() { } #[test] -fn moving_the_last_path_out_of_a_compound_path_deletes_the_compound_path() { +fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.compoundPath.make", &json!({})).unwrap(); @@ -498,16 +503,16 @@ fn moving_the_last_path_out_of_a_compound_path_deletes_the_compound_path() { let steps = undo_steps(&s); let out = log( &mut s, - "var d = app.activeDocument, c = d.pageItems[0], m = [d.pageItems[1], d.pageItems[2]];\ + "var d = app.activeDocument, c = d.pageItems[0], m = [d.pageItems[2], d.pageItems[1]];\ m[0].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\ m[1].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\ - try { c.name; } catch (e) { vc.log(e.message); }", + vc.log([c.typename, c === d.pageItems[2]]);", ); - assert_eq!(out, vec![json!(3), json!(2), json!("Stale page item")]); + assert_eq!(out, vec![json!(3), json!(3), json!(["CompoundPathItem", true])]); let doc = &s.active().unwrap().doc; - assert!(doc.node(compound).is_none(), "the empty compound path is deleted"); + assert!(doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); // Each path went directly above the compound path, the second above the first. - assert_eq!(layer_order(&s), [b, a]); + assert_eq!(layer_order(&s), [compound, b, a]); assert!([a, b].iter().all(|id| doc.parent_of(*id) == Some(layer))); assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); } @@ -612,9 +617,9 @@ fn stale_documents_throw_on_every_member() { fn hiding_or_locking_a_selected_item_deselects_it() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); - log(&mut s, "app.activeDocument.pageItems[0].hidden = true;"); + log(&mut s, "app.activeDocument.pageItems[1].hidden = true;"); assert_eq!(s.active().unwrap().selection.objects, vec![b]); - log(&mut s, "app.activeDocument.pageItems[1].locked = true;"); + log(&mut s, "app.activeDocument.pageItems[0].locked = true;"); assert!(s.active().unwrap().selection.objects.is_empty()); } @@ -648,7 +653,7 @@ fn assigning_the_selection_clears_a_layers_panel_target() { let (mut s, a, _) = doc(); s.execute("layer.target", &json!({"id": a.0})).unwrap(); assert_eq!(s.active().unwrap().selection.target, Some(a)); - log(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[0];"); + log(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[1];"); let sel = &s.active().unwrap().selection; assert_eq!((sel.objects.clone(), sel.target), (vec![a], None)); } @@ -694,7 +699,7 @@ fn an_edit_keeps_the_current_layer() { log(&mut s, "app.activeDocument.pageItems[0].left = 70;"); assert_eq!(layer(&s), (Some(back), vec![first])); // Assigning the selection makes the layer of the selected object current, as a click does. - log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[0];"); + log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[1];"); assert_eq!(s.active().unwrap().active_layer, Some(first)); assert_eq!(s.active().unwrap().selection.objects, vec![a]); } @@ -817,7 +822,7 @@ fn assigning_the_same_objects_clears_the_key_and_guides() { s.execute("select.key", &json!({"id": b.0})).unwrap(); s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); assert!(!s.active().unwrap().selection.guides.is_empty()); - log(&mut s, "var d = app.activeDocument; d.selection = [d.pageItems[0], d.pageItems[1]];"); + log(&mut s, "var d = app.activeDocument; d.selection = [d.pageItems[1], d.pageItems[0]];"); let sel = &s.active().unwrap().selection; assert_eq!((sel.objects.clone(), sel.key, sel.guides.len()), (vec![a, b], None, 0)); s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); @@ -865,7 +870,7 @@ fn the_same_document_or_item_is_the_same_object() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems;\ - vc.log([d === app.documents[0], p[0] === p[0], p[0] === d.selection[0], p[0] !== p[1], p === d.pageItems]);", + vc.log([d === app.documents[0], p[1] === p[1], p[1] === d.selection[0], p[0] !== p[1], p === d.pageItems]);", ); assert_eq!(out, vec![json!([true, true, true, true, true])]); } @@ -903,11 +908,11 @@ fn placement_in_another_document_is_refused() { fn note_is_the_attributes_note() { let (mut s, a, _) = doc(); let steps = undo_steps(&s); - let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; vc.log(i.note); i.note = 'check bleed'; vc.log(i.note);"); + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.note); i.note = 'check bleed'; vc.log(i.note);"); assert_eq!(out, vec![json!(""), json!("check bleed")]); assert_eq!(s.active().unwrap().doc.node(a).unwrap().extras().attrs.as_ref().unwrap().note, "check bleed"); assert_eq!(undo_steps(&s), steps + 1); - log(&mut s, "app.activeDocument.pageItems[0].note = 'check bleed';"); + log(&mut s, "app.activeDocument.pageItems[1].note = 'check bleed';"); assert_eq!(undo_steps(&s), steps + 1, "the same note adds no step"); assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = 5;").contains("note must be a string")); assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long")); @@ -1135,7 +1140,7 @@ fn remove_refuses_hidden_or_locked_art_as_remove_all_does() { (json!({"ids": [b.0], "visible": false}), json!({"ids": [b.0], "visible": true})), ] { s.execute("object.setProps", &on).unwrap(); - let e = failure(&mut s, "app.activeDocument.pageItems[1].remove();"); + let e = failure(&mut s, "app.activeDocument.pageItems[0].remove();"); assert!(e.contains(&format!("cannot delete hidden or locked objects: {}", b.0)), "{on}: {e}"); assert!(s.active().unwrap().doc.node(b).is_some(), "{on}"); s.execute("object.setProps", &off).unwrap(); @@ -1180,7 +1185,7 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(undo_steps(&s), steps); // `editable` is false for art on the locked artboard and true for art on the unlocked one. let editable = "var p = app.activeDocument.pageItems; vc.log([p[0].editable, p[1].editable, p[2].editable]);"; - assert_eq!(log(&mut s, editable), vec![json!([false, false, true])]); + assert_eq!(log(&mut s, editable), vec![json!([true, false, false])]); lock(&mut s, false); assert_eq!(log(&mut s, editable), vec![json!([true, true, true])]); let out = log(&mut s, "var p = app.activeDocument.pageItems; p[1].remove(); p.removeAll(); vc.log(p.length);"); @@ -1199,17 +1204,17 @@ fn move_and_duplicate_refuse_art_on_a_locked_artboard() { }; lock(&mut s, true); let (order, steps) = (layer_order(&s), undo_steps(&s)); - let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.PLACEBEFORE);"); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[0], ElementPlacement.PLACEBEFORE);"); assert!(e.contains(&format!("Cannot move PathItem {}", a.0)), "{e}"); assert_eq!((layer_order(&s), undo_steps(&s)), (order.clone(), steps)); // `duplicate` refuses it too, with or without a relative object. - for source in ["app.activeDocument.pageItems[0].duplicate();", "var p = app.activeDocument.pageItems; p[0].duplicate(p[1]);"] { + for source in ["app.activeDocument.pageItems[1].duplicate();", "var p = app.activeDocument.pageItems; p[1].duplicate(p[0]);"] { let e = failure(&mut s, source); assert!(e.contains(&format!("Cannot duplicate PathItem {}", a.0)), "{source}: {e}"); } assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps)); lock(&mut s, false); - log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.PLACEBEFORE);"); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[0], ElementPlacement.PLACEBEFORE);"); assert_eq!(layer_order(&s), [b, a]); } @@ -1223,14 +1228,14 @@ fn duplicate_refuses_hidden_or_locked_art() { s.execute("object.setProps", &on).unwrap(); let (order, steps) = (layer_order(&s), undo_steps(&s)); // With no argument and with a relative object. - for source in ["app.activeDocument.pageItems[1].duplicate();", "var p = app.activeDocument.pageItems; p[1].duplicate(p[0]);"] { + for source in ["app.activeDocument.pageItems[0].duplicate();", "var p = app.activeDocument.pageItems; p[0].duplicate(p[1]);"] { let e = failure(&mut s, source); assert!(e.contains(&format!("Cannot duplicate PathItem {}", b.0)), "{on} {source}: {e}"); } assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps), "{on}"); s.execute("object.setProps", &off).unwrap(); } - log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); let order = layer_order(&s); assert_eq!(order.len(), 3); assert!(order.contains(&a) && order.contains(&b)); @@ -1319,3 +1324,260 @@ fn unsupported_members_say_so() { let (mut s, _, _) = doc(); assert!(failure(&mut s, "app.activeDocument.layers;").contains("Document.layers is not available yet")); } + +/// A script that lowers each selected object's opacity by 10 points, checking each member with +/// `hasOwnProperty` and the selection's `length` first, as scripts written for the object model do. +const LOWER_OPACITY: &str = "\ + var doc = app.activeDocument;\ + var sel = doc.selection;\ + if (sel.length === 0) { alert('Nothing selected.'); }\ + else {\ + var done = 0;\ + for (var i = 0; i < sel.length; i++) {\ + var item = sel[i];\ + if (item.hasOwnProperty('opacity') && typeof item.opacity === 'number') {\ + item.opacity = Math.max(0, item.opacity - 10);\ + done++;\ + }\ + if (item.hasOwnProperty('blendingMode')) { item.blendingMode; }\ + }\ + if (done === 0) { alert('No object with an opacity.'); }\ + }"; + +#[test] +fn a_script_that_checks_has_own_property_changes_every_kind_of_selected_object() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let path = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let (g1, g2) = (rect(&mut s, 50.0, 10.0, 20.0, 20.0), rect(&mut s, 80.0, 10.0, 20.0, 20.0)); + s.execute("select.set", &json!({"ids": [g1.0, g2.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let text = NodeId(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let (c1, c2) = (rect(&mut s, 150.0, 10.0, 20.0, 20.0), rect(&mut s, 155.0, 15.0, 20.0, 20.0)); + s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.active().unwrap().selection.objects[0]; + s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 55})).unwrap(); + s.execute("object.setProps", &json!({"ids": [text.0], "opacity": 5})).unwrap(); + let objects = [path, group, text, compound]; + s.execute("select.set", &json!({"ids": objects.iter().map(|n| n.0).collect::>()})).unwrap(); + let opacities = |s: &Session| -> Vec { + let d = &s.active().unwrap().doc; + objects.iter().map(|n| (f64::from(d.node(*n).unwrap().opacity) * 1000.0).round() / 10.0).collect() + }; + let before = opacities(&s); + let steps = undo_steps(&s); + // The run shows no alert: without an answer for one, it would stop there. + let r = run(&mut s, LOWER_OPACITY).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["dialogs"], json!([]), "{r}"); + assert_eq!(opacities(&s), vec![90.0, 45.0, 0.0, 90.0]); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(opacities(&s), before); +} + +#[test] +fn the_selection_is_an_empty_list_when_nothing_is_selected() { + let (mut s, _, _) = doc(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + let out = log(&mut s, "var d = app.activeDocument; vc.log([d.selection instanceof Array, d.selection.length, app.selection.length]);"); + assert_eq!(out, vec![json!([true, 0, 0])]); + let steps = undo_steps(&s); + let r = s.execute("script.run", &json!({"source": LOWER_OPACITY, "name": "t.js", "answers": [{"kind": "alert", "value": "ok"}]})).unwrap(); + assert_eq!(r["dialogs"][0]["message"], json!("Nothing selected."), "{r}"); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn page_items_report_their_available_members_as_their_own() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems[0], d = app.activeDocument, keys = [];\ + for (var k in p) keys.push(k);\ + vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\ + Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\ + app.hasOwnProperty('activeDocument')]);\ + vc.log([p.hasOwnProperty('blendingMode'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ + p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ + vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('blendingMode')]);", + ); + assert_eq!(out[0], json!([true, true, true, true, true, true, true])); + // Members that are not available yet, unknown names and inherited ones are not the object's own. + assert_eq!(out[1], json!([false, false, false, false, false, false])); + // `for`-`in` lists the properties, not the methods or the members that are not available yet. + assert_eq!(out[2], json!([true, true, -1, -1])); +} + +/// A name a page item class's prototype has, such as `constructor`, or that a script tries to put on +/// the prototype, is not an object's own. +#[test] +fn a_property_added_to_a_class_prototype_is_not_an_objects_own() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems[0]; PathItem.prototype.foo = 1; PageItem.prototype.bar = 2;\ + vc.log([p.hasOwnProperty('foo'), p.hasOwnProperty('bar'), p.propertyIsEnumerable('foo'), p.hasOwnProperty('constructor')]);", + ); + assert_eq!(out, vec![json!([false, false, false, false])]); +} + +/// Reading every property `for`-`in` lists calls each getter, and each call counts against the run: +/// a loop of such reads ends at `maxFuel` and at `script.stop`. +#[test] +fn reading_every_listed_property_is_charged_and_can_be_stopped() { + let (mut s, _, _) = doc(); + let mut calls = |body: &str| { + let source = format!("var p = app.activeDocument.pageItems[0], n = 0; for (var k in p) {{ {body} n++; }} vc.log(n);"); + let r = run(&mut s, &source).unwrap_or_else(|e| panic!("{e}")); + (r["hostCalls"].as_u64().unwrap(), r["log"][0].as_u64().unwrap()) + }; + let (listed, n) = calls(""); + let (read, m) = calls("p[k];"); + assert_eq!(n, m); + assert!(n > 10, "{n} properties"); + assert!(read >= listed + n, "{listed} host calls to list, {read} to read {n} properties"); + let spin = "var p = app.activeDocument.pageItems[0]; while (true) for (var k in p) p[k];"; + let e = s.execute("script.run", &json!({"source": spin, "name": "t.js", "maxFuel": 200_000})).unwrap_err(); + assert!(e.to_string().ends_with("(limit)"), "{e}"); + s.script_frames = true; + assert_eq!(run(&mut s, spin).unwrap()["running"], true); + assert!(s.script_pump().is_none()); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert!(s.script_pump().unwrap().is_err()); + assert!(!s.script_running()); +} + +/// `pageItems` lists art topmost first, and the selection lists the selected objects in that +/// order whatever order they were selected in. +#[test] +fn page_items_and_the_selection_list_the_topmost_object_first() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "bottom"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "top"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + assert_eq!(s.active().unwrap().selection.objects, vec![a, b], "picked bottom first"); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log([d.pageItems[0].name, d.pageItems[1].name, d.selection[0].name, d.selection[1].name]);\ + d.selection = [d.pageItems[1], d.pageItems[0]]; vc.log(d.selection[0].name);", + ); + assert_eq!(out, vec![json!(["top", "bottom", "top", "bottom"]), json!("top")]); +} + +/// A collection read with a name gives what `getByName` gives, and throws as it does for no match. +#[test] +fn a_collection_read_with_a_name_gives_the_named_object() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "n"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, m = [];\ + vc.log([p['n'] === p.getByName('n'), p['n'].name, 'n' in p, 'nosuch' in p, p['length'] === p.length]);\ + vc.log([app.documents[d.name] === d, d.name in app.documents, 'nosuch' in app.documents]);\ + try { p['nosuch']; } catch (e) { m.push(e.message); }\ + try { app.documents.nosuch; } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); +} + +/// `opacity` on an object in a hidden or locked layer throws and the run changes nothing; an object +/// that is hidden or locked itself takes it. +#[test] +fn opacity_refuses_art_in_a_hidden_or_locked_layer() { + let (mut s, a, b) = doc(); + let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + for (id, name) in [(a, "locked"), (b, "free"), (c, "closed")] { + s.execute("object.setProps", &json!({"ids": [id.0], "name": name})).unwrap(); + } + for (on, off) in [ + (json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})), + (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), + ] { + s.execute("object.setProps", &on).unwrap(); + let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + // The change made before the refusal is put back with the rest of the run. + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.getByName('free').opacity = 20; p.getByName('closed').opacity = 50;"); + assert!(e.contains(&format!("Cannot edit PathItem {}", c.0)), "{on}: {e}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{on}"); + assert_eq!(undo_steps(&s), steps, "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "visible": false})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems; p.getByName('locked').opacity = 50; p.getByName('free').opacity = 40;\ + vc.log([p.getByName('locked').opacity, p.getByName('free').opacity]);", + ); + assert_eq!(out, vec![json!([50, 40])]); +} + +/// `name` takes a number or a Boolean as the text `String` gives it, and nothing else. +#[test] +fn a_name_given_as_a_number_or_a_boolean_becomes_its_text() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[1]; i.name = 5; vc.log([typeof i.name, i.name]); i.name = 2.5e-7; vc.log(i.name);\ + i.name = true; vc.log(i.name);", + ); + assert_eq!(out, vec![json!(["string", "5"]), json!("2.5e-7"), json!("true")]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().name.as_deref(), Some("true")); + for value in ["null", "undefined", "{}"] { + assert!(failure(&mut s, &format!("app.activeDocument.pageItems[1].name = {value};")).contains("name must be a string"), "{value}"); + } +} + +/// `String` of an object of the object model names its class, and its name when it has one. +#[test] +fn objects_of_the_object_model_print_their_class_and_name() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "Logo"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + vc.log([String(p[0]), String(p[1]), '' + p[1], p[1].toString(), String(p[1].parent) === '[Layer ' + p[1].parent.name + ']']);\ + vc.log([String(d) === '[Document ' + d.name + ']', String(app), String(p), String(app.documents)]);", + ); + assert_eq!(out[0], json!(["[PathItem ]", "[PathItem Logo]", "[PathItem Logo]", "[PathItem Logo]", true])); + assert_eq!(out[1], json!([true, "[Application]", "[PageItems]", "[Documents]"])); +} + +/// `activeDocument`, `documents` and `selection` without `app.` read the application's members, and +/// assigning one makes it the script's own variable. +#[test] +fn the_application_members_can_be_named_without_app() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "vc.log([activeDocument === app.activeDocument, documents === app.documents, documents.length,\ + selection.length, selection[0] === app.activeDocument.pageItems[1], typeof activeDocument]);", + ); + assert_eq!(out, vec![json!([true, true, 1, 1, true, "object"])]); + // A script's own variable of the same name holds what the script puts in it. + let out = log(&mut s, "var selection = 5, documents; vc.log([selection, typeof documents, app.selection.length]);"); + assert_eq!(out, vec![json!([5, "object", 1])]); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + // With no document open, reading `activeDocument` throws as `app.activeDocument` does. + let mut s = Session::new(); + assert!(failure(&mut s, "activeDocument;").contains("No active document")); +} + +/// Assigning to a name a collection does not have throws as reading it does; a page item keeps +/// no member it lacks and does not throw. +#[test] +fn assigning_a_name_a_collection_lacks_throws() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + for source in ["app.activeDocument.pageItems.qux = 4;", "app.documents.qux = 4;"] { + assert!(failure(&mut s, source).contains("Not found"), "{source}"); + } + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.foo = 1; app.activeDocument.pageItems[0] = 3; vc.log([i.foo === undefined]);"); + assert_eq!(out, vec![json!([true])]); + assert_eq!(undo_steps(&s), steps); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 02176c38c9..3e336062f2 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -166,7 +166,8 @@ fn an_error_names_the_script_its_place_and_kind() { let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); assert!(run(&mut s, "new Window('dialog');").unwrap_err().to_string().contains("`vc`")); - assert!(run(&mut s, "activeDocument;").unwrap_err().to_string().contains("`app.activeDocument`")); + // The application's members need no `app.`, so naming one alone is not an error. + assert_eq!(run(&mut s, "activeDocument;").unwrap()["ok"], true); assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _")); assert_eq!(s.script_report().unwrap()["line"], 1); } diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index d9b6b87103..09c4daa936 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -73,15 +73,15 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ - DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems RulerUnits ZOrderMethod", + "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ + DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ + documents= Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod", ), ("Application.", "prototype"), ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + selection toString typename", ), ("DocumentPreset.", "prototype"), ( @@ -89,29 +89,29 @@ const INSIDE: &[(&str, &str)] = &[ "artboardLayout artboardLayout= artboardRowsOrCols artboardRowsOrCols= artboardSpacing artboardSpacing= colorMode \ colorMode= constructor documentBleedLink documentBleedLink= documentBleedOffsetRect documentBleedOffsetRect= height \ height= numArtboards numArtboards= previewMode previewMode= rasterResolution rasterResolution= title title= \ - transparencyGrid transparencyGrid= typename units units= width width=", + toString transparencyGrid transparencyGrid= typename units units= width width=", ), ("Documents.", "prototype"), - ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), + ("Documents.prototype.", "add addDocument constructor getByName index length parent toString typename"), ("Document.", "prototype"), ( "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ - views views= width", + rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= toString \ + typename views views= width", ), ("Layer.", "prototype"), - ("Layer.prototype.", "constructor name typename"), + ("Layer.prototype.", "constructor name toString typename"), ("PageItems.", "prototype"), - ("PageItems.prototype.", "constructor getByName index length parent removeAll typename"), + ("PageItems.prototype.", "constructor getByName index length parent removeAll toString typename"), ("PageItem.", "prototype"), ( "PageItem.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ - position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= top top= transform \ + position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= toString top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), @@ -154,6 +154,9 @@ const LIST: &str = r#"(function () { var globals = Object.getOwnPropertyNames(g); add(g, ""); for (var i = 0; i < globals.length; i++) { + // A global with a getter, such as `activeDocument`, is not read: it throws with no document open. + var gd = Object.getOwnPropertyDescriptor(g, globals[i]); + if (gd && gd.get) continue; var v = g[globals[i]]; if (v !== null && (typeof v == "object" || typeof v == "function")) { add(v, globals[i] + "."); diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 69c2ebf402..2c5fcfa9f4 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -433,7 +433,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some())) + Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some() || interp.is_host_member(o, &k)?)) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -452,7 +452,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()))) + Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member(o, &k)?)) } // ---- Function ---- diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..c688a0512c 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -15,12 +15,22 @@ //! Every member function gets the object it is called on (`this`) as its first argument, or //! `undefined` when `this` is not an object of a host class, followed by the call's arguments; a //! setter gets `this` and the value assigned. A class with an indexer answers `object[i]` for each -//! array index `i` with it, called with `this` and the index, and `i in object` is true when it -//! gives a value other than `undefined`; other names are looked up as usual. +//! array index `i` with it, called with `this` and the index as a number. Other names are looked up +//! as usual, and a name that the object and its prototypes lack goes to the indexer as a string (as +//! a number when it is the text of one, such as `-1`), so the indexer may throw for a name nothing has. Assigning to such a name reads it with the indexer +//! first, so the assignment throws what the read throws; otherwise the value is not kept. `k in +//! object` calls the indexer with `true` as a third argument, and is true when it gives a value other +//! than `undefined`. +//! +//! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each +//! member of its class and of the classes it descends from, apart from the members that are not +//! available yet ([`HostMember::Unavailable`]). `for`-`in` lists the properties among those members, +//! and not the methods. +use std::collections::HashSet; use std::rc::Rc; -use crate::heap::{Class, Func, ObjId, Object, Prop, key}; +use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, NativeKind, ObjId, Object, Prop, WRITABLE, key}; use crate::host::ArgRead; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; use crate::value::Value; @@ -38,6 +48,9 @@ pub enum HostMember { Property { get: HostFunction, set: HostFunction }, /// A method. Method(HostFunction), + /// A property the class lists that is not available yet: the function answers both a read and + /// an assignment, with an error. It is not reported as the object's own, and `for`-`in` skips it. + Unavailable(HostFunction), } /// A class [`crate::Realm::define_host_classes`] adds. @@ -72,6 +85,10 @@ pub(crate) struct Entry { /// The class without a parent this class descends from (itself for such a class), as an index /// into the realm's classes. family: u32, + /// The class this class's prototype inherits from, as an index into the realm's classes. + parent: Option, + /// The names of the members `hasOwnProperty` reports: every member but the unavailable ones. + own: Rc>, } impl Entry { @@ -123,6 +140,21 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { } impl Interp { + /// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host + /// class, and `k` names an available member of that class or of a class it descends from. + pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult { + let Class::Host(h) = &self.object(id)?.class else { return Ok(false) }; + let mut class = Some(h.class); + while let Some(c) = class { + let Some(e) = self.host_classes.get(c as usize) else { return Err(Abrupt::Internal("host class out of range".into())) }; + if e.own.contains(k) { + return Ok(true); + } + class = e.parent; + } + Ok(false) + } + /// The [`Data`] for the object of a host class `id`, or `None` when it is not one. pub(crate) fn host_ref_of(&self, id: ObjId) -> JsResult> { let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; @@ -174,24 +206,45 @@ impl Interp { Ok(self.host_classes.get(h.class as usize).and_then(|e| e.index.clone())) } - /// `object[index]` of an object of a host class, which its class's indexer `f` answers. - pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, index: u32) -> JsResult { + /// `object[k]` of an object of a host class, which its class's indexer `f` answers: `k` is an + /// array index as a number, or a name as a string. With `probe`, for `k in object`, the indexer + /// gets `true` as a third argument. + pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult { self.use_fuel()?; let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) }; - match f(vec![this, Data::Number(f64::from(index))]) { + let mut args = vec![this, k]; + if probe { + args.push(Data::Bool(true)); + } + match f(args) { Ok(d) => self.write_hosted(d), Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())), Err(e) => Err(self.host_error(e)?), } } - /// [[HasProperty]] of `k` on `id`: for an array index of an object of a host class with an - /// indexer, whether the indexer gives a value other than `undefined` for it. + /// The key an indexer gets for `k`: a number for an array index and for any other key that is + /// the text of a number (`-1`, `1.5`, `NaN`), otherwise the name. + pub(crate) fn indexer_key(k: &[u16]) -> Data { + if let Some(i) = crate::value::array_index(k) { + return Data::Number(f64::from(i)); + } + let name = String::from_utf16_lossy(k); + match name.parse::() { + Ok(n) if crate::number_to_string(n) == name => Data::Number(n), + _ => Data::String(name), + } + } + + /// [[HasProperty]] of `k` on `id`: for an object of a host class with an indexer, an array index, + /// or a name that the object and its prototypes lack, is there when the indexer gives a value other + /// than `undefined` for it. pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &[u16]) -> JsResult { - if let Some(i) = crate::value::array_index(k) + let index = crate::value::array_index(k).is_some(); + if (index || !self.has_property(id, k)?) && let Some(f) = self.host_indexer(id)? { - return Ok(!matches!(self.host_index(&f, id, i)?, Value::Undefined)); + return Ok(!matches!(self.host_index(&f, id, Self::indexer_key(k), true)?, Value::Undefined)); } self.has_property(id, k) } @@ -218,15 +271,48 @@ pub(crate) fn install(i: &mut Interp, classes: Vec, instances: Vec<(S Ok(()) } +/// Adds the global properties `getters`, each read with its function as a member of a host class is. +/// Assigning one, as `var name = value` at the top level does, replaces it with a plain global +/// variable that holds the value. +pub(crate) fn install_globals(i: &mut Interp, getters: Vec<(String, HostFunction)>) -> JsResult<()> { + let global = i.global; + let proto = i.intrinsics.function_proto; + for (name, f) in getters { + let mark = i.temp_roots.len(); + let get = hosted_function(i, f, &name); + i.temp_roots.push(Value::Object(get)); + let replace = i.heap.alloc_object(Object::new( + Class::Function(Func::Native { f: replace_global, kind: NativeKind::Plain, constructor: false, name: "" }), + Some(proto), + )); + i.temp_roots.push(Value::Object(replace)); + let args: Rc<[Value]> = Rc::from([Value::str(&name)]); + let set = i.heap.alloc_object(Object::new(Class::Function(Func::Bound { target: replace, this: Value::Undefined, args }), Some(proto))); + i.temp_roots.truncate(mark); + i.define(global, key(&name), Prop::Accessor { get: Some(get), set: Some(set), flags: CONFIGURABLE })?; + } + Ok(()) +} + +/// The setter of a global [`install_globals`] adds: makes the global `args[0]` a plain variable +/// holding `args[1]`. +fn replace_global(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let name = interp.to_key(args.first().unwrap_or(&Value::Undefined))?; + let value = args.get(1).cloned().unwrap_or(Value::Undefined); + let global = interp.global; + interp.define(global, name, Prop::Data { value, flags: WRITABLE | ENUMERABLE | CONFIGURABLE })?; + Ok(Value::Undefined) +} + fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { if i.host_classes.iter().any(|e| *e.name == *class.name) { return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); } let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX); - let (parent, family) = match &class.parent { - None => (i.intrinsics.object_proto, own), - Some(p) => match i.host_classes.iter().find(|e| *e.name == **p) { - Some(e) => (e.proto, e.family), + let (parent, family, parent_class) = match &class.parent { + None => (i.intrinsics.object_proto, own, None), + Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) { + Some((n, e)) => (e.proto, e.family, u32::try_from(n).ok()), None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), }, }; @@ -236,7 +322,16 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family }); + let members = class.members.iter().filter(|(_, m)| !matches!(m, HostMember::Unavailable(_))).map(|(name, _)| key(name)).collect(); + i.host_classes.push(Entry { + name: class.name.as_str().into(), + proto, + ctor, + index: class.index, + family, + parent: parent_class, + own: Rc::new(members), + }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) } @@ -247,13 +342,17 @@ fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult Prop::Accessor { get: Some(hosted_function(i, f.clone(), &full)), set: None, flags: 0 }, + HostMember::Get(f) => Prop::Accessor { get: Some(hosted_function(i, f.clone(), &full)), set: None, flags: ENUMERABLE }, HostMember::Property { get, set } => { let get = hosted_function(i, get.clone(), &full); i.temp_roots.push(Value::Object(get)); - Prop::Accessor { get: Some(get), set: Some(hosted_function(i, set.clone(), &full)), flags: 0 } + Prop::Accessor { get: Some(get), set: Some(hosted_function(i, set.clone(), &full)), flags: ENUMERABLE } } HostMember::Method(f) => Prop::Data { value: Value::Object(hosted_function(i, f.clone(), &full)), flags: 0 }, + HostMember::Unavailable(f) => { + let f = hosted_function(i, f.clone(), &full); + Prop::Accessor { get: Some(f), set: Some(f), flags: 0 } + } }; i.define(proto, key(name), prop)?; } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..ba0e005ce0 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -676,6 +676,47 @@ fn a_host_class_constructor_called_with_new_cannot_wait() { assert_eq!(could.get(), Some(false)); } +#[test] +fn objects_of_a_host_class_report_its_available_members_as_their_own() { + let mut r = realm(1_000_000); + let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0))); + let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into()))); + let base = HostClass { + name: "Base".into(), + parent: None, + members: vec![ + ("size".to_string(), HostMember::Get(value.clone())), + ("shape".to_string(), HostMember::Property { get: value.clone(), set: value.clone() }), + ("grow".to_string(), HostMember::Method(value.clone())), + ("later".to_string(), HostMember::Unavailable(missing)), + ], + index: None, + construct: None, + }; + let leaf = HostClass { + name: "Leaf".into(), + parent: Some("Base".into()), + members: vec![("leaf".to_string(), HostMember::Get(value))], + index: None, + construct: None, + }; + r.define_host_classes(vec![base, leaf], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap(); + r.start( + "var own = Object.prototype.hasOwnProperty, keys = [];\ + for (var k in it) keys.push(k);\ + [it.hasOwnProperty('size'), it.hasOwnProperty('shape'), it.hasOwnProperty('grow'), it.hasOwnProperty('leaf'),\ + own.call(it, 'size'), it.propertyIsEnumerable('grow'),\ + it.hasOwnProperty('later'), it.propertyIsEnumerable('later'), it.hasOwnProperty('nope'),\ + it.hasOwnProperty('hasOwnProperty'), it.hasOwnProperty('constructor'), 'later' in it,\ + keys.sort().join(' '), Leaf.prototype.hasOwnProperty('size'), ({}).hasOwnProperty('size')].join()", + ) + .unwrap(); + assert_eq!( + finish(&mut r, 1_000_000).0.unwrap(), + JsValue::String("true,true,true,true,true,true,false,false,false,false,false,true,leaf shape size,false,false".into()) + ); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 63e6251dd7..f91eaae0ef 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1432,10 +1432,15 @@ impl Interp { if let Some(i) = array_index(k) && let Some(f) = self.host_indexer(start)? { - return self.host_index(&f, start, i); + return self.host_index(&f, start, crate::Data::Number(f64::from(i)), false); } match self.find_property(start, k)? { - None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), + // A name the object and its prototypes lack is the indexer's answer too. + None => match self.host_indexer(start)? { + Some(f) => self.host_index(&f, start, Self::indexer_key(k), false), + None => Ok(Value::Undefined), + }, + Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Some(Prop::Data { value, .. }) => Ok(value), Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), } @@ -1728,10 +1733,17 @@ impl Interp { Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"), _ => {} } - let o = self.object(id)?; - if !o.extensible { + if !self.object(id)?.extensible { + // A name that an object of a host class with an indexer lacks is read with the indexer + // first, so assigning it throws what reading it throws. + if array_index(&k).is_none() + && let Some(f) = self.host_indexer(id)? + { + self.host_index(&f, id, Self::indexer_key(&k), false)?; + } return self.reject(throw, &k, "the object is not extensible"); } + let o = self.object(id)?; if let Class::Array { length, length_writable: false } = o.class && array_index(&k).is_some_and(|i| i >= length) { diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index f1ca6b570d..ac58574087 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -522,6 +522,16 @@ impl Realm { } } + /// Adds the global properties `getters`, each read with its function, which gets `undefined` as + /// `this`. Assigning one, as `var name = value` at the top level does, makes it a plain global + /// variable that holds the value. + pub fn define_host_globals(&mut self, getters: Vec<(String, crate::HostFunction)>) -> Result<(), RunError> { + match crate::host_classes::install_globals(&mut self.interp, getters) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Sets `Folder.current` back to the host's `current`, for the next run of a realm that has /// `File` and `Folder` ([`Realm::define_file_classes`]); a realm without them keeps its /// `Folder.current`. The files an earlier run opened are no longer open. The last run's uncaught diff --git a/docs/mcp.md b/docs/mcp.md index 4685f408d7..9d6b02e10c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2622,7 +2622,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.log(value)` adds a value to the report and a line to the Script Console. - `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), - `app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. `app.documents` + `app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. A script may name `activeDocument`, + `documents` and `selection` without `app.`, as + [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) + describes; assigning one of those names, as `var selection = ...` does, makes it a variable of the script's own + (VectorCraft's own rule). `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of @@ -2663,16 +2667,30 @@ app through the global object `vc`, and writes to the Script Console and runs ot `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an - object, with or without a relative object, throws `Cannot duplicate` and makes no copy. When `move` takes the last - path out of a compound path, the empty compound path is deleted in the same undo step. `duplicate` on a path inside a compound path throws + object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `opacity` to an + object in a hidden or locked layer throws `Cannot edit` and changes nothing; an object that is hidden or locked + itself takes it (VectorCraft's own rule). `move` with the object itself as the relative object and `PLACEBEFORE` + or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` takes the last path out of a compound + path, the compound path stays, empty, so a script that holds it can still read it. `duplicate` on a path inside a compound path throws `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a `RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. - VectorCraft's own rules: documents are listed in tab order, and page items in paint order from the bottom, with the - objects inside groups and compound paths after their group and without layers and ruler guides. Script coordinates + `pageItems` lists the art topmost first, as the example on + [CMYKColor](https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/) reads the frontmost path as `pathItems[0]`, + and a document's `selection` lists the selected objects in the same order, not in the order they were selected + ([Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/)). + A collection read with a name, such as `pageItems["Logo"]` or `documents["Untitled-1"]`, gives the object + `getByName` gives, as that page describes, and throws `Not found` when none has the name, a name the collection + class lacks as a member included; `"name" in pageItems` is false then, and assigning to such a name throws + `Not found` too. `name` takes a number or a Boolean as the text `String(value)` gives. `String(object)` gives + `[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document ]`, + `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). + VectorCraft's own rules: documents are listed in tab order, and page items with the + objects inside groups and compound paths after their group and without layers and ruler guides. A document's + `selection`, and `app.selection` while a document is open, is an empty list when nothing is selected. Script coordinates are points with Y up from the bottom-left corner of the first artboard, or, with `CoordinateSystem.ARTBOARDCOORDINATESYSTEM`, Y down from the top-left corner of the active artboard. `typename` is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem` @@ -2694,7 +2712,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and - `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members + `app.beep`, throw an error that says they are not available yet when they are read or assigned. + `hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an + object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the + other properties but not the methods. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..597b3ca6b3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, read a collection by name, and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 6b778a4c7073927760bdcf88fb3e044900eeacf6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 13:24:33 -0800 Subject: [PATCH 066/101] Scripts: setters refuse art in a hidden or locked layer, and empty objects read zero bounds - Assigning hidden, locked, position, left, top, width or height to an object in a hidden or locked layer throws Cannot edit, as opacity does, and changes nothing. Its name and note still change. - An object with nothing in it, such as an empty group or a compound path whose paths moved out, reads its bounds, position, width and height as zeros, and assigning them does nothing, so reading every property for-in lists does not throw on it. - Assigning selection without app. sets the active document's selection, and app.selection can be assigned the same way. Assigning activeDocument without app. activates a document, and assigning documents keeps its value. - JSON.stringify writes a collection, or data that holds one, without reading toJSON through the collection's name lookup, which threw Not found. - The docs state that Object.keys, Object.getOwnPropertyNames and Object.getOwnPropertyDescriptor do not report the members, that a value assigned to a member the class lacks is not kept, and that the selection order is VectorCraft's own rule. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 105 ++++++++++++------ crates/engine/src/tests/script_dom.rs | 97 +++++++++++----- .../tests/it/script_host_vs_scriptcheck.rs | 4 +- crates/js/src/builtins/json.rs | 2 +- crates/js/src/host_classes.rs | 47 +++----- crates/js/src/interp.rs | 11 ++ crates/js/src/realm.rs | 10 +- docs/mcp.md | 39 ++++--- docs/target-app-parity.md | 2 +- 9 files changed, 200 insertions(+), 117 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index bef71437d4..7b9df28106 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -15,15 +15,18 @@ //! //! Collections are counted from 0, and `pageItems` lists art topmost first, as //! reads the frontmost path as -//! `pathItems[0]`. A document's selection lists the selected objects in the same order, not in the -//! order they were selected (). -//! A collection read with a name, `pageItems["name"]`, gives the object `getByName` gives, as that -//! page describes, and throws `Not found` when none has the name; `"name" in pageItems` is false then, -//! and assigning to such a name throws the same error. As that page also describes, a script may name -//! `activeDocument`, `documents` and `selection` without `app.`; assigning one of those names makes it -//! a variable of the script's own. +//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName` +//! gives, and a script may name the application's members without `app.`, as +//! describes; here +//! that holds for `activeDocument`, `documents` and `selection`. //! //! VectorCraft's own rules, which the help pages do not state: +//! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever +//! order they were selected or made in. +//! - A collection read with a name that nothing has throws `Not found`, and `"name" in pageItems` is +//! false then. Assigning to such a name throws the same error. +//! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the +//! active document's selection. Assigning `documents` keeps its value. //! - Collections list documents in tab order. `pageItems` lists every object, with the objects //! inside groups and compound paths after the group or compound path, and leaves out layers and //! ruler guides. An index out of range gives `undefined`; `index` and `getByName` throw @@ -36,8 +39,12 @@ //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. //! - Members the help pages list that are not here yet throw an error that says so. -//! - Assigning `opacity` to an object in a hidden or locked layer throws `Cannot edit` and changes -//! nothing. An object that is hidden or locked itself, or is in a hidden or locked group, takes it. +//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an +//! object in a hidden or locked layer throws `Cannot edit` and changes nothing; its `name` and +//! `note` still change. An object that is hidden or locked itself, or is in a hidden or locked +//! group, takes them. +//! - An object with nothing in it, such as an empty group or a compound path whose paths moved out, +//! reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing. use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; @@ -709,6 +716,18 @@ fn app_selection(h: &Host, _: &[Data]) -> Answer { } } +/// `app.selection = objects`: the active document's selection, as `selection` of that document is +/// assigned. +fn app_set_selection(h: &Host, a: &[Data]) -> Answer { + let doc = { + let s = h.session.borrow(); + let active = s.active_index().and_then(|index| s.documents().get(index).map(|st| Doc { index, uid: st.uid })); + active.ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))? + }; + let ids = selection_ids(h, doc, arg(a, 1))?; + set_selection(h, doc, ids) +} + fn app_coords(h: &Host, _: &[Data]) -> Answer { Ok(text(if h.dom.coords.get() == Coords::Document { DOCUMENT_COORDS } else { ARTBOARD_COORDS })) } @@ -1490,12 +1509,27 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// Refuses a change to the item's appearance, place or size while a layer it is in is hidden or +/// locked. Its name and note may still change. +fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> { + let refused = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked)); + d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item")) + }); + match refused { + Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))), + None => Ok(()), + } +} + fn item_hidden(h: &Host, a: &[Data]) -> Answer { read_item(h, a, |_, n| Ok(Data::Bool(!n.visible))) } fn item_set_hidden(h: &Host, a: &[Data]) -> Answer { let hidden = boolean(arg(a, 1), "hidden")?; + refuse_in_closed_layer(h, this_item(h, a)?)?; set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden})) } @@ -1505,6 +1539,7 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer { fn item_set_locked(h: &Host, a: &[Data]) -> Answer { let locked = boolean(arg(a, 1), "locked")?; + refuse_in_closed_layer(h, this_item(h, a)?)?; set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) } @@ -1521,14 +1556,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still // replaces the one the graph keeps for its series or kind. let item = this_item(h, a)?; - let refused = with_doc(h, item.doc, |_, st| { - let d = &st.doc; - let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked)); - d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item")) - }); - if let Some(name) = refused { - return Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))); - } + refuse_in_closed_layer(h, item)?; let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0)); let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v); set_props(h, a, |_| false, json!({"opacity": v})) @@ -1554,18 +1582,19 @@ fn item_set_selected(h: &Host, a: &[Data]) -> Answer { } /// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the -/// document's [`Frame`]. -fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Rect, Frame), HostError> { - with_doc(h, item.doc, |_, st| { - let r = st.doc.bounds_of(&[item.id], visual).ok_or_else(|| HostError::Error("the object has no bounds".into()))?; - Ok((r, frame(st)?)) - }) +/// document's [`Frame`]. An object with nothing in it, such as an empty group or a compound path +/// whose paths moved out, has no bounds: its bounds read as zeros, and moving or resizing it does +/// nothing. +fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Option, Frame), HostError> { + with_doc(h, item.doc, |_, st| Ok((st.doc.bounds_of(&[item.id], visual), frame(st)?))) } fn bounds(h: &Host, a: &[Data], visual: bool) -> Answer { let item = this_item(h, a)?; - let (r, f) = item_rect(h, item, visual)?; - Ok(f.bounds(h.dom.coords.get(), r)) + match item_rect(h, item, visual)? { + (Some(r), f) => Ok(f.bounds(h.dom.coords.get(), r)), + (None, _) => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])), + } } fn item_geometric(h: &Host, a: &[Data]) -> Answer { @@ -1578,8 +1607,10 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - let (r, f) = item_rect(h, item, false)?; - Ok(pair(f.to_script(h.dom.coords.get(), Point::new(r.x0, r.y0)))) + match item_rect(h, item, false)? { + (Some(r), f) => Ok(pair(f.to_script(h.dom.coords.get(), Point::new(r.x0, r.y0)))), + (None, _) => Ok(pair([0.0, 0.0])), + } } fn item_left(h: &Host, a: &[Data]) -> Answer { @@ -1598,19 +1629,20 @@ fn item_top(h: &Host, a: &[Data]) -> Answer { fn item_width(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - Ok(num(item_rect(h, item, false)?.0.width())) + Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.width()))) } fn item_height(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - Ok(num(item_rect(h, item, false)?.0.height())) + Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.height()))) } /// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one /// stays). fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { let item = this_item(h, a)?; - let (r, f) = item_rect(h, item, false)?; + refuse_in_closed_layer(h, item)?; + let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; let c = h.dom.coords.get(); let now = f.to_script(c, Point::new(r.x0, r.y0)); let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); @@ -1646,7 +1678,8 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer { return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points"))); } let item = this_item(h, a)?; - let (r, _) = item_rect(h, item, false)?; + refuse_in_closed_layer(h, item)?; + let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; let now = if width { r.width() } else { r.height() }; if now <= 0.0 { return Err(HostError::Error(format!("the object has no {what} to scale"))); @@ -2009,7 +2042,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("typename", typename_of("Application")), ("documents", get(l, app_documents)), ("activeDocument", property(l, app_active, app_set_active)), - ("selection", get(l, app_selection)), + ("selection", property(l, app_selection, app_set_selection)), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), ("toString", class_text("Application")), @@ -2137,11 +2170,11 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), None, )); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?; - // The application's members a script may name without `app.`. + // The application's members a script may name without `app.`, assigned as `app.` is. realm.define_host_globals(vec![ - ("activeDocument".into(), function(l, app_active)), - ("documents".into(), function(l, app_documents)), - ("selection".into(), function(l, app_selection)), + ("activeDocument".into(), function(l, app_active), Some(function(l, app_set_active))), + ("documents".into(), function(l, app_documents), None), + ("selection".into(), function(l, app_selection), Some(function(l, app_set_selection))), ]) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 8d015d8727..68a485c8de 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -506,9 +506,16 @@ fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() { "var d = app.activeDocument, c = d.pageItems[0], m = [d.pageItems[2], d.pageItems[1]];\ m[0].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\ m[1].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\ - vc.log([c.typename, c === d.pageItems[2]]);", + vc.log([c.typename, c === d.pageItems[2]]);\ + var bad = []; for (var k in c) { try { c[k]; } catch (e) { bad.push(k + ': ' + e.message); } } vc.log(bad);\ + vc.log([c.geometricBounds, c.visibleBounds, c.position, c.width, c.height]);\ + c.left = 5; c.top = 5; c.position = [1, 2]; c.width = 10; c.height = 10; vc.log(c.geometricBounds);", ); - assert_eq!(out, vec![json!(3), json!(3), json!(["CompoundPathItem", true])]); + let zeros = json!([0, 0, 0, 0]); + assert_eq!(out[..3], [json!(3), json!(3), json!(["CompoundPathItem", true])]); + // Every property `for`-`in` lists reads, and the emptied compound path has zero bounds that + // moving or resizing leaves as they are. + assert_eq!(out[3..], [json!([]), json!([zeros, zeros, [0, 0], 0, 0]), zeros]); let doc = &s.active().unwrap().doc; assert!(doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); // Each path went directly above the compound path, the second above the first. @@ -1409,17 +1416,18 @@ fn page_items_report_their_available_members_as_their_own() { assert_eq!(out[2], json!([true, true, -1, -1])); } -/// A name a page item class's prototype has, such as `constructor`, or that a script tries to put on -/// the prototype, is not an object's own. +/// A name a page item class's prototype has, such as `constructor`, is not an object's own, and a +/// script cannot put a name on the prototype. #[test] fn a_property_added_to_a_class_prototype_is_not_an_objects_own() { let (mut s, _, _) = doc(); let out = log( &mut s, "var p = app.activeDocument.pageItems[0]; PathItem.prototype.foo = 1; PageItem.prototype.bar = 2;\ + vc.log([PathItem.prototype.foo === undefined, PageItem.prototype.bar === undefined, 'foo' in p]);\ vc.log([p.hasOwnProperty('foo'), p.hasOwnProperty('bar'), p.propertyIsEnumerable('foo'), p.hasOwnProperty('constructor')]);", ); - assert_eq!(out, vec![json!([false, false, false, false])]); + assert_eq!(out, vec![json!([true, true, false]), json!([false, false, false, false])]); } /// Reading every property `for`-`in` lists calls each getter, and each call counts against the run: @@ -1449,7 +1457,7 @@ fn reading_every_listed_property_is_charged_and_can_be_stopped() { } /// `pageItems` lists art topmost first, and the selection lists the selected objects in that -/// order whatever order they were selected in. +/// order whatever order they were selected or made in. #[test] fn page_items_and_the_selection_list_the_topmost_object_first() { let (mut s, a, b) = doc(); @@ -1464,6 +1472,16 @@ fn page_items_and_the_selection_list_the_topmost_object_first() { d.selection = [d.pageItems[1], d.pageItems[0]]; vc.log(d.selection[0].name);", ); assert_eq!(out, vec![json!(["top", "bottom", "top", "bottom"]), json!("top")]); + // An object made last and sent to the back comes after the others it is selected with. + let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "last"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.pageItems.getByName('last'); c.zOrder(ZOrderMethod.SENDTOBACK);\ + d.selection = null; c.selected = true; d.pageItems.getByName('top').selected = true;\ + vc.log([d.selection[0].name, d.selection[1].name, d.pageItems[2].name]);", + ); + assert_eq!(out, vec![json!(["top", "last", "last"])]); } /// A collection read with a name gives what `getByName` gives, and throws as it does for no match. @@ -1483,10 +1501,11 @@ fn a_collection_read_with_a_name_gives_the_named_object() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); } -/// `opacity` on an object in a hidden or locked layer throws and the run changes nothing; an object -/// that is hidden or locked itself takes it. +/// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or +/// locked layer throw and the run changes nothing, while its name and note still change; an object +/// that is hidden or locked itself takes them. #[test] -fn opacity_refuses_art_in_a_hidden_or_locked_layer() { +fn setters_refuse_art_in_a_hidden_or_locked_layer() { let (mut s, a, b) = doc(); let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); @@ -1498,12 +1517,20 @@ fn opacity_refuses_art_in_a_hidden_or_locked_layer() { (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), ] { s.execute("object.setProps", &on).unwrap(); - let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); - // The change made before the refusal is put back with the rest of the run. - let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.getByName('free').opacity = 20; p.getByName('closed').opacity = 50;"); - assert!(e.contains(&format!("Cannot edit PathItem {}", c.0)), "{on}: {e}"); - assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{on}"); - assert_eq!(undo_steps(&s), steps, "{on}"); + for set in ["opacity = 50", "hidden = true", "locked = true", "left = 5", "top = 5", "position = [5, 5]", "width = 10", "height = 10"] { + let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + // The change made before the refusal is put back with the rest of the run. + let e = failure(&mut s, &format!("var p = app.activeDocument.pageItems; p.getByName('free').opacity = 20; p.getByName('closed').{set};")); + assert!(e.contains(&format!("Cannot edit PathItem {}", c.0)), "{on} {set}: {e}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{on} {set}"); + assert_eq!(undo_steps(&s), steps, "{on} {set}"); + } + let out = log( + &mut s, + "var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; vc.log([c.name, c.note]);\ + c.name = 'closed'; c.note = '';", + ); + assert_eq!(out, vec![json!(["renamed", "n"])], "{on}"); s.execute("object.setProps", &off).unwrap(); } s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); @@ -1548,10 +1575,10 @@ fn objects_of_the_object_model_print_their_class_and_name() { } /// `activeDocument`, `documents` and `selection` without `app.` read the application's members, and -/// assigning one makes it the script's own variable. +/// assigning one assigns the member: `selection` selects, `documents` keeps its value. #[test] fn the_application_members_can_be_named_without_app() { - let (mut s, a, _) = doc(); + let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let out = log( &mut s, @@ -1559,17 +1586,24 @@ fn the_application_members_can_be_named_without_app() { selection.length, selection[0] === app.activeDocument.pageItems[1], typeof activeDocument]);", ); assert_eq!(out, vec![json!([true, true, 1, 1, true, "object"])]); - // A script's own variable of the same name holds what the script puts in it. - let out = log(&mut s, "var selection = 5, documents; vc.log([selection, typeof documents, app.selection.length]);"); - assert_eq!(out, vec![json!([5, "object", 1])]); - assert_eq!(s.active().unwrap().selection.objects, vec![a]); + let out = log( + &mut s, + "var d = app.activeDocument; selection = null; vc.log(d.selection.length);\ + selection = [d.pageItems[0], d.pageItems[1]]; vc.log(d.selection.length);\ + app.selection = d.pageItems[0]; vc.log([d.selection.length, selection[0] === d.pageItems[0]]);\ + var selection = d.selection; documents = 5; activeDocument = d; vc.log([selection.length, typeof documents]);", + ); + assert_eq!(out, vec![json!(0), json!(2), json!([1, true]), json!([1, "object"])]); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + assert!(failure(&mut s, "activeDocument = 5;").contains("not a Document")); + failure(&mut s, "'use strict'; documents = 5;"); // With no document open, reading `activeDocument` throws as `app.activeDocument` does. let mut s = Session::new(); assert!(failure(&mut s, "activeDocument;").contains("No active document")); } -/// Assigning to a name a collection does not have throws as reading it does; a page item keeps -/// no member it lacks and does not throw. +/// Assigning to a name a collection does not have throws as reading it does, and assigning an +/// index does not replace the object there. #[test] fn assigning_a_name_a_collection_lacks_throws() { let (mut s, _, _) = doc(); @@ -1577,7 +1611,20 @@ fn assigning_a_name_a_collection_lacks_throws() { for source in ["app.activeDocument.pageItems.qux = 4;", "app.documents.qux = 4;"] { assert!(failure(&mut s, source).contains("Not found"), "{source}"); } - let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.foo = 1; app.activeDocument.pageItems[0] = 3; vc.log([i.foo === undefined]);"); - assert_eq!(out, vec![json!([true])]); + let out = log(&mut s, "var p = app.activeDocument.pageItems; p[0] = 3; vc.log(typeof p[0]);"); + assert_eq!(out, vec![json!("object")]); assert_eq!(undo_steps(&s), steps); } + +/// `JSON.stringify` writes a collection, or data that holds one, without reading a `toJSON` the +/// collection lacks, while a script that reads `toJSON` itself gets `Not found`. +#[test] +fn json_stringify_writes_a_collection() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, m = ''; vc.log([JSON.stringify(p), JSON.stringify({list: [p, app.documents]})]);\ + try { p.toJSON; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, vec![json!(["{}", "{\"list\":[{},{}]}"]), json!("Not found")]); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 09c4daa936..4426cbaaf5 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -75,13 +75,13 @@ const INSIDE: &[(&str, &str)] = &[ "", "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ - documents= Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod", + Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod", ), ("Application.", "prototype"), ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection toString typename", + selection selection= toString typename", ), ("DocumentPreset.", "prototype"), ( diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 364ec99696..df9cbba9ee 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -538,7 +538,7 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K keep(interp, &v); let name = Value::String(Str::from_rc(k.clone())); if let Value::Object(o) = v { - let to_json = interp.get_from(o, &key("toJSON"), &v)?; + let to_json = interp.get_property_only(o, &key("toJSON"), &v)?; if interp.is_callable(&to_json) { v = interp.call(&to_json, &v, std::slice::from_ref(&name))?; keep(interp, &v); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index c688a0512c..206f781ef3 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -17,20 +17,22 @@ //! setter gets `this` and the value assigned. A class with an indexer answers `object[i]` for each //! array index `i` with it, called with `this` and the index as a number. Other names are looked up //! as usual, and a name that the object and its prototypes lack goes to the indexer as a string (as -//! a number when it is the text of one, such as `-1`), so the indexer may throw for a name nothing has. Assigning to such a name reads it with the indexer -//! first, so the assignment throws what the read throws; otherwise the value is not kept. `k in -//! object` calls the indexer with `true` as a third argument, and is true when it gives a value other -//! than `undefined`. +//! a number when it is the text of one, such as `-1`), so the indexer may throw for a name nothing +//! has. Names the engine looks up itself, such as `toJSON` in `JSON.stringify`, do not go to the +//! indexer. Assigning to such a name reads it with the indexer first, so the assignment throws what +//! the read throws; otherwise the value is not kept. `k in object` calls the indexer with `true` as +//! a third argument, and is true when it gives a value other than `undefined`. //! //! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each //! member of its class and of the classes it descends from, apart from the members that are not //! available yet ([`HostMember::Unavailable`]). `for`-`in` lists the properties among those members, -//! and not the methods. +//! and not the methods. `Object.keys`, `Object.getOwnPropertyNames` and +//! `Object.getOwnPropertyDescriptor` do not report the members. use std::collections::HashSet; use std::rc::Rc; -use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, NativeKind, ObjId, Object, Prop, WRITABLE, key}; +use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key}; use crate::host::ArgRead; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; use crate::value::Value; @@ -271,39 +273,22 @@ pub(crate) fn install(i: &mut Interp, classes: Vec, instances: Vec<(S Ok(()) } -/// Adds the global properties `getters`, each read with its function as a member of a host class is. -/// Assigning one, as `var name = value` at the top level does, replaces it with a plain global -/// variable that holds the value. -pub(crate) fn install_globals(i: &mut Interp, getters: Vec<(String, HostFunction)>) -> JsResult<()> { +/// Adds the global properties `globals`, each read with its getter and assigned with its setter as +/// a member of a host class is. Assigning one without a setter keeps its value, and throws in strict +/// mode code. +pub(crate) fn install_globals(i: &mut Interp, globals: Vec<(String, HostFunction, Option)>) -> JsResult<()> { let global = i.global; - let proto = i.intrinsics.function_proto; - for (name, f) in getters { + for (name, get, set) in globals { let mark = i.temp_roots.len(); - let get = hosted_function(i, f, &name); + let get = hosted_function(i, get, &name); i.temp_roots.push(Value::Object(get)); - let replace = i.heap.alloc_object(Object::new( - Class::Function(Func::Native { f: replace_global, kind: NativeKind::Plain, constructor: false, name: "" }), - Some(proto), - )); - i.temp_roots.push(Value::Object(replace)); - let args: Rc<[Value]> = Rc::from([Value::str(&name)]); - let set = i.heap.alloc_object(Object::new(Class::Function(Func::Bound { target: replace, this: Value::Undefined, args }), Some(proto))); + let set = set.map(|f| hosted_function(i, f, &name)); i.temp_roots.truncate(mark); - i.define(global, key(&name), Prop::Accessor { get: Some(get), set: Some(set), flags: CONFIGURABLE })?; + i.define(global, key(&name), Prop::Accessor { get: Some(get), set, flags: CONFIGURABLE })?; } Ok(()) } -/// The setter of a global [`install_globals`] adds: makes the global `args[0]` a plain variable -/// holding `args[1]`. -fn replace_global(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - let name = interp.to_key(args.first().unwrap_or(&Value::Undefined))?; - let value = args.get(1).cloned().unwrap_or(Value::Undefined); - let global = interp.global; - interp.define(global, name, Prop::Data { value, flags: WRITABLE | ENUMERABLE | CONFIGURABLE })?; - Ok(Value::Undefined) -} - fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { if i.host_classes.iter().any(|e| *e.name == *class.name) { return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index f91eaae0ef..423039d3b8 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1446,6 +1446,17 @@ impl Interp { } } + /// [[Get]] of a name that is not an array index, without the indexer of an object of a host + /// class: a name the object and its prototypes lack is `undefined`. For names the engine looks + /// up itself, such as `toJSON`, which a collection's indexer would answer with an error. + pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + match self.find_property(start, k)? { + None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), + Some(Prop::Data { value, .. }) => Ok(value), + Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), + } + } + /// The prototype a primitive's properties are looked up on. fn primitive_proto(&mut self, v: &Value, k: &[u16]) -> JsResult { match v { diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ac58574087..600068fd4c 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -522,11 +522,11 @@ impl Realm { } } - /// Adds the global properties `getters`, each read with its function, which gets `undefined` as - /// `this`. Assigning one, as `var name = value` at the top level does, makes it a plain global - /// variable that holds the value. - pub fn define_host_globals(&mut self, getters: Vec<(String, crate::HostFunction)>) -> Result<(), RunError> { - match crate::host_classes::install_globals(&mut self.interp, getters) { + /// Adds the global properties `globals`: a name, the function that answers a read, and the + /// function that answers an assignment, each called with `undefined` as `this` (and the value + /// assigned). Assigning one without a setter keeps its value, and throws in strict mode code. + pub fn define_host_globals(&mut self, globals: Vec<(String, crate::HostFunction, Option)>) -> Result<(), RunError> { + match crate::host_classes::install_globals(&mut self.interp, globals) { Ok(()) => Ok(()), Err(e) => self.outcome(Err(e)).map(drop), } diff --git a/docs/mcp.md b/docs/mcp.md index 9d6b02e10c..cef9a0af60 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2622,11 +2622,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.log(value)` adds a value to the report and a line to the Script Console. - `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), - `app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. A script may name `activeDocument`, - `documents` and `selection` without `app.`, as + `app.selection` (assigning it sets the active document's selection), `app.coordinateSystem` and + `app.getIsFileOpen(path)`. A script may name the application's members without `app.`, as [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) - describes; assigning one of those names, as `var selection = ...` does, makes it a variable of the script's own - (VectorCraft's own rule). `app.documents` + describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. Assigning `activeDocument` or `selection` without `app.`, as `var selection = ...` at the top level also + does, assigns the application's member, and assigning `documents` keeps its value (VectorCraft's own rule). + `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of @@ -2667,11 +2668,14 @@ app through the global object `vc`, and writes to the Script Console and runs ot `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an - object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `opacity` to an - object in a hidden or locked layer throws `Cannot edit` and changes nothing; an object that is hidden or locked - itself takes it (VectorCraft's own rule). `move` with the object itself as the relative object and `PLACEBEFORE` - or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` takes the last path out of a compound - path, the compound path stays, empty, so a script that holds it can still read it. `duplicate` on a path inside a compound path throws + object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`, + `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer + throws `Cannot edit` and changes nothing, while its `name` and `note` still change; an object that is hidden or + locked itself takes them (VectorCraft's own rule). `move` with the object itself as the relative object and + `PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` takes the last path out of + a compound path, the compound path stays, empty, so a script that holds it can still read it. An object with + nothing in it, such as an empty group or that compound path, reads its bounds, `position`, `width` and `height` + as zeros, and assigning them does nothing (VectorCraft's own rule). `duplicate` on a path inside a compound path throws `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a `RasterItem`. The @@ -2680,12 +2684,13 @@ app through the global object `vc`, and writes to the Script Console and runs ot `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. `pageItems` lists the art topmost first, as the example on [CMYKColor](https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/) reads the frontmost path as `pathItems[0]`, - and a document's `selection` lists the selected objects in the same order, not in the order they were selected - ([Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/)). - A collection read with a name, such as `pageItems["Logo"]` or `documents["Untitled-1"]`, gives the object - `getByName` gives, as that page describes, and throws `Not found` when none has the name, a name the collection - class lacks as a member included; `"name" in pageItems` is false then, and assigning to such a name throws - `Not found` too. `name` takes a number or a Boolean as the text `String(value)` gives. `String(object)` gives + and a document's `selection` lists the selected objects in the same order, whatever order they were selected or + made in (VectorCraft's own rule). A collection read with a name, such as `pageItems["Logo"]` or + `documents["Untitled-1"]`, gives the object `getByName` gives, as + [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) + shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws + `Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too + (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` takes a number or a Boolean as the text `String(value)` gives. `String(object)` gives `[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document ]`, `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). VectorCraft's own rules: documents are listed in tab order, and page items with the @@ -2715,7 +2720,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. `hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the - other properties but not the methods. Other members + other properties but not the methods. `Object.keys`, `Object.getOwnPropertyNames` and + `Object.getOwnPropertyDescriptor` do not report those members. Assigning a member that an object's class does not + have does not keep the value and does not throw. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 597b3ca6b3..f062c9d54b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, read a collection by name, and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From abdc57c30697616bc541efdf1fb86dda3d2b2bac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 09:41:20 -0800 Subject: [PATCH 067/101] Pathfinder: Outline keeps boundaries that meet only at their ends and middle Outline treated two chains as one edge when their start, end and midpoint were within the merge distance. At a coarse Precision, two closed boundaries that share those three points but part elsewhere (an ellipse inside a circle, touching at its rightmost and leftmost points) became one edge, and the inner boundary was dropped. The ends and midpoint now only pick the candidates. Two chains are one edge when each lies within the merge distance of the other along its whole length: every piece is checked at points no farther apart along its control polygon than that distance, at most 64 to a piece, always including its middle. Chains whose pieces pair up with control points within the distance are taken without sampling, so copies of a detailed path cost no more to merge than before. --- crates/pathops/src/pathfinder.rs | 104 ++++++++++++++++++++++++++++++- crates/pathops/tests/it/ops.rs | 19 ++++++ 2 files changed, 122 insertions(+), 1 deletion(-) diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index 6f99a3d917..1ec916e500 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -971,6 +971,48 @@ fn along(a: &[PathSeg], b: &[PathSeg], tol: f64) -> bool { covers(a, b) && covers(b, a) } +/// [`along`] with each piece checked at points no farther apart along its control polygon than +/// `tol`, at most 64 to a piece, so curves that meet at the middles and ends of their pieces but +/// part between them are not one. `a` and `b` run opposite ways. Each piece's samples include its +/// middle. Chains whose pieces pair up with control points within `tol` of each other are one +/// without sampling: each point of such a piece is within `tol` of the point of its pair at the same +/// parameter. +fn along_closely(a: &[PathSeg], b: &[PathSeg], tol: f64) -> bool { + let within = |p: Point, q: Point| p.distance(q) <= tol; + let paired = a.len() == b.len() + && a.iter().zip(b.iter().rev()).all(|(p, q)| match (p, q.reverse()) { + (PathSeg::Line(x), PathSeg::Line(y)) => within(x.p0, y.p0) && within(x.p1, y.p1), + (PathSeg::Quad(x), PathSeg::Quad(y)) => within(x.p0, y.p0) && within(x.p1, y.p1) && within(x.p2, y.p2), + (PathSeg::Cubic(x), PathSeg::Cubic(y)) => within(x.p0, y.p0) && within(x.p1, y.p1) && within(x.p2, y.p2) && within(x.p3, y.p3), + _ => false, + }); + if paired { + return true; + } + let samples = |s: &PathSeg| { + let len = match s { + PathSeg::Line(l) => l.p0.distance(l.p1), + PathSeg::Quad(q) => q.p0.distance(q.p1) + q.p1.distance(q.p2), + PathSeg::Cubic(c) => c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3), + }; + // An even count puts a sample at the middle of the piece. + let n = if tol > 0.0 { ((len / tol / 2.0).ceil().clamp(1.0, 32.0) as usize) * 2 } else { 64 }; + let s = *s; + (1..=n).map(move |k| s.eval(k as f64 / n as f64)) + }; + let covers = |from: &[PathSeg], to: &[PathSeg]| { + // Each point's search goes back along `to` from the piece the point before it was near. + let mut at = to.len(); + from.iter().flat_map(samples).all(|p| { + let mut order = to.iter().enumerate().take(at).rev().chain(to.iter().enumerate().skip(at).rev()); + let Some((i, _)) = order.find(|(_, t)| t.nearest(p, 1e-12).distance_sq.sqrt() <= tol) else { return false }; + at = i + 1; + true + }) + }; + covers(a, b) && covers(b, a) +} + /// Pathfinder Outline: split every shape's boundary at junctions of the arrangement. Junctions /// closer together than `reach` are one, and coincident edges within ten times it are one edge. /// `reach` is its value at [`DEFAULT_PRECISION`] times `precision / DEFAULT_PRECISION`, a factor kept @@ -1057,8 +1099,15 @@ fn outline_edges(arr: &Arrangement, shapes: &[Shape], precision: f64) -> Vec, u64)> = Vec::new(); let mut sigs: Vec<(Point, Point, Point)> = Vec::new(); + let mut paths: Vec> = Vec::new(); + let as_path = |c: &[Seg]| -> Vec { + c.iter().map(|s| if s.line { PathSeg::Line(Line::new(s.c.p0, s.c.p3)) } else { PathSeg::Cubic(s.c) }).collect() + }; + let reversed = |c: &[PathSeg]| -> Vec { c.iter().rev().map(|s| s.reverse()).collect() }; let sig = |c: &[Seg]| -> (Point, Point, Point) { let a = c[0].c.p0; let b = c[c.len() - 1].c.p3; @@ -1071,6 +1120,7 @@ fn outline_edges(arr: &Arrangement, shapes: &[Shape], precision: f64) -> Vec> = HashMap::new(); for (chain, key) in chains { let (a, b, m) = sig(&chain); + let path = as_path(&chain); let (cx, cy) = cell(m); let found = (cx - 1..=cx + 1) .flat_map(|x| (cy - 1..=cy + 1).map(move |y| (x, y))) @@ -1079,7 +1129,21 @@ fn outline_edges(arr: &Arrangement, shapes: &[Shape], precision: f64) -> Vec p.end().distance(f.end()) <= p.end().distance(l.start()), + _ => true, + }); + if runs_same { along_closely(&path, &reversed(other), d) } else { along_closely(&path, other, d) } }) .min(); match found { @@ -1087,6 +1151,7 @@ fn outline_edges(arr: &Arrangement, shapes: &[Shape], precision: f64) -> Vec { grid.entry((cx, cy)).or_default().push(out.len()); sigs.push((a, b, m)); + paths.push(path); out.push((chain, key)); } } @@ -1714,4 +1779,41 @@ mod tests { assert_eq!(merged.len(), 40); assert!(merged.iter().enumerate().all(|(k, s)| s.key == k as u64)); } + + /// A curve with the ends of a line that passes within 0.25 pt of the line's middle, and whose + /// own middle is within 0.25 pt of the line, but which runs about 23 pt past the line's start: + /// the middles and ends of the two pieces match, and the two are still not one edge. + #[test] + fn along_closely_checks_curves_between_the_middles_of_their_pieces() { + let line = [PathSeg::Line(Line::new((100.0, 0.0), (0.0, 0.0)))]; + let curve = [PathSeg::Cubic(kurbo::CubicBez::new((0.0, 0.0), (-54.56, 0.4537), (198.85, 0.0963), (100.0, 0.0)))]; + assert!(along(&line, &curve, 0.25), "the middles and ends match"); + assert!(!along_closely(&line, &curve, 0.25)); + assert!(!along_closely(&curve, &line, 0.25)); + let same = [PathSeg::Line(Line::new((0.0, 0.0), (100.0, 0.0)))]; + assert!(along_closely(&line, &same, 0.25)); + } + + /// A curve 1.05 pt from a line at its middle and under 1 pt from it at its thirds: with a + /// control polygon under three times the tolerance long, the samples still take in the middle. + #[test] + fn along_closely_samples_the_middle_of_a_short_piece() { + let line = [PathSeg::Line(Line::new((0.15, 0.0), (0.0, 0.0)))]; + let curve = [PathSeg::Cubic(kurbo::CubicBez::new((0.0, 0.0), (0.05, 1.4), (0.1, 1.4), (0.15, 0.0)))]; + assert!(!along_closely(&curve, &line, 1.0)); + } + + /// Pieces whose control points pair up within the tolerance are one edge, copies included. + #[test] + fn along_closely_takes_pieces_whose_control_points_pair_up() { + let a = [ + PathSeg::Cubic(kurbo::CubicBez::new((0.0, 0.0), (10.0, 20.0), (30.0, 20.0), (40.0, 0.0))), + PathSeg::Line(Line::new((40.0, 0.0), (80.0, 0.0))), + ]; + let reversed: Vec = a.iter().rev().map(|s| s.reverse()).collect(); + assert!(along_closely(&a, &reversed, 0.01)); + let shifted: Vec = reversed.iter().map(|s| kurbo::Affine::translate((0.0, 0.2)) * *s).collect(); + assert!(along_closely(&a, &shifted, 0.25)); + assert!(!along_closely(&a, &shifted, 0.1)); + } } diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index 9780f71420..def782ffc0 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -254,6 +254,25 @@ fn pf_outline_joins_junctions_closer_than_the_precision() { assert!(close(length(&coarse), length(&at_default), 1e-6), "{} against {}", length(&coarse), length(&at_default)); } +/// Two boundaries that are close only at their start, end and middle stay two edges at 10 pt: an +/// ellipse 0.005 pt inside a circle at its rightmost and leftmost points, and 30 pt inside it at +/// the top and bottom. Two copies of one boundary are still one edge at that precision. +#[test] +fn pf_outline_keeps_boundaries_that_differ_between_their_ends_at_coarse_precision() { + let ellipse = |rx: f64, ry: f64| PathData::from_bezpath(&kurbo::Ellipse::new((100.0, 100.0), (rx, ry), 0.0).to_path(1e-4)); + let s = vec![shape(ellipse(50.0, 50.0), 1), shape(ellipse(49.995, 20.0), 2)]; + let length = |r: &[Shape]| r.iter().map(|s| s.path.length()).sum::(); + let expected = s[0].path.length() + s[1].path.length(); + for precision in [DEFAULT_PRECISION, 10.0] { + let r = pathfinder_with(PathfinderOp::Outline, &s, precision); + assert_eq!(r.len(), 2, "{precision} pt: {r:?}"); + assert!(close(length(&r), expected, 1e-6), "{precision} pt: {} against {expected}", length(&r)); + } + let copies = vec![shape(ellipse(50.0, 50.0), 1), shape(ellipse(50.0, 50.0), 2)]; + let r = pathfinder_with(PathfinderOp::Outline, &copies, 10.0); + assert!(close(length(&r), copies[0].path.length(), 1e-6), "{r:?}"); +} + #[test] fn regions_and_region_at() { let s = stack(); From a58150198f6e33c06818d1edd759413e11da9dce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 10:47:51 -0800 Subject: [PATCH 068/101] Pathfinder: Outline's junction distance scales with the art and the precision together Outline joined crossings closer together than the art-size tolerance multiplied by precision / 0.01. Scale Strokes & Effects scales the art and the precision together, so scaling both by 10 made that distance 100 times larger, and crossings that were apart could become one junction. The distance is now precision / 10000, or the tolerance for the art's size when that is larger. At the 0.01 pt default it is 0.000001 pt as before, and scaling the art and the precision together gives the same pieces at the new size. The params text of object.pathfinder.options and of the Pathfinder effects, docs/mcp.md and the Pathfinder Options line in docs/target-app-parity.md describe the new rule. --- crates/effects/src/group.rs | 2 +- crates/engine/src/cmd/pathops.rs | 2 +- crates/pathops/src/pathfinder.rs | 8 +++++--- crates/pathops/tests/it/ops.rs | 26 ++++++++++++++++++++++++++ docs/mcp.md | 5 +++-- docs/target-app-parity.md | 2 +- 6 files changed, 37 insertions(+), 8 deletions(-) diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index bebf0e46be..74a24c2442 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -66,7 +66,7 @@ pub const PATHFINDER_EFFECT_PRECISION: std::ops::RangeInclusive = 0.001..=1 /// The documentation of [`PATHFINDER_OPTION_KEYS`], as a literal for `concat!`. macro_rules! options_doc { () => { - "precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing, and a stored value that is not a number evaluates as 0.01; results are refit to within it and pieces thinner than it are dropped; Outline treats crossings closer together than a tolerance multiplied by precision / 0.01 as one point), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)" + "precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing, and a stored value that is not a number evaluates as 0.01; results are refit to within it and pieces thinner than it are dropped; Outline treats crossings closer together than precision / 10000 as one point, or than the tolerance for the art's size when that is larger), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)" }; } diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 9c1b31ce1d..b28cf537dc 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Pathfinder Options…", ["Window", "Pathfinder"], None, - "{precision?: pt 0.001..10 (0.01; how closely the Pathfinder operations follow the paths: results are refit to within it and pieces thinner than it are dropped; Outline treats crossings closer together than a tolerance multiplied by precision / 0.01 as one point), removeRedundantPoints?: bool (false; the results lose the anchors that don't change their shape), removeUnpainted?: bool (false; Divide and Outline leave out the pieces of objects with no fill)} Pathfinder Options, kept in the preferences and used by every later Shape Mode and Pathfinder operation (not Trap); {} reads them → the options", + "{precision?: pt 0.001..10 (0.01; how closely the Pathfinder operations follow the paths: results are refit to within it and pieces thinner than it are dropped; Outline treats crossings closer together than precision / 10000 as one point, or than the tolerance for the art's size when that is larger), removeRedundantPoints?: bool (false; the results lose the anchors that don't change their shape), removeUnpainted?: bool (false; Divide and Outline leave out the pieces of objects with no fill)} Pathfinder Options, kept in the preferences and used by every later Shape Mode and Pathfinder operation (not Trap); {} reads them → the options", always, pathfinder_options ), diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index 1ec916e500..102d7e7138 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -1015,14 +1015,16 @@ fn along_closely(a: &[PathSeg], b: &[PathSeg], tol: f64) -> bool { /// Pathfinder Outline: split every shape's boundary at junctions of the arrangement. Junctions /// closer together than `reach` are one, and coincident edges within ten times it are one edge. -/// `reach` is its value at [`DEFAULT_PRECISION`] times `precision / DEFAULT_PRECISION`, a factor kept -/// within 0.1 to 1000 (Pathfinder Options › Precision's range of 0.001 to 10 pt). +/// `reach` is the larger of the arrangement's tolerance for the art's size and `precision` / 10,000, +/// with `precision` kept within 0.001 to 10 pt (Pathfinder Options › Precision's range), so the +/// default precision gives 0.000001 pt as before. Scaling the art and the precision together scales +/// `reach` by the same amount. fn outline_edges(arr: &Arrangement, shapes: &[Shape], precision: f64) -> Vec { // Sorted by x (then y), so a segment needs only the junctions inside its control box. let junctions = arr.junctions(); let scale = shapes.iter().filter_map(|s| s.path.control_bounds()).map(|r| r.width().max(r.height())).fold(1.0, f64::max); let tol = scale * 1e-7; - let reach = tol.max(1e-6) * (precision / DEFAULT_PRECISION).clamp(0.1, 1000.0); + let reach = tol.max(1e-6 * (precision / DEFAULT_PRECISION).clamp(0.1, 1000.0)); // (chain, key, source index) let mut chains: Vec<(Vec, u64)> = Vec::new(); for s in shapes { diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index def782ffc0..e26d0e69e9 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -254,6 +254,32 @@ fn pf_outline_joins_junctions_closer_than_the_precision() { assert!(close(length(&coarse), length(&at_default), 1e-6), "{} against {}", length(&coarse), length(&at_default)); } +/// Outline at a tenth of the size and a tenth of the precision gives the same pieces at a tenth of +/// the length: crossings 0.05 pt apart on a 1,000 pt square at 10 pt, and 0.005 pt apart on a 100 pt +/// square at 1 pt, stay two junctions in both. +#[test] +fn pf_outline_scales_with_the_art_and_the_precision_together() { + let art = |k: f64| { + vec![ + shape(rect(0.0, 0.0, 1000.0 * k, 1000.0 * k), 1), + shape(rect(500.0 * k, 900.0 * k, 100.0 * k, 200.0 * k), 2), + shape(rect(500.05 * k, 950.0 * k, 49.95 * k, 100.0 * k), 3), + ] + }; + let length = |r: &[Shape]| r.iter().map(|s| s.path.length()).sum::(); + let large = pathfinder_with(PathfinderOp::Outline, &art(1.0), 10.0); + let small = pathfinder_with(PathfinderOp::Outline, &art(0.1), 1.0); + assert_eq!(large.len(), small.len(), "{large:?}\n{small:?}"); + assert!(close(length(&large) / 10.0, length(&small), 1e-6), "{} against {}", length(&large), length(&small)); + let pieces = |r: &[Shape], k: f64| { + let mut l: Vec = r.iter().map(|s| s.path.length() / k).collect(); + l.sort_by(f64::total_cmp); + l + }; + let (a, b) = (pieces(&large, 1.0), pieces(&small, 0.1)); + assert!(a.iter().zip(&b).all(|(x, y)| close(*x, *y, 1e-6)), "{a:?} against {b:?}"); +} + /// Two boundaries that are close only at their start, end and middle stay two edges at 10 pt: an /// ellipse 0.005 pt inside a circle at its rightmost and leftmost points, and 30 pt inside it at /// the top and bottom. Two copies of one boundary are still one edge at that precision. diff --git a/docs/mcp.md b/docs/mcp.md index 675792cd6e..13b4101610 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6257,8 +6257,9 @@ Pathfinder Options: `object.pathfinder.options {precision?, removeRedundantPoint operation uses: `precision` (0.001–10 pt, default 0.01; a string with a unit or a string that is all one number also reads, and any other string, such as `"1abc"`, is an error) is how closely results follow the paths (they are refit to within it and pieces thinner than it are dropped; Outline treats crossings closer together -than a small tolerance as one point and edges that lie within ten times it as one edge, and that tolerance is multiplied by -`precision / 0.01`, so 0.01 keeps it as it was and 10 makes it 1,000 times larger), `removeRedundantPoints` takes the +than `precision / 10000` as one point, or than the tolerance for the art's size when that is larger, and edges that lie +within ten times that distance of each other along their whole length as one edge; 0.01 keeps the earlier output, and +scaling the art and the precision together gives the same pieces at the new size), `removeRedundantPoints` takes the anchors that don't change a result's shape off it, and `removeUnpainted` makes Divide and Outline leave out the pieces of objects with no fill (or only hidden fills). Both default to false; `{}` reads the options. Each Shape Mode and Pathfinder command (`object.pathfinder.unite` … `minusBack`) also takes `precision`, `removeRedundantPoints` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 11cbdf74ef..5df6ceac4f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1707,7 +1707,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Revolve takes type, as its glyph outlines, and groups or layers, whose members sweep about one axis as [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html) describes; a surface can have up to 16,384 profile points, and curves take fewer samples when a surface would pass 163,840 faces (#3617). - Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters). Zig Zag spaces its ridges evenly along each segment, so lines and curves get a regular wave in Corner and Smooth (#1558). Warp › Arc (the effect and Envelope › Make with Warp) bends in the object's real proportions: a circular arc with concentric edges and no fold-over at 100%, so Arc on art that isn't square draws differently from before (#1581, fixes #1578). `effect.apply` and `effect.setParams` give an error for a misspelt or wrongly typed effect parameter instead of running the effect with its default (#1623, #1592). Roughen with Smooth keeps turn-backs smooth instead of making cusps that draw as spikes (#1646, #1643). Scribble draws one zig-zag per region, with no lines across holes and notches; convex shapes are unchanged (#1651, #1648). On the canvas, in Expand Appearance and in exports, Effect → Pathfinder uses the glyph outlines of type in the group, and results painted like the type keep its opacity and blend mode. - Cmd/Ctrl+4 (`pathfinder.repeat`) repeats the last successful Pathfinder panel operation, direct `object.pathfinder.*` command or `command.batch` step (including Actions playback) on the current selection; the panel menu names it. `action.batch`, Trap, compound-shape edits and live effects do not set history. Public references: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html). - - Pathfinder Options ([Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the panel menu's Pathfinder Options… sets Precision (0.001–10 pt: results refit to within it, thinner pieces dropped; Outline treats crossings closer together than a tolerance scaled by it as one point, by VectorCraft's own rule, `pf_outline_joins_junctions_closer_than_the_precision`), Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork (`object.pathfinder.options`, kept in the preferences) for every Shape Mode and Pathfinder operation; the defaults keep the earlier output (`pathops` `precision_drops_pieces_thinner_than_it`, engine `tests_pathops` Pathfinder Options tests, `panels::pathfinder` dialog test). + - Pathfinder Options ([Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the panel menu's Pathfinder Options… sets Precision (0.001–10 pt: results refit to within it, thinner pieces dropped; Outline treats crossings closer together than a ten-thousandth of it as one point, or than the tolerance for the art's size when that is larger, by VectorCraft's own rule, `pf_outline_joins_junctions_closer_than_the_precision`, `pf_outline_scales_with_the_art_and_the_precision_together`), Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork (`object.pathfinder.options`, kept in the preferences) for every Shape Mode and Pathfinder operation; the defaults keep the earlier output (`pathops` `precision_drops_pieces_thinner_than_it`, engine `tests_pathops` Pathfinder Options tests, `panels::pathfinder` dialog test). - Pathfinder on clip groups (#8093): a clip group's members take part in the Shape Modes and Pathfinder buttons (`object.pathfinder.*`) only where its clipping path shows them, so Divide cuts the visible art along the mask and the hidden art goes; nested clip groups cut by each mask, a member the mask hides gives no piece, a cutting line's hidden part cuts nothing, a selected object the masks hide altogether counts as an empty shape where that changes the result (Intersect, Minus Front, Minus Back, Crop), and the clipping path adds no piece of its own (the public documentation doesn't say what Pathfinder does with masked art; our choice, asked on the issue). A cutting line is clipped by sampling, so a part of the mask much narrower than the mask itself can be missed. Make Compound Shape, Trap and the Pathfinder effects still take the members whole. Tests: `crates/engine/src/tests/pathfinder_clip.rs`. - Pathfinder › Trap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html), [Pathfinder panel](https://helpx.adobe.com/illustrator/using/pathfinder-panel-overview.html)): the Pathfinder panel menu's Trap… (`object.pathfinder.trap`) and Effect › Pathfinder › Trap… (`pathfinder.trap`, live on groups) add, where two objects' visible areas of different solid colours meet, a strip of the darker one's area along the edge, filled with the lighter colour at the Tint Reduction percentage and set to overprint (Reverse Traps: the darker colour spreads instead, but not a rich black); Thickness 0.01–5000 pt across vertical edges, Height/Width scales it across horizontal ones, Traps with Process Color paints a swatch colour's trap with its CMYK equivalent; the effect also has Precision and Remove Redundant Points. The panel's Trap is one undo step and groups the traps above the topmost selected object, selected; with no adjoining edges of different colours it says so and changes nothing. Tests: `crates/pathops/src/trap.rs`, `crates/effects/src/trap.rs`, `group::tests::trap_effect_adds_an_overprinting_strip_above_the_members`, `crates/engine/src/tests/trap.rs`, `panels::pathfinder::tests::trap_opens_its_options_and_ok_traps_the_selection`. - Compound shapes ([Create compound shapes with Pathfinder](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html), [Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the Pathfinder panel menu's Make Compound Shape (every member in Add) and Alt-clicking a Shape Mode (every member in that mode) make the two or more selected paths, compound paths, groups, compound shapes or type a live compound shape (`object.compoundShape.make`): a group whose members each keep a shape mode and stay editable, drawn, printed and exported (SVG, PDF and the rest through the baked document) as the area the modes make from the backmost member up, open paths closed, painted with its own appearance, taken from the topmost member not subtracting. With members selected (Direct Selection, Layers panel, isolation mode) a Shape Mode button sets theirs (`object.compoundShape.setMode`) and is lit for the mode they share; with members in different modes selected, each of the four Shape Mode buttons carries a question mark and screen readers report it as mixed, and a click gives every selected member that mode in one undo step ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=368)); paint given to a member goes to the compound shape. Release Compound Shape gives the members back as they were (`object.compoundShape.release`); Expand Compound Shape and the panel's Expand button turn it into the path or compound path of its area (`object.compoundShape.expand`). Shape Modes and Pathfinders take a compound shape as its area. Saved files keep it (`compound_shape`, `shape_mode`; an unknown mode reads as Add). Blends, envelopes and objects with a warp or another geometry effect are members as they draw (a blend's steps, an envelope's distorted art, the warped outline), and the area follows an edit of the blend, envelope or warp; Release gives them back as they were. Tests: `crates/engine/src/tests/compound_shape.rs`, `group::tests::compound_shapes_draw_the_area_their_shape_modes_make`, `group::tests::nested_compound_shapes_take_part_as_their_area`, `panels::pathfinder::tests::compound_shape_items_follow_the_selection`, `panels::pathfinder::tests::shape_modes_show_a_question_mark_while_the_selected_members_modes_differ`, `panels::pathfinder::tests::members_of_two_compound_shapes_are_compared_together`, `panels::pathfinder::tests::shape_modes_show_no_question_mark_without_mixed_members`, the `CompoundShape` op of the property-test strategies. Not yet: hit-testing by the area (a click hits the members). From fe0e4086078c53b0321a482ccf180952f665acfb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 16:15:50 -0800 Subject: [PATCH 069/101] Scripts: zOrder refuses art in a hidden or locked layer, and the same opacity may be assigned - zOrder() on an object in a hidden or locked layer throws Cannot edit and changes nothing, as the other setters do. - Assigning an object the opacity it already has no longer throws when its layer is hidden or locked. hidden and locked are still refused there, whatever the value. - The docs say that a top-level var selection = ... assigns the selection, that the selection order and the tab order of documents differ from the objectReferences page, and that assigning a member a collection lacks throws Not found. Docs: docs/mcp.md. --- crates/engine/src/script/dom.rs | 40 ++++++++++++++++++--------- crates/engine/src/tests/script_dom.rs | 29 +++++++++++++++---- docs/mcp.md | 23 +++++++++------ 3 files changed, 65 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7b9df28106..8b68a39250 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -20,17 +20,20 @@ //! describes; here //! that holds for `activeDocument`, `documents` and `selection`. //! -//! VectorCraft's own rules, which the help pages do not state: +//! VectorCraft's own rules: //! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever -//! order they were selected or made in. +//! order they were selected or made in. The objectReferences page above says instead that the +//! first object is the one last added to the page; VectorCraft does not follow that sentence. //! - A collection read with a name that nothing has throws `Not found`, and `"name" in pageItems` is //! false then. Assigning to such a name throws the same error. //! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the -//! active document's selection. Assigning `documents` keeps its value. -//! - Collections list documents in tab order. `pageItems` lists every object, with the objects -//! inside groups and compound paths after the group or compound path, and leaves out layers and -//! ruler guides. An index out of range gives `undefined`; `index` and `getByName` throw -//! `Not found` when nothing matches. +//! active document's selection. A top-level `var selection = ...` does the same and does +//! not make a variable of the script. Assigning `documents` keeps its value. +//! - Collections list documents in tab order. The objectReferences page says `documents[0]` is +//! always the active document; VectorCraft does not follow that yet. +//! - `pageItems` lists every object, with the objects inside groups and compound paths after the +//! group or compound path, and leaves out layers and ruler guides. An index out of range gives +//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches. //! - Script coordinates are points with Y up from the bottom of the first artboard //! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of //! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run. @@ -1265,7 +1268,14 @@ fn selection_of(h: &Host, uid: u64) -> Answer { } else { let all = page_items(h, st); h.charge_call(all.len() as u64)?; - all.iter().copied().filter(|i| picked.contains(i)).collect() + let mut ids: Vec = all.iter().copied().filter(|i| picked.contains(i)).collect(); + // A selected object that `pageItems` does not list still comes last, in the order it was + // selected. + if ids.len() < picked.len() { + let mut listed: HashSet = ids.iter().copied().collect(); + ids.extend(st.selection.objects.iter().copied().filter(|i| picked.contains(i) && listed.insert(*i))); + } + ids }; h.charge_call(16 * ids.len() as u64)?; Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) @@ -1509,8 +1519,8 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// Refuses a change to the item's appearance, place or size while a layer it is in is hidden or -/// locked. Its name and note may still change. +/// Refuses a change to the item's appearance, place, stacking order or size while a layer it is in +/// is hidden or locked. Its name and note may still change. fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> { let refused = with_doc(h, item.doc, |_, st| { let d = &st.doc; @@ -1555,10 +1565,13 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { // A value the getter reports for the item's opacity sends the opacity it has, and // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still // replaces the one the graph keeps for its series or kind. + // The opacity the item already has may be assigned while its layer is hidden or locked. let item = this_item(h, a)?; - refuse_in_closed_layer(h, item)?; let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0)); - let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v); + let Some(v) = now.filter(|now| (now - v).abs() < 1e-4) else { + refuse_in_closed_layer(h, item)?; + return set_props(h, a, |_| false, json!({"opacity": v})); + }; set_props(h, a, |_| false, json!({"opacity": v})) } @@ -1923,7 +1936,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { } /// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a -/// compound path is refused. +/// compound path is refused, and so is an object in a hidden or locked layer. fn item_z_order(h: &Host, a: &[Data]) -> Answer { let id = match arg(a, 1) { Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront", @@ -1936,6 +1949,7 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into())); } + refuse_in_closed_layer(h, item)?; let (before, after) = with_doc(h, item.doc, |_, st| { let at = st.doc.position(item.id); let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 68a485c8de..e2a61ec18d 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1509,6 +1509,7 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { let (mut s, a, b) = doc(); let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + rect(&mut s, 300.0, 200.0, 20.0, 20.0); for (id, name) in [(a, "locked"), (b, "free"), (c, "closed")] { s.execute("object.setProps", &json!({"ids": [id.0], "name": name})).unwrap(); } @@ -1517,7 +1518,20 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), ] { s.execute("object.setProps", &on).unwrap(); - for set in ["opacity = 50", "hidden = true", "locked = true", "left = 5", "top = 5", "position = [5, 5]", "width = 10", "height = 10"] { + // `hidden` and `locked` are refused even when the value is the one the object has. + for set in [ + "opacity = 50", + "hidden = true", + "hidden = false", + "locked = true", + "locked = false", + "left = 5", + "top = 5", + "position = [5, 5]", + "width = 10", + "height = 10", + "zOrder(ZOrderMethod.BRINGTOFRONT)", + ] { let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); // The change made before the refusal is put back with the rest of the run. let e = failure(&mut s, &format!("var p = app.activeDocument.pageItems; p.getByName('free').opacity = 20; p.getByName('closed').{set};")); @@ -1527,10 +1541,10 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { } let out = log( &mut s, - "var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; vc.log([c.name, c.note]);\ - c.name = 'closed'; c.note = '';", + "var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; c.opacity = c.opacity;\ + vc.log([c.name, c.note, c.opacity]); c.name = 'closed'; c.note = '';", ); - assert_eq!(out, vec![json!(["renamed", "n"])], "{on}"); + assert_eq!(out, vec![json!(["renamed", "n", 100])], "{on}"); s.execute("object.setProps", &off).unwrap(); } s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); @@ -1595,8 +1609,13 @@ fn the_application_members_can_be_named_without_app() { ); assert_eq!(out, vec![json!(0), json!(2), json!([1, true]), json!([1, "object"])]); assert_eq!(s.active().unwrap().selection.objects, vec![b]); + // A top-level `var selection = []` clears the selection; a push goes to a list nobody keeps. + let out = log(&mut s, "var selection = []; selection.push(app.activeDocument.pageItems[0]); vc.log(selection.length);"); + assert_eq!(out, vec![json!(0)]); + assert!(s.active().unwrap().selection.objects.is_empty()); assert!(failure(&mut s, "activeDocument = 5;").contains("not a Document")); - failure(&mut s, "'use strict'; documents = 5;"); + let e = failure(&mut s, "'use strict'; documents = 5;"); + assert!(e.contains("TypeError") && e.contains("cannot assign to property 'documents': it has only a getter"), "{e}"); // With no document open, reading `activeDocument` throws as `app.activeDocument` does. let mut s = Session::new(); assert!(failure(&mut s, "activeDocument;").contains("No active document")); diff --git a/docs/mcp.md b/docs/mcp.md index cef9a0af60..d05579f7e3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2625,9 +2625,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.selection` (assigning it sets the active document's selection), `app.coordinateSystem` and `app.getIsFileOpen(path)`. A script may name the application's members without `app.`, as [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) - describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. Assigning `activeDocument` or `selection` without `app.`, as `var selection = ...` at the top level also - does, assigns the application's member, and assigning `documents` keeps its value (VectorCraft's own rule). - `app.documents` + describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. VectorCraft's own rules: + assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level + `var selection = ...` does the same and does not make a variable of the script. Assigning `documents` keeps its + value. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of @@ -2670,8 +2671,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer - throws `Cannot edit` and changes nothing, while its `name` and `note` still change; an object that is hidden or - locked itself takes them (VectorCraft's own rule). `move` with the object itself as the relative object and + throws `Cannot edit` and changes nothing, even when the value is the one the object has, except for `opacity`, and + `zOrder()` on such an object throws `Cannot edit` too. Its `name` and `note` still change, and an object that is + hidden or locked itself takes all of them (VectorCraft's own rule). `move` with the object itself as the relative object and `PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` takes the last path out of a compound path, the compound path stays, empty, so a script that holds it can still read it. An object with nothing in it, such as an empty group or that compound path, reads its bounds, `position`, `width` and `height` @@ -2685,7 +2687,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `pageItems` lists the art topmost first, as the example on [CMYKColor](https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/) reads the frontmost path as `pathItems[0]`, and a document's `selection` lists the selected objects in the same order, whatever order they were selected or - made in (VectorCraft's own rule). A collection read with a name, such as `pageItems["Logo"]` or + made in. This is VectorCraft's own rule: the page cited below says the first object in a selection is the one last + added to the page, and VectorCraft does not follow that sentence. A collection read with a name, such as `pageItems["Logo"]` or `documents["Untitled-1"]`, gives the object `getByName` gives, as [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws @@ -2693,7 +2696,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` takes a number or a Boolean as the text `String(value)` gives. `String(object)` gives `[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document ]`, `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). - VectorCraft's own rules: documents are listed in tab order, and page items with the + Documents are listed in tab order; the same page says `documents[0]` is always the active document, and + VectorCraft does not follow that yet. VectorCraft's own rules: page items are listed with the objects inside groups and compound paths after their group and without layers and ruler guides. A document's `selection`, and `app.selection` while a document is open, is an empty list when nothing is selected. Script coordinates are points with Y up from the bottom-left corner of the first artboard, or, with @@ -2721,8 +2725,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the other properties but not the methods. `Object.keys`, `Object.getOwnPropertyNames` and - `Object.getOwnPropertyDescriptor` do not report those members. Assigning a member that an object's class does not - have does not keep the value and does not throw. Other members + `Object.getOwnPropertyDescriptor` do not report those members. Assigning a member that a page item, a layer, a + document or the application does not have does not keep the value and does not throw; on a collection it throws `Not found`, + as described above. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and From 112eacbb1c50da15169de201932f30d91f293f00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 16:15:51 -0800 Subject: [PATCH 070/101] Scripts: remove() keeps an emptied compound path, and note takes numbers - remove() on the last path of a compound path keeps the compound path, empty, as move() does, so a script that holds it can still read it. edit.clear takes keepEmpty: true for this, and passes it on to path.deleteAnchors when it deletes direct-selected anchors; without it, Clear still deletes a compound path it empties. - note, like name, takes a number or a Boolean as the text String() gives it. - Assigning a graph mark or label the opacity it already has throws Cannot edit in a hidden or locked layer when the graph keeps another opacity for its series or kind, since the assignment would still change the graph. - Only the exact opacity the getter reports counts as the opacity an object already has; a value that differs from it by less than 0.0001 is now applied instead of being dropped. - Reading a document's selection orders only the selected objects, by their place in the tree, so its cost no longer grows with the size of the document. - docs/mcp.md: the opacity exception, note, keepEmpty, and that strict-mode code throws a TypeError when it assigns a member an object lacks. Docs: docs/mcp.md. --- crates/engine/src/cmd/edit.rs | 10 +- crates/engine/src/cmd/path.rs | 19 ++- crates/engine/src/script/dom.rs | 94 ++++++++----- crates/engine/src/tests/script_dom.rs | 187 ++++++++++++++++++++++---- docs/mcp.md | 54 ++++---- 5 files changed, 268 insertions(+), 96 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index c8b9785fe9..6e08795146 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -225,7 +225,7 @@ pub fn specs() -> Vec { "Clear", ["Edit"], Some("Delete"), - "{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected", + "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected", has_selection_or_guides, clear ), @@ -1221,6 +1221,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; + let keep_empty = switch_or(p, "keepEmpty", false, "edit.clear")?; let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; // An object of a symbol instance's art can't be removed from the instance alone. if explicit.is_none() && s.doc()?.selection.symbol_part.is_some() { @@ -1252,8 +1253,11 @@ fn clear(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Clear", |d, sel| { - let parents: Vec<_> = - ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect(); + let parents: Vec<_> = if keep_empty { + Vec::new() + } else { + ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect() + }; d.remove_many(&ids)?; for p in parents { if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) { diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index d32594d92d..9c41b7c78d 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Delete Anchor Points", [], None, - "{} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key)", + "{keepEmpty?: bool (keep a compound path left with no members)} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key)", has_anchors, delete_anchors ), @@ -1654,6 +1654,7 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result { pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { // `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step. let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?; + let keep_empty = switch_or(p, "keepEmpty", false, "path.deleteAnchors")?; let st = s.doc()?; let sel = st.selection.anchors.clone(); let segments = st.selection.segments.clone(); @@ -1671,12 +1672,16 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { .copied() .filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor))) .collect(); - // The compound paths that hold a deleted object; one left with no members goes too. - let compounds: BTreeSet = whole_ids - .iter() - .chain(sel.keys()) - .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) - .collect(); + // The compound paths that hold a deleted object; one left with no members goes too, unless `keepEmpty`. + let compounds: BTreeSet = if keep_empty { + BTreeSet::new() + } else { + whole_ids + .iter() + .chain(sel.keys()) + .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) + .collect() + }; if !whole_ids.is_empty() { d.remove_many(&whole_ids)?; } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8b68a39250..39c740cb2e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -43,9 +43,14 @@ //! must be one of that document's that can be selected, or nothing changes. //! - Members the help pages list that are not here yet throw an error that says so. //! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an -//! object in a hidden or locked layer throws `Cannot edit` and changes nothing; its `name` and -//! `note` still change. An object that is hidden or locked itself, or is in a hidden or locked -//! group, takes them. +//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change +//! nothing, even for the value the object has. The exception is `opacity` given the value the +//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps +//! another opacity it would still change the graph, so it is refused too. Its `name` and `note` +//! still change. An object that is hidden or locked itself, or is in a hidden or locked group, +//! takes them. +//! - `name` and `note` take a number or a Boolean as the text `String(value)` gives. +//! - A compound path whose last path `move` or `remove()` takes out stays, empty. //! - An object with nothing in it, such as an empty group or a compound path whose paths moved out, //! reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing. @@ -1263,21 +1268,28 @@ fn selection_of(h: &Host, uid: u64) -> Answer { if picked.len() > MAX_LISTED { return Err(HostError::Range(format!("the selection has more than {MAX_LISTED} objects"))); } - let ids: Vec = if picked.is_empty() { - Vec::new() - } else { - let all = page_items(h, st); - h.charge_call(all.len() as u64)?; - let mut ids: Vec = all.iter().copied().filter(|i| picked.contains(i)).collect(); - // A selected object that `pageItems` does not list still comes last, in the order it was - // selected. - if ids.len() < picked.len() { - let mut listed: HashSet = ids.iter().copied().collect(); - ids.extend(st.selection.objects.iter().copied().filter(|i| picked.contains(i) && listed.insert(*i))); + // Only the selected objects are ordered, by their place in the tree, so the cost follows the + // size of the selection and not of the document. `pageItems` walks each list of children + // topmost first and puts a group before the objects in it: a higher index comes first, and an + // ancestor's path, a prefix of its descendants' paths, sorts before them. + let mut placed: Vec<(Vec>, NodeId)> = Vec::with_capacity(picked.len()); + let mut unplaced: Vec = Vec::new(); + let mut seen: HashSet = HashSet::with_capacity(picked.len()); + let mut steps = 0u64; + for id in st.selection.objects.iter().copied().filter(|i| picked.contains(i) && seen.insert(*i)) { + match st.doc.index_path(id) { + Some(path) => { + steps += path.len() as u64; + placed.push((path.into_iter().map(std::cmp::Reverse).collect(), id)); + } + // A selected object outside the tree's walk still comes last, in the order it was + // selected. + None => unplaced.push(id), } - ids - }; - h.charge_call(16 * ids.len() as u64)?; + } + placed.sort(); + let ids: Vec = placed.into_iter().map(|(_, id)| id).chain(unplaced).collect(); + h.charge_call(steps + 16 * ids.len() as u64)?; Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) } @@ -1482,15 +1494,20 @@ fn set_props(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Node) -> Ok(Data::Undefined) } +/// The text a string property such as `name` or `note` is given: a number or a Boolean becomes the +/// text `String(value)` gives, and any other value that is not a string is refused. +fn text_arg(v: &Data, what: &str) -> std::result::Result { + match v { + Data::String(s) => Ok(s.clone()), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + Data::Bool(b) => Ok(b.to_string()), + _ => Err(HostError::Type(format!("{what} must be a string"))), + } +} + /// `name = value`: a number or a Boolean becomes the text `String(value)` gives. fn item_set_name(h: &Host, a: &[Data]) -> Answer { - let name = match arg(a, 1) { - Data::String(s) => s.clone(), - Data::Number(n) => vectorcraft_js::number_to_string(*n), - Data::Bool(b) => b.to_string(), - _ => return Err(HostError::Type("name must be a string".into())), - }; - let name = &name; + let name = &text_arg(arg(a, 1), "name")?; if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } @@ -1505,9 +1522,10 @@ fn item_note(h: &Host, a: &[Data]) -> Answer { read_item(h, a, |_, n| Ok(text(note_of(n)))) } -/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. +/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number +/// or a Boolean becomes the text `String(value)` gives. fn item_set_note(h: &Host, a: &[Data]) -> Answer { - let Data::String(note) = arg(a, 1) else { return Err(HostError::Type("note must be a string".into())) }; + let note = &text_arg(arg(a, 1), "note")?; if note.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the note is too long".into())); } @@ -1565,14 +1583,21 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { // A value the getter reports for the item's opacity sends the opacity it has, and // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still // replaces the one the graph keeps for its series or kind. - // The opacity the item already has may be assigned while its layer is hidden or locked. + // The opacity the item already has may be assigned while its layer is hidden or locked, unless + // it would still replace the opacity a graph keeps for the item's series or kind. let item = this_item(h, a)?; - let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0)); - let Some(v) = now.filter(|now| (now - v).abs() < 1e-4) else { + let (now, keeps_other) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + // Only the exact number the getter reports counts as the same opacity. + let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v); + let keeps_other = + crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]); + (now, keeps_other) + }); + if now.is_none() || keeps_other { refuse_in_closed_layer(h, item)?; - return set_props(h, a, |_| false, json!({"opacity": v})); - }; - set_props(h, a, |_| false, json!({"opacity": v})) + } + set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) } fn item_selected(h: &Host, a: &[Data]) -> Answer { @@ -1731,7 +1756,7 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { /// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or /// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`] -/// refuses it. +/// refuses it. A compound path whose last path this is stays, empty. fn item_remove(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (whole, on_locked) = with_doc(h, item.doc, |_, st| { @@ -1743,7 +1768,8 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } - edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?; + // A compound path whose last path this is stays, empty, as it does after `move`. + edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?; Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e2a61ec18d..4e705538d9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -242,6 +242,20 @@ fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 50})).unwrap(); assert_eq!(kept(&s), Some(0.5)); s.execute("object.setProps", &json!({"id": series(&s)[1].0, "name": "mark"})).unwrap(); + // In a hidden or locked layer the same assignment would still change the graph, so it is refused. + let layer = s.active().unwrap().doc.layers[0].id; + for (on, off) in [ + (json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})), + (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), + ] { + s.execute("object.setProps", &on).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "var m = app.activeDocument.pageItems.getByName('mark'); m.opacity = m.opacity;"); + assert!(e.contains("Cannot edit"), "{on}: {e}"); + assert_eq!(kept(&s), Some(0.5), "{on}"); + assert_eq!(undo_steps(&s), steps, "{on}"); + s.execute("object.setProps", &off).unwrap(); + } log(&mut s, "app.activeDocument.pageItems.getByName('mark').opacity = 100;"); assert_eq!(kept(&s), None); } @@ -256,6 +270,12 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(out, vec![json!(33.3333)]); assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); assert_eq!(undo_steps(&s), steps); + // A value close to the reported one but not equal to it is still applied. + s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); + let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); + log(&mut s, "app.activeDocument.pageItems[1].opacity = 50.00005;"); + assert!(s.active().unwrap().doc.node(a).unwrap().opacity > before, "the assigned opacity was applied"); + assert_eq!(undo_steps(&s), steps + 1); } #[test] @@ -524,6 +544,54 @@ fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() { assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); } +/// `remove()` on the last path of a compound path keeps the compound path, empty, as `move` does, +/// and a document holding it saves, reopens, exports and releases it. +#[test] +fn removing_the_last_path_of_a_compound_path_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.pageItems[0]; d.pageItems[2].remove(); d.pageItems[1].remove();\ + vc.log([c.typename, d.pageItems.length, c === d.pageItems[0]]);", + ); + assert_eq!(out, vec![json!(["CompoundPathItem", 1, true])]); + let doc = s.active().unwrap().doc.clone(); + assert!(doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); + assert!(s.execute("edit.clear", &json!({"ids": [compound.0], "keepEmpty": 1})).is_err(), "keepEmpty must be a boolean"); + // The native format keeps it, and the other writers and Release Compound Path accept it. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert!(back.node(compound).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.children().is_some_and(|c| c.is_empty()))); + for format in ["svg", "pdf", "vectorcraft"] { + s.execute("document.export", &json!({"format": format})).unwrap_or_else(|e| panic!("{format}: {e}")); + } + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + s.execute("object.compoundPath.release", &json!({})).unwrap(); +} + +/// Clear with `keepEmpty` keeps the emptied compound path also when it deletes direct-selected +/// anchors, and without it deletes the compound path as before. +#[test] +fn clearing_anchors_with_keep_empty_keeps_the_compound_path() { + for keep in [true, false] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + for (id, mode) in [(a, "set"), (b, "add")] { + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": mode})).unwrap(); + } + s.execute("edit.clear", &json!({"keepEmpty": keep})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none(), "keepEmpty {keep}: both paths are deleted"); + assert_eq!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), keep, "keepEmpty {keep}"); + } +} + #[test] fn a_copy_of_an_object_with_a_large_id_is_the_copy() { let mut s = Session::new(); @@ -921,7 +989,12 @@ fn note_is_the_attributes_note() { assert_eq!(undo_steps(&s), steps + 1); log(&mut s, "app.activeDocument.pageItems[1].note = 'check bleed';"); assert_eq!(undo_steps(&s), steps + 1, "the same note adds no step"); - assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = 5;").contains("note must be a string")); + // A number or a Boolean becomes its text, as it does for `name`. + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; i.note = 5; vc.log([typeof i.note, i.note]); i.note = true; vc.log(i.note);"); + assert_eq!(out, vec![json!(["string", "5"]), json!("true")]); + for value in ["null", "undefined", "{}"] { + assert!(failure(&mut s, &format!("app.activeDocument.pageItems[0].note = {value};")).contains("note must be a string"), "{value}"); + } assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long")); } @@ -1332,24 +1405,20 @@ fn unsupported_members_say_so() { assert!(failure(&mut s, "app.activeDocument.layers;").contains("Document.layers is not available yet")); } -/// A script that lowers each selected object's opacity by 10 points, checking each member with -/// `hasOwnProperty` and the selection's `length` first, as scripts written for the object model do. -const LOWER_OPACITY: &str = "\ - var doc = app.activeDocument;\ - var sel = doc.selection;\ - if (sel.length === 0) { alert('Nothing selected.'); }\ - else {\ - var done = 0;\ - for (var i = 0; i < sel.length; i++) {\ - var item = sel[i];\ - if (item.hasOwnProperty('opacity') && typeof item.opacity === 'number') {\ - item.opacity = Math.max(0, item.opacity - 10);\ - done++;\ - }\ - if (item.hasOwnProperty('blendingMode')) { item.blendingMode; }\ - }\ - if (done === 0) { alert('No object with an opacity.'); }\ - }"; +/// A script that names each visible selected object after its place in `app.selection`, testing +/// the members it uses with `hasOwnProperty` and `propertyIsEnumerable` first. A member that is not +/// available yet, such as `blendingMode`, is read only when `hasOwnProperty` reports it, so it is +/// never read. +const NAME_PICKED: &str = "\ + var picked = app.selection, k = picked.length, named = 0;\ + if (!k) alert('Select something first.');\ + while (k--) {\ + var obj = picked[k];\ + var usable = obj.propertyIsEnumerable('name') && obj.hasOwnProperty('hidden') && !obj.hidden;\ + if (obj.hasOwnProperty('blendingMode') && obj.blendingMode) usable = false;\ + if (usable) { obj.name = 'picked ' + k; named += 1; }\ + }\ + if (picked.length && named < picked.length) alert('Some objects were skipped.');"; #[test] fn a_script_that_checks_has_own_property_changes_every_kind_of_selected_object() { @@ -1364,20 +1433,40 @@ fn a_script_that_checks_has_own_property_changes_every_kind_of_selected_object() s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap(); s.execute("object.compoundPath.make", &json!({})).unwrap(); let compound = s.active().unwrap().selection.objects[0]; - s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 55})).unwrap(); - s.execute("object.setProps", &json!({"ids": [text.0], "opacity": 5})).unwrap(); let objects = [path, group, text, compound]; s.execute("select.set", &json!({"ids": objects.iter().map(|n| n.0).collect::>()})).unwrap(); - let opacities = |s: &Session| -> Vec { + let names = |s: &Session| -> Vec> { let d = &s.active().unwrap().doc; - objects.iter().map(|n| (f64::from(d.node(*n).unwrap().opacity) * 1000.0).round() / 10.0).collect() + objects.iter().map(|n| d.node(*n).unwrap().name.clone()).collect() + }; + let before = names(&s); + let steps = undo_steps(&s); + // The run shows no alert: without an answer for one, it would stop there. + let r = run(&mut s, NAME_PICKED).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["dialogs"], json!([]), "{r}"); + let after = names(&s); + assert!(after.iter().all(|n| n.as_deref().is_some_and(|n| n.starts_with("picked "))), "every kind was named: {after:?}"); + assert_eq!(after.iter().collect::>().len(), objects.len(), "each got its own name: {after:?}"); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(names(&s), before); + // Opacity reads and writes on every kind too: each object goes to its own value, read back from the script. + s.execute("select.set", &json!({"ids": objects.iter().map(|n| n.0).collect::>()})).unwrap(); + let opacities = |s: &Session| -> Vec { + let d = &s.active().unwrap().doc; + objects.iter().map(|n| d.node(*n).unwrap().opacity).collect() }; let before = opacities(&s); let steps = undo_steps(&s); - // The run shows no alert: without an answer for one, it would stop there. - let r = run(&mut s, LOWER_OPACITY).unwrap_or_else(|e| panic!("{e}")); - assert_eq!(r["dialogs"], json!([]), "{r}"); - assert_eq!(opacities(&s), vec![90.0, 45.0, 0.0, 90.0]); + let out = log( + &mut s, + "var sel = app.activeDocument.selection, read = [];\ + for (var i = 0; i < sel.length; i++) { sel[i].opacity = 20 + 10 * i; read.push(sel[i].opacity); }\ + vc.log(read);", + ); + assert_eq!(out, vec![json!([20, 30, 40, 50])]); + let after = opacities(&s); + assert!(after.iter().zip(&before).all(|(a, b)| a < b), "every kind got a lower opacity: {before:?} -> {after:?}"); assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(opacities(&s), before); @@ -1390,8 +1479,8 @@ fn the_selection_is_an_empty_list_when_nothing_is_selected() { let out = log(&mut s, "var d = app.activeDocument; vc.log([d.selection instanceof Array, d.selection.length, app.selection.length]);"); assert_eq!(out, vec![json!([true, 0, 0])]); let steps = undo_steps(&s); - let r = s.execute("script.run", &json!({"source": LOWER_OPACITY, "name": "t.js", "answers": [{"kind": "alert", "value": "ok"}]})).unwrap(); - assert_eq!(r["dialogs"][0]["message"], json!("Nothing selected."), "{r}"); + let r = s.execute("script.run", &json!({"source": NAME_PICKED, "name": "t.js", "answers": [{"kind": "alert", "value": "ok"}]})).unwrap(); + assert_eq!(r["dialogs"][0]["message"], json!("Select something first."), "{r}"); assert_eq!(undo_steps(&s), steps); } @@ -1484,6 +1573,41 @@ fn page_items_and_the_selection_list_the_topmost_object_first() { assert_eq!(out, vec![json!(["top", "last", "last"])]); } +/// The selection lists a group before the objects in it, in `pageItems`' order, and reading it +/// costs as much in a large document as in a small one. +#[test] +fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, c.0, group]})).unwrap(); + let source = "var d = app.activeDocument, want = [], got = [];\ + for (var i = 0; i < d.pageItems.length; i++) if (d.pageItems[i].selected) want.push(d.pageItems[i].typename + i);\ + for (var i = 0; i < d.pageItems.length; i++) for (var j = 0; j < d.selection.length; j++)\ + if (d.selection[j] === d.pageItems[i]) got[j] = d.pageItems[i].typename + i;\ + vc.log([want, got]);"; + let out = log(&mut s, source); + assert_eq!(out[0][0], out[0][1], "the selection is in pageItems' order"); + assert_eq!(out[0][0].as_array().map(Vec::len), Some(3)); + // Each pass edits the document, so nothing kept from the last read can be reused. + let edits = "var d = app.activeDocument; for (var i = 0; i < 50; i++) d.selection[0].opacity = 50 + i % 2;"; + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + let small = run(&mut s, edits).unwrap()["fuelUsed"].as_u64().unwrap(); + // 3 objects doubled 11 times: 6,144. + s.execute("select.all", &json!({})).unwrap(); + for _ in 0..11 { + s.execute("edit.duplicate", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + } + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let large = run(&mut s, edits); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let large = large.unwrap_or_else(|e| panic!("the reads in a large document went over: {e}"))["fuelUsed"].as_u64().unwrap(); + assert_eq!(small, large); +} + /// A collection read with a name gives what `getByName` gives, and throws as it does for no match. #[test] fn a_collection_read_with_a_name_gives_the_named_object() { @@ -1632,6 +1756,11 @@ fn assigning_a_name_a_collection_lacks_throws() { } let out = log(&mut s, "var p = app.activeDocument.pageItems; p[0] = 3; vc.log(typeof p[0]);"); assert_eq!(out, vec![json!("object")]); + // On a page item the value is not kept; strict-mode code throws instead. + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.qux = 4; vc.log(typeof i.qux);"); + assert_eq!(out, vec![json!("undefined")]); + let e = failure(&mut s, "'use strict'; app.activeDocument.pageItems[0].qux = 4;"); + assert!(e.contains("TypeError") && e.contains("qux"), "{e}"); assert_eq!(undo_steps(&s), steps); } diff --git a/docs/mcp.md b/docs/mcp.md index d05579f7e3..d3e47680f1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2671,29 +2671,33 @@ app through the global object `vc`, and writes to the Script Console and runs ot locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer - throws `Cannot edit` and changes nothing, even when the value is the one the object has, except for `opacity`, and - `zOrder()` on such an object throws `Cannot edit` too. Its `name` and `note` still change, and an object that is - hidden or locked itself takes all of them (VectorCraft's own rule). `move` with the object itself as the relative object and - `PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` takes the last path out of - a compound path, the compound path stays, empty, so a script that holds it can still read it. An object with - nothing in it, such as an empty group or that compound path, reads its bounds, `position`, `width` and `height` - as zeros, and assigning them does nothing (VectorCraft's own rule). `duplicate` on a path inside a compound path throws + throws `Cannot edit` and changes nothing, even when the value is the one the object has, and `zOrder()` on such + an object throws `Cannot edit` too. The one exception is `opacity` given the value the object already has, which + changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity, that + value would still change the graph, so it throws `Cannot edit` as well. Its `name` and `note` still change, and an + object that is hidden or locked itself takes all of them (VectorCraft's own rule). `move` with the object itself + as the relative object and `PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` + or `remove()` takes the last path out of a compound path, the compound path stays, empty, so a script that holds + it can still read it (`remove()` runs `edit.clear` with `keepEmpty: true`). An object with nothing in it, such + as an empty group or that compound path, reads its bounds, `position`, `width` and `height` as zeros, and + assigning them does nothing (VectorCraft's own rule). `duplicate` on a path inside a compound path throws `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws - `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the - same object when the image is embedded: the next read gives that object, now a `RasterItem`. The - enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, + `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that + holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a + `RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. `pageItems` lists the art topmost first, as the example on [CMYKColor](https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/) reads the frontmost path as `pathItems[0]`, and a document's `selection` lists the selected objects in the same order, whatever order they were selected or made in. This is VectorCraft's own rule: the page cited below says the first object in a selection is the one last - added to the page, and VectorCraft does not follow that sentence. A collection read with a name, such as `pageItems["Logo"]` or - `documents["Untitled-1"]`, gives the object `getByName` gives, as + added to the page, and VectorCraft does not follow that sentence. A collection read with a name, such as + `pageItems["Logo"]` or `documents["Untitled-1"]`, gives the object `getByName` gives, as [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws `Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too - (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` takes a number or a Boolean as the text `String(value)` gives. `String(object)` gives + (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note` + take a number or a Boolean as the text `String(value)` gives. `String(object)` gives `[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document ]`, `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). Documents are listed in tab order; the same page says `documents[0]` is always the active document, and @@ -2706,11 +2710,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each changed document. A value that changes nothing runs no command, and a change to another document leaves the active tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers - panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine - kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a - hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw - `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` - when any object is on one, throw `cannot delete objects on a locked artboard` and delete nothing. Setting `width` or `height` scales the object along + panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was + deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that + is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` + when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on + a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` + and delete nothing. Setting `width` or `height` scales the object along the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, @@ -2725,9 +2730,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the other properties but not the methods. `Object.keys`, `Object.getOwnPropertyNames` and - `Object.getOwnPropertyDescriptor` do not report those members. Assigning a member that a page item, a layer, a - document or the application does not have does not keep the value and does not throw; on a collection it throws `Not found`, - as described above. Other members + `Object.getOwnPropertyDescriptor` do not report any member of the class. Assigning a member that a page item, a + layer, a document or the application does not have does not keep the value; it does not throw, except in + strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, as described above. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and @@ -3381,7 +3386,8 @@ or unknown id leaves the document unchanged. An empty `ids` array does nothing. are kept, and selecting an ancestor together with its descendants deletes that subtree once. Without `ids`, direct-selected anchors or selected ruler guides retain their usual Clear behavior. With `ids`, `guides: true` also deletes the selected ruler guides. The command rejects a `guides` value that is not a -boolean. +boolean. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given, which keeps it, empty, +also when the deleted parts are direct-selected anchors; a `keepEmpty` value that is not a boolean is rejected. `edit.copy` takes a compound-path member selected on its own (whole or in part, with Direct or Group Selection) as an ordinary path with the compound's paint, transparency, opacity mask and fill rule. The path is linked to the compound's @@ -6992,7 +6998,9 @@ their facing handles are refitted so one cubic follows the two old segments; two The anchor after each removed one is then selected (the one before at an open path's end), so running `path.removeAnchors` again goes on along the path. `path.removeAnchor {id, subpath?, anchor}` (the Delete Anchor Point tool) removes one anchor the same way, and -`path.deleteAnchors {}` (the Delete key) deletes the selected anchors with their segments, opening closed paths there. +`path.deleteAnchors {keepEmpty?}` (the Delete key) deletes the selected anchors with their segments, opening closed paths +there. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given; `edit.clear` passes its +`keepEmpty` on when it deletes direct-selected anchors. ```json {"name":"run_command","arguments":{"command":"select.anchors","params":{"id":12,"anchors":[[0,1],[0,3]]}}} From 2447f9e35835440bc22ef9f8a7387bf4341cb6cc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 16:27:19 -0800 Subject: [PATCH 071/101] UI: dialog and panel labels, separators and notices use Text, Divider and Notice Labels drawn with raw `ui.label` and `ui.weak` in the Export As, DXF, EPS, HP-GL, PNG, Simplify, Map Art, Print and Save Options dialogs and in the Graphic Styles and Layers panels now use the framework's Text, so each one is in the accessibility tree. The hints under the export dialogs and the Layers footer count use the caption role in the muted shade. The Print Summary rows are selectable text named Pages, Options and Warnings. The Stroke panel and the Swatches library menu draw their separators with Divider. The HP-GL pen error and the kinsoku set problem show as an inline Notice in the bad tone and are announced as alerts, and the legacy .ai artboard note shows as an info Notice. The Art Brush Options Direction segments are arrow icons with the tooltips Left to Right, Right to Left, Top to Bottom and Bottom to Top, and a screen reader reads those names instead of the arrow glyphs. The app's icon set gains left and right arrows drawn like the existing up and down arrows. --- ASSETS.md | 2 + assets/icons/dc-arrow-left.svg | 1 + assets/icons/dc-arrow-right.svg | 1 + .../ui-egui/src/dialogs/brush_art_options.rs | 13 ++-- .../src/dialogs/brush_options/tests.rs | 18 ++++++ crates/ui-egui/src/dialogs/dxf_options.rs | 15 +++-- crates/ui-egui/src/dialogs/eps_options.rs | 14 ++++- crates/ui-egui/src/dialogs/export_as.rs | 6 +- crates/ui-egui/src/dialogs/hpgl_options.rs | 15 +++-- crates/ui-egui/src/dialogs/kinsoku_sets.rs | 7 ++- crates/ui-egui/src/dialogs/path_ops.rs | 3 +- crates/ui-egui/src/dialogs/png_options.rs | 2 +- crates/ui-egui/src/dialogs/print.rs | 14 ++--- crates/ui-egui/src/dialogs/save_options.rs | 5 +- .../ui-egui/src/dialogs/save_options/tests.rs | 23 +++++++ crates/ui-egui/src/dialogs/tests_export.rs | 61 +++++++++++++++++++ crates/ui-egui/src/dialogs/tests_modal.rs | 12 ++++ crates/ui-egui/src/dialogs/tests_print.rs | 17 ++++++ crates/ui-egui/src/dialogs/three_d_classic.rs | 4 +- crates/ui-egui/src/icon_data.rs | 2 + crates/ui-egui/src/panels/graphic_styles.rs | 4 +- crates/ui-egui/src/panels/layers/controls.rs | 6 +- crates/ui-egui/src/panels/layers/tests.rs | 12 ++++ crates/ui-egui/src/panels/stroke.rs | 5 +- .../ui-egui/src/panels/swatches/libraries.rs | 7 ++- 25 files changed, 224 insertions(+), 45 deletions(-) create mode 100644 assets/icons/dc-arrow-left.svg create mode 100644 assets/icons/dc-arrow-right.svg diff --git a/ASSETS.md b/ASSETS.md index a483174dc1..d652019370 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -137,6 +137,8 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-arrow-down.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-extend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline | +| `assets/icons/dc-arrow-left.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-arrow-right.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-tip.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-up.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-artboard-options.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/assets/icons/dc-arrow-left.svg b/assets/icons/dc-arrow-left.svg new file mode 100644 index 0000000000..4d2ad158b6 --- /dev/null +++ b/assets/icons/dc-arrow-left.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-arrow-right.svg b/assets/icons/dc-arrow-right.svg new file mode 100644 index 0000000000..f53cc9e5ef --- /dev/null +++ b/assets/icons/dc-arrow-right.svg @@ -0,0 +1 @@ + diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 13261028e5..3bb0d3c8c8 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -528,13 +528,18 @@ fn art_rows(object: bool) -> Vec { rows } -/// The direction of the art along the stroke: a segment per direction in [`DIRECTIONS`] order. +/// The direction of the art along the stroke: an arrow segment per direction in [`DIRECTIONS`] order, +/// named by its tooltip. fn direction_row() -> Param { - // PLAN: the arrows are text until sh.S5's `APP_ICONS` names its arrow icons (with the tooltips Left to Right, Right to Left, Top to Bottom, Bottom to Top); a screen reader reads each segment as its glyph. - let arrows = ["→", "←", "↓", "↑"]; + let arrows = [ + ("dc-arrow-right", tl!("Left to Right")), + ("dc-arrow-left", tl!("Right to Left")), + ("dc-arrow-down", tl!("Top to Bottom")), + ("dc-arrow-up", tl!("Bottom to Top")), + ]; Param::custom("direction", tl!("Direction"), move |ui, f, _| { let current = DIRECTIONS.iter().position(|d| *d == parse_field::(f, "direction")).unwrap_or(0); - let entries: Vec> = arrows.iter().enumerate().map(|(i, arrow)| Entry::new(i, *arrow)).collect(); + let entries: Vec> = arrows.iter().enumerate().map(|(i, (icon, tip))| Entry::new(i, *tip).icon(IconId::new(icon))).collect(); let shown = Segmented::new(tl!("Direction"), Bind::given(current), &entries).show(ui); if let Some(dir) = shown.value().and_then(|i| DIRECTIONS.get(*i)) { f.set("direction", id_of(dir)); diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 0f2db21d46..41efe4e89e 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -278,6 +278,24 @@ fn ok_redraws_the_strokes_painted_with_the_brush() { assert!((drawn_height(&app, id) - before).abs() < 1e-6); } +/// Art Brush Options draws each Direction segment as an arrow icon named by its tooltip, so the +/// accessibility tree reads the direction instead of an arrow glyph. +#[test] +fn art_brush_direction_segments_are_named_by_their_tooltips() { + let mut app = app(); + open(&mut app, "Arrow"); + crate::dialogs::tests::settle(&mut app); + let out = crate::dialogs::tests::frame(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let labels: Vec<&str> = nodes.iter().filter_map(|(_, node)| node.label()).collect(); + for tip in ["Left to Right", "Right to Left", "Top to Bottom", "Bottom to Top"] { + assert!(labels.contains(&tip), "{tip} is not named in {labels:?}"); + } + for glyph in ["→", "←", "↓", "↑"] { + assert!(!labels.contains(&glyph), "a segment is named {glyph}"); + } +} + #[test] fn a_taken_name_keeps_the_dialog_open() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/dxf_options.rs b/crates/ui-egui/src/dialogs/dxf_options.rs index 4f8218172c..4841842a12 100644 --- a/crates/ui-egui/src/dialogs/dxf_options.rs +++ b/crates/ui-egui/src/dialogs/dxf_options.rs @@ -9,8 +9,10 @@ //! (asking where when there is no path); bad options keep the dialog open. use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::display::{Shade, Text}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::pickers::Select; +use craft::ui::style::TypeRole; use craft::ui::text::NumberField; use serde_json::{Map, Value, json}; use vectorcraft_cad::{ColorDepth, DxfPreset, DxfVersion, Preserve, RasterFormat}; @@ -144,11 +146,11 @@ pub(crate) fn scale_param(disabled_when: Option<(&str, FieldValue)>) -> Param { let (lo, hi) = (*vectorcraft_cad::SCALE_RANGE.start(), *vectorcraft_cad::SCALE_RANGE.end()); let shown = ui .horizontal(|ui| { - ui.label("1"); + Text::new("1").show(ui); Select::new(tl!("Unit"), Bind::bound(&mut unit), &units).show(ui); - ui.label("="); + Text::new("=").show(ui); NumberField::new(tl!("Scale"), Bind::bound(&mut scale)).range(lo..=hi).show(ui); - ui.label(tl!("Units")); + Text::new(tl!("Units")).show(ui); }) .response; let scale = scale.unwrap_or(1.0); @@ -199,10 +201,13 @@ pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) { .values(Bind::bound(fields)) .ok_label(tl!("Export").into()) .below(|ui, fields| { - ui.weak(match fields.text("preserve").and_then(Preserve::from_id).unwrap_or_default() { + Text::new(match fields.text("preserve").and_then(Preserve::from_id).unwrap_or_default() { Preserve::Appearance => tl!("Type becomes outlines, and strokes a CAD line can't draw become filled shapes."), Preserve::Editability => tl!("Type stays text, and every stroke is a line with its lineweight and dashes."), - }); + }) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); }) }); export_host::open(app, Export::Dxf, selection, dialog); diff --git a/crates/ui-egui/src/dialogs/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 5c8a86007d..878986389b 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -17,7 +17,9 @@ use std::sync::Arc; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Show as _, TooltipSpec}; use craft::ui::dialog::DialogId; +use craft::ui::display::{Shade, Text}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft::ui::style::TypeRole; use serde_json::{Map, Value, json}; use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset, fileio}; use vectorcraft_eps::{Level, Overprint, Preview}; @@ -136,11 +138,14 @@ pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) { builtin_label(fields); normalise_level(fields); ParamDialog::new(KIND, tl!("EPS Options"), rows(&presets)).values(Bind::bound(fields)).ok_label(tl!("Export").into()).below(|ui, fields| { - ui.weak(if fields.text("level").and_then(Level::from_id) == Some(Level::Two) || fields.bool("compatibleGradients") == Some(true) { + Text::new(if fields.text("level").and_then(Level::from_id) == Some(Level::Two) || fields.bool("compatibleGradients") == Some(true) { tl!("Transparency is flattened with the preset. Type is written as outlines; gradients as bands of colour.") } else { tl!("Transparency is flattened with the preset. Type is written as outlines; gradients stay smooth.") - }); + }) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); }) }); export_host::open(app, Export::Eps, selection, dialog); @@ -195,7 +200,10 @@ pub(super) fn custom_dialog(app: &VectorcraftApp, parent: DialogId, fields: &Dia ParamDialog::new(CUSTOM_KIND, tl!("Custom Transparency Flattener Options"), flatten::option_params(&FIXED, FIXED_REASON)) .values(Bind::bound(fields)) .below(|ui, _| { - ui.weak(tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept.")); + Text::new(tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept.")) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); }) }) } diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 3c76dea90e..6e8f8bc1d2 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -11,9 +11,11 @@ use std::sync::LazyLock; -use craft::ui::contract::Bind; +use craft::ui::contract::{Bind, Show as _}; +use craft::ui::display::{Shade, Text}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::Label; +use craft::ui::style::TypeRole; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format}; @@ -127,7 +129,7 @@ fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Res ParamDialog::new(KIND, tl!("Export As"), params()) .values(Bind::bound(fields)) .below(|ui, fields| { - ui.weak(summary(fields)); + Text::new(summary(fields)).role(TypeRole::Caption).shade(Shade::Muted).show(ui); }) .ok_label(Label::from("Export…")) }); diff --git a/crates/ui-egui/src/dialogs/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs index 3998523a57..dc95ff468d 100644 --- a/crates/ui-egui/src/dialogs/hpgl_options.rs +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -12,15 +12,16 @@ //! nothing. use craft::behavior::IconId; +use craft::theme::variant::Tone; use craft::theme::{Rgba, Srgba}; use craft::ui::buttons::{Button, IconButton}; use craft::ui::choice::{Radio, RadioGroup, Swatch}; -use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Politeness, Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::dialog::DialogId; +use craft::ui::display::Text; use craft::ui::layout_components::Stack; +use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog}; -use craft::ui::runtime::env::Env; -use craft::ui::style::rgba_color; use craft::ui::text::TextField; use serde_json::{Map, Value, json}; use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE}; @@ -177,8 +178,10 @@ fn pens_ui(ui: &mut egui::Ui, fields: &mut DialogFields, cx: &mut CustomContext) } } if let Some(e) = fields.text(PEN_ERROR) { - let error = rgba_color(Env::of(ui).tokens.tokens().color.status.bad.fg); - ui.colored_label(error, crate::i18n::message(crate::i18n::current(), e)); + Notice::new(Tone::Bad, crate::i18n::message(crate::i18n::current(), e).to_string()) + .layout(NoticeLayout::Inline) + .announce(Politeness::Assertive) + .show(ui); } // A table longer than a plot takes (set through `ui.dialog.set`) draws no rows: OK refuses it. let Some(mut pens) = list.filter(|a| a.len() <= MAX_PENS) else { return }; @@ -187,7 +190,7 @@ fn pens_ui(ui: &mut egui::Ui, fields: &mut DialogFields, cx: &mut CustomContext) Stack::new().scroll(Scroll::vertical()).room_height(180.0).show(ui, |ui, _| { for (i, pen) in pens.iter_mut().enumerate() { ui.horizontal(|ui| { - ui.label((i + 1).to_string()); + Text::new((i + 1).to_string()).show(ui); let mut color = pen.as_str().and_then(Rgba::from_hex).unwrap_or(Rgba::rgb(0, 0, 0)); if Swatch::new(tl!("Pen color"), Srgba::from(color)).show(ui).clicked { cx.pick_color(&pen_key(i), Srgba::from(color)); diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs index c2c334f148..1aac4c28b8 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets.rs @@ -15,12 +15,14 @@ //! Behavior reference: the help page //! . +use craft::theme::variant::Tone; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Politeness, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::display::Text; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::{Row, Stack}; +use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::presets::{ NameCheck, NamedPresetEvent, NamedPresetRow, PickerField, PresetError, PresetPicker, PresetRow, PresetSource, PresetState, }; @@ -408,9 +410,8 @@ impl KinsokuDialog { } fn show_problem(&self, ui: &mut Ui) { - // PLAN: craft_ui does not re-export `Tone`, which `Notice` needs, so the reason shows as plain text. if let Some(problem) = &self.problem { - Text::new(problem.clone()).show(ui); + Notice::new(Tone::Bad, problem.clone()).layout(NoticeLayout::Inline).announce(Politeness::Assertive).show(ui); } } } diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index a17ddcb027..72fb260ee2 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -7,6 +7,7 @@ // runtime; the form-dialog items live under `patterns::form_dialogs`; `Field` and `NumberField` under craft-ui-widgets). use craft::ui::contract::{Bind, FieldLabelRole, Show as _, ShowContainer as _, SideLabel}; use craft::ui::dialog::DialogId; +use craft::ui::display::Text; use craft::ui::form::Field; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; @@ -286,7 +287,7 @@ fn counts_row(ui: &mut egui::Ui, f: &DialogFields) { if let Some(FieldValue::Json(c)) = f.get(COUNTS) && let (Some(before), Some(after)) = (c["before"].as_u64(), c["after"].as_u64()) { - ui.label(format!("{} {before} → {after}", crate::i18n::colon(tl!("Anchor Points")))); + Text::new(format!("{} {before} → {after}", crate::i18n::colon(tl!("Anchor Points")))).show(ui); } } diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 00151a7f2c..6aad94b0c1 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -244,7 +244,7 @@ fn resolution_row() -> Param { fn size_row(w: f64, h: f64) -> Param { Param::custom("__sizeText", tl!("Size:"), move |ui, fields, _| { let (pw, ph) = vectorcraft_render::region_pixels(vectorcraft_geom::Rect::new(0.0, 0.0, w, h), fields.number("ppi").unwrap_or(72.0) / 72.0); - ui.label(format!("{pw} × {ph} px")) + Text::new(format!("{pw} × {ph} px")).show(ui) }) } diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index e988d10099..ce0acf1dbf 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -33,7 +33,7 @@ use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook}; use craft::ui::primitives::IconSpec; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use craft::ui::shell::WindowDialogs; -use craft::ui::text::{LinkMode, LinkedFields, NumberField}; +use craft::ui::text::{LinkMode, LinkedFields, NumberField, SelectableText}; use serde_json::{Map, Value, json}; use vectorcraft_color::cms::Intent; use vectorcraft_engine::cmd::printpresets::DEFAULT_PRESET; @@ -633,9 +633,9 @@ fn scaling_ids(tiles: bool) -> Vec<&'static str> { PrintScaling::ALL.iter().filter(|s| s.tiles() == tiles).map(|s| s.id()).collect() } -/// A summary line that the pump fills (`key` is a `__` companion of the fields). -fn shown(key: &'static str) -> Param { - Param::custom(key, "", move |ui, fields, _| ui.label(fields.text(key).unwrap_or_default())) +/// A summary line that the pump fills (`key` is a `__` companion of the fields), selectable and named `label`. +fn shown(key: &'static str, label: &'static str) -> Param { + Param::custom(key, "", move |ui, fields, _| SelectableText::new(label, fields.text(key).unwrap_or_default()).multiline().show(ui)) } /// The sections of the dialog, with the rows of each. @@ -791,11 +791,11 @@ fn sections(lists: &Lists) -> Vec { ]; let summary = vec![ Param::section(tl!("Pages")), - shown("__summary.pages"), + shown("__summary.pages", tl!("Pages")), Param::section(tl!("Options")), - shown("__summary.options"), + shown("__summary.options", tl!("Options")), Param::section(tl!("Warnings")), - shown("__summary.warnings"), + shown("__summary.warnings", tl!("Warnings")), ]; [general, marks, output, graphics, color, advanced, summary] .into_iter() diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index 921dd8d37f..8dbbab34f8 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -36,6 +36,7 @@ use vectorcraft_eps::{Level, Overprint, Preview}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, CollectionEvent, Show as _, ShowCollection as _, TooltipSpec}; +use craft::ui::display::Text; use craft::ui::list::{ThumbAspect, ToggleState}; use craft::ui::notices::Notice; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; @@ -401,7 +402,7 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> let files = board_files(menus.doc.as_deref(), fields.text("path").unwrap_or_default(), &boards); let response = ui .vertical(|ui| { - ui.label(tl!("A legacy .ai file holds one artboard: each artboard you check is saved as a separate file.")); + Notice::new(Tone::Info, tl!("A legacy .ai file holds one artboard: each artboard you check is saved as a separate file.")).show(ui); ui.horizontal(|ui| { if Button::new(tl!("Select All")).show(ui).clicks > 0 { boards.iter_mut().for_each(|b| *b = true); @@ -411,7 +412,7 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> } let checked = boards.iter().filter(|b| **b).count(); let (count, total) = (checked.to_string(), n.to_string()); - ui.label(crate::i18n::fmt(tl!("{count} of {total} artboards"), &[("count", &count), ("total", &total)])); + Text::new(crate::i18n::fmt(tl!("{count} of {total} artboards"), &[("count", &count), ("total", &total)])).show(ui); }); if !boards.iter().any(|b| *b) { Notice::new(Tone::Warn, tl!("Check an artboard to save.")).show(ui); diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index a0e5dbbd56..8227766b4a 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -247,6 +247,29 @@ fn legacy_ai_saves_the_artboards_checked_in_its_picker() { assert_eq!(boards_in(&dialog(&mut app)), Some(vec![true, false, true, false])); } +/// The legacy picker's note and its count of checked artboards are in the window's accessibility tree, and the count +/// follows the checks. +#[test] +fn legacy_ai_names_its_note_and_artboard_count_in_the_accessibility_tree() { + let (mut app, _, _) = desktop("art.ai"); + app.run("artboard.new", json!({"x": 200, "y": 0, "width": 100, "height": 80})).unwrap(); + save_as(&mut app, "file.saveAs"); + set(&mut app, "aiVersion", json!("7")); + let labels = |app: &mut VectorcraftApp| -> Vec { + frame(app); + let ctx = app.ui_ctx.clone().unwrap(); + let out = crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| app.ui(ui)); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, node)| node.label()).map(str::to_owned).collect() + }; + let shown = labels(&mut app); + assert!(shown.iter().any(|l| l.starts_with("A legacy .ai file holds one artboard")), "{shown:?}"); + assert!(shown.iter().any(|l| l == "2 of 2 artboards"), "{shown:?}"); + set(&mut app, "boards", json!([true, false])); + let shown = labels(&mut app); + assert!(shown.iter().any(|l| l == "1 of 2 artboards") && !shown.iter().any(|l| l == "2 of 2 artboards"), "{shown:?}"); +} + #[test] fn save_a_copy_and_template_suggest_their_names() { let (mut app, written, picks) = desktop("copy.vectorcraft"); diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index e81e7a81e4..016cf865aa 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -206,6 +206,67 @@ fn export_as_png_picks_the_file_then_shows_png_options() { assert_eq!(&written.borrow()[0].1[16..20], 120u32.to_be_bytes(), "60 pt at 144 ppi"); } +/// PNG Options' pixel size is in the window's accessibility tree, and it follows the resolution. +#[test] +fn png_options_name_the_pixel_size_in_the_accessibility_tree() { + let (mut app, _) = app(1); + app.run("file.export.png", json!({})).unwrap(); + answer_saves(&mut app); + let sizes = |app: &mut VectorcraftApp| -> Vec { + super::tests::settle(app); + let out = super::tests::frame(app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, node)| node.label()).filter(|label| label.ends_with(" px")).map(str::to_owned).collect() + }; + let at_72 = sizes(&mut app); + assert_eq!(at_72, ["60 × 40 px"]); + set(&mut app, "ppi", json!(144)); + assert_eq!(sizes(&mut app), ["120 × 80 px"]); +} + +/// The role and name of each node of the window's accessibility tree, in a frame drawn once the dialogs have settled. +fn access_names(app: &mut VectorcraftApp) -> Vec<(egui::accesskit::Role, String)> { + super::tests::settle(app); + let out = super::tests::frame(app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, node)| node.label().map(|label| (node.role(), label.to_owned()))).collect() +} + +/// The hints under Export As, DXF Options and EPS Options, the words of the DXF scale row and the HP-GL pen numbers +/// are in the window's accessibility tree, and the HP-GL pen error is announced as an alert. +#[test] +fn export_dialogs_name_their_hints_rows_and_errors_in_the_accessibility_tree() { + let names = |app: &mut VectorcraftApp| -> Vec { access_names(app).into_iter().map(|(_, name)| name).collect() }; + let (mut app, _) = app(1); + app.run("file.exportAs", json!({"format": "png", "useArtboards": false})).unwrap(); + let shown = names(&mut app); + assert!(shown.iter().any(|n| n == "The bounds of the visible art."), "{shown:?}"); + cancel(&mut app); + + crate::menus::invoke(&mut app, "ui.dxfOptionsDialog", json!({})); + let shown = names(&mut app); + for word in ["=", "Units"] { + assert!(shown.iter().any(|n| n == word), "{word} is not named in {shown:?}"); + } + assert!(shown.iter().any(|n| n.starts_with("Type becomes outlines")), "{shown:?}"); + cancel(&mut app); + + crate::menus::invoke(&mut app, "ui.epsOptionsDialog", json!({})); + let shown = names(&mut app); + assert!(shown.iter().any(|n| n.starts_with("Transparency is flattened with the preset.")), "{shown:?}"); + cancel(&mut app); + + app.run("ui.hpglOptionsDialog", json!({})).unwrap(); + set(&mut app, "pens", json!(["#ff0000", "#000000"])); + set(&mut app, "__penError", json!("The pens could not be listed.")); + let shown = access_names(&mut app); + assert!(shown.iter().any(|(_, n)| n == "2"), "the second pen's number is not named in {shown:?}"); + assert!( + shown.iter().any(|(role, n)| *role == egui::accesskit::Role::Alert && n.contains("The pens could not be listed.")), + "the pen error is not an alert in {shown:?}" + ); +} + /// File › Export › Export As PNG… exports the artboard in use, not the first (#5502), and each /// artboard the Artboard tool has selected, one file each. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index f558c6690f..e551e71627 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -115,6 +115,18 @@ fn simplify_opens_a_slider_whose_drag_previews_fewer_or_more_points() { assert_eq!(anchor_count(&app), 2); } +/// The Simplify dialog's count of anchor points before and after is in the window's accessibility tree. +#[test] +fn the_simplify_dialog_names_its_anchor_point_counts() { + let mut app = app_with_dense_path(); + open_simplify_dialog(&mut app); + settle(&mut app); + let out = frame(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let names: Vec<&str> = nodes.iter().filter_map(|(_, node)| node.label()).collect(); + assert!(names.iter().any(|n| n.starts_with("Anchor Points:") && n.contains('→')), "{names:?}"); +} + /// A wave of 20 anchors `width` pt wide and `width / 5` pt high, selected. fn app_with_wave(width: f64) -> VectorcraftApp { let mut app = window(VectorcraftApp::new(Session::new(), Default::default())); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 67d45de47e..957f07cd0a 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -346,6 +346,23 @@ fn the_control_channel_fills_and_confirms_the_dialog() { assert_eq!(jobs.borrow().len(), 1); } +/// The Summary section's Pages, Options and Warnings are each named in the window's accessibility tree, with their +/// summary text as the value. +#[test] +fn the_summary_names_its_pages_options_and_warnings() { + let (mut app, _) = app(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "section", json!("Summary")); + pump(&mut app); + let ctx = ctx(&app); + let out = crate::testing::app_frame(&mut app, &ctx, Default::default()); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + for name in ["Pages", "Options", "Warnings"] { + assert!(nodes.iter().any(|(_, n)| n.label() == Some(name) && n.value().is_some_and(|v| !v.is_empty())), "{name} has no summary"); + } +} + /// Scale W and H of the open dialog, and its link. fn scale(app: &VectorcraftApp) -> (f64, f64, bool) { let f = fields(app); diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 390c536503..0c816e8052 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -13,7 +13,7 @@ use craft::ui::canvas::Canvas; use craft::ui::canvas::{CanvasSpace, canvas_space}; use craft::ui::canvas_controls::SelectionOutline; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; -use craft::ui::display::Picture; +use craft::ui::display::{Picture, Text}; use craft::ui::list::ThumbAspect; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind}; use craft::ui::pickers::Select; @@ -311,7 +311,7 @@ fn navigator(count: usize, seen: Vec) -> Param { } } if !seen.get(current - 1).copied().unwrap_or(true) { - ui.label(tl!("Hidden")); + Text::new(tl!("Hidden")).show(ui); } }); let shown = next.map_or(current, |n| n.clamp(1, count)); diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index bf76005b9e..017a6988b0 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -48,6 +48,8 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-arc-three-point", include_bytes!("../../../assets/icons/dc-arc-three-point.svg")), ("dc-arrow-down", include_bytes!("../../../assets/icons/dc-arrow-down.svg")), ("dc-arrow-extend", include_bytes!("../../../assets/icons/dc-arrow-extend.svg")), + ("dc-arrow-left", include_bytes!("../../../assets/icons/dc-arrow-left.svg")), + ("dc-arrow-right", include_bytes!("../../../assets/icons/dc-arrow-right.svg")), ("dc-arrow-tip", include_bytes!("../../../assets/icons/dc-arrow-tip.svg")), ("dc-arrow-up", include_bytes!("../../../assets/icons/dc-arrow-up.svg")), ("dc-artboard-options", include_bytes!("../../../assets/icons/dc-artboard-options.svg")), diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 0ffa35a7b4..5fc566a040 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -20,7 +20,7 @@ use craft::behavior::{EditEvent, GesturePhase, IconId, Selection}; use craft::ui::contract::{ Bind, DropAt, DropPayload, DropPlace, Entry, ListDrag, MemoProps, PopupKind, ReorderMove, SelectMode, Show as _, ShowContainer as _, Trigger, }; -use craft::ui::display::Divider; +use craft::ui::display::{Divider, Text}; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::patterns::presets::{ PickerField, PresetBrowser, PresetDrop, PresetEvent, PresetFns, PresetPicker, PresetReorder, PresetRow, PresetSource, PresetState, PresetView, @@ -393,7 +393,7 @@ fn large_tip(app: &VectorcraftApp, thumbs: &StyleThumbs, ui: &mut Ui, key: &Styl Some(tex) => ui.painter().image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE), None => ui.painter().rect_filled(r, 0.0, Color32::WHITE), }; - ui.label(key); + Text::new(key.clone()).show(ui); } // ---------- the panel ---------- diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index 30cbc520aa..4200073a7b 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -2,11 +2,13 @@ use craft::behavior::IconId; use craft::keymap::Mods; use craft::layers::ui::panel::MenuTarget; // PLAN: assumed path of craft-layers' panel types use craft::layers::ui::tree::LayerRowKey; -use craft::ui::contract::{Entry, ListDrag}; +use craft::ui::contract::{Entry, ListDrag, Show as _}; +use craft::ui::display::{Shade, Text}; use craft::ui::menu::{MenuRow, PanelRow}; use craft::ui::primitives::IconSpec; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; use craft::ui::sections::{FooterAction, FooterBar}; +use craft::ui::style::TypeRole; // PLAN: assumed document-panels-w7's `model` exports `DocLayers` (accessors used here: `doc() -> &Arc`, // `state() -> &DocState`, `root() -> Option`, `layers_only() -> bool`, `guides() -> &[usize]`, @@ -451,7 +453,7 @@ pub(crate) fn footer(tree: &DocLayers, ui: &mut Ui, out: &mut Vec<(String, Value ]; let count = crate::i18n::tn(tree.doc().layers.len() as u64, "{n} Layer", "{n} Layers").to_string(); let (output, _) = FooterBar::actions(actions).at_start(0).show_footer_leading(ui, |ui, _| { - ui.weak(&count); + Text::new(count.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); }); // The footer runs twice per pass: the sizing pass measures it and must report nothing. if ui.is_sizing_pass() { diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 2ac1b0af3f..b4e1aa278a 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -483,6 +483,18 @@ fn context_menu_others_actions_sublayer_state_enables_all_commands() { assert!(lock_enabled, "locked sublayer enables Unlock All Layers"); } +/// The footer's layer count is in the accessibility tree, and it follows the document's layers. +#[test] +fn the_footer_counts_the_layers() { + use crate::tests::panel_harness::Panel; + let (app, _, _) = two_rects(); + let mut panel = Panel::new(app, show); + assert!(panel.shows("1 Layer")); + panel.app().session.execute("layer.new", &json!({})).unwrap(); + panel.frame(); + assert!(panel.shows("2 Layers") && !panel.shows("1 Layer")); +} + /// Names object `id` `name`, so its target circle is "Target {name}". fn name_row(app: &mut VectorcraftApp, id: NodeId, name: &str) { app.session.execute("layer.setProps", &json!({"ids": [id.0], "name": name})).unwrap(); diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index c339c73b6e..7a2be889bb 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -11,6 +11,7 @@ use craft::keymap::CommandRef; use craft::ui::buttons::IconButton; use craft::ui::choice::Segmented; use craft::ui::contract::{Bind, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel, TooltipSpec}; +use craft::ui::display::Divider; use craft::ui::form::Field; use craft::ui::menu::PanelRow; use craft::ui::pickers::Select; @@ -386,9 +387,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if let (Some(new), Some(field)) = (output.events.landed(), output.field) { apply_style(app, &style, new.clone(), field); } - ui.separator(); + Divider::horizontal().show(ui); arrow_rows(app, ui, st.as_ref()); - ui.separator(); + Divider::horizontal().show(ui); Field::new(tl!("Profile")).show(ui, |ui, _| { ui.horizontal(|ui| { profile_select(app, ui); diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index 62e926dd55..e255b6757d 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -2,7 +2,8 @@ use std::borrow::Cow; use std::collections::HashMap; use std::sync::Arc; -use craft::ui::contract::{Entry, MemoKey, MemoProps}; +use craft::ui::contract::{Entry, MemoKey, MemoProps, Show as _}; +use craft::ui::display::Divider; use craft::ui::patterns::presets::PresetRow; use craft::ui::primitives::ContentPainterCx; use egui::{Rect, Ui}; @@ -163,10 +164,10 @@ impl LibraryKind for SwatchLibraries { if item(ui, tl!("Default Swatches"), app.session.active().is_some(), None) { app.run("swatch.resetDefaults", json!({})).ok(); } - ui.separator(); + Divider::horizontal().show(ui); } fn menu_tail(app: &mut VectorcraftApp, ui: &mut Ui) { - ui.separator(); + Divider::horizontal().show(ui); // As a command, so its file dialog, shown off the UI thread, loads the library when it // answers. if item(ui, tl!("Other Library…"), true, None) From b4cccf2d956f1e17a96acdb86b1a8a155c10e641 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:22:19 -0800 Subject: [PATCH 072/101] Tests: Direction segments are checked by their radio button role The Art Brush Options test now reads labels only from the radio button nodes that Segmented gives its segments, so a tooltip label on another node no longer passes it. --- crates/ui-egui/src/dialogs/brush_options/tests.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 41efe4e89e..34e11865cf 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -287,12 +287,14 @@ fn art_brush_direction_segments_are_named_by_their_tooltips() { crate::dialogs::tests::settle(&mut app); let out = crate::dialogs::tests::frame(&mut app, vec![]); let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); - let labels: Vec<&str> = nodes.iter().filter_map(|(_, node)| node.label()).collect(); + // Segmented gives each segment the radio button role. + let segments: Vec<&str> = + nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::RadioButton).filter_map(|(_, node)| node.label()).collect(); for tip in ["Left to Right", "Right to Left", "Top to Bottom", "Bottom to Top"] { - assert!(labels.contains(&tip), "{tip} is not named in {labels:?}"); + assert!(segments.contains(&tip), "no segment is named {tip} in {segments:?}"); } for glyph in ["→", "←", "↓", "↑"] { - assert!(!labels.contains(&glyph), "a segment is named {glyph}"); + assert!(!segments.contains(&glyph), "a segment is named {glyph}"); } } From cecaf16baea2ecb17285b7825c7544c2ae8e00cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 20:39:34 -0800 Subject: [PATCH 073/101] Circle: switching Third Point by Dragging keeps a center placed with From Center --- crates/tools/src/circle.rs | 3 ++- crates/tools/src/circle/tests.rs | 18 ++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 738141a993..37c0e33bcd 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -640,7 +640,8 @@ impl Tool for CircleTool { if let Some(switch) = self.options.switch(key) { *switch = on; } - if self.options.drag_third != was { + // A circle drawn from its center has no third point, so its center stays placed. + if self.options.drag_third != was && !self.centered { self.clear(); } } diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index 20cf56977b..3264a771e8 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -857,6 +857,24 @@ fn from_center_holds_for_the_circle_being_drawn() { assert_eq!(t.options()["fromCenter"], json!(false), "a value that is not true or false is ignored"); } +/// Switching `dragThird` while a center is placed keeps the center: the circle from it is still +/// drawn. Without From Center, the switch drops the point placed. +#[test] +fn switching_third_point_by_dragging_keeps_a_placed_center() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("dragThird", &json!(false)); + assert!(t.ends_on_escape(&cx), "the center is still placed"); + assert_eq!(click(&mut t, &cx, (100.0, 150.0)), centered((100.0, 100.0), (100.0, 150.0))); + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("dragThird", &json!(false)); + assert!(!t.ends_on_escape(&cx), "the first point is dropped"); +} + /// `tool.setOption` takes `fromCenter` as true or false, and no other key. #[test] fn the_options_are_checked() { diff --git a/docs/mcp.md b/docs/mcp.md index da42323ebe..78e18df020 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7396,7 +7396,7 @@ default except `fromCenter`, which is off, and `color` is `"blue"`: the opposite corner, with the diagonal as its radius. Shift keeps the second point at 45° steps from the center, and Alt rounds the diameter (twice the distance from the center) to the nearest ruler tick. The tool shows one radius, to the pointer. A second click on the center places nothing. The setting in force when the first point is placed applies - to that circle, and `dragThird` does not apply to it. + to that circle, and `dragThird` does not apply to it: switching `dragThird` keeps a placed center. `tool.setOption` returns an error and changes none of the options when a value is not one the option takes (`` `radii` must be true or false ``, `` `color` must be one of red, blue, magenta, green, black, gray ``) or the key is From a1886f6957a5735471034add3a7470442fa82f88 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:32:35 -0800 Subject: [PATCH 074/101] 3D: the light list is a framework Stack, and the light sphere measures as tall as it shows The light sphere's height follows its width, but it measured with the width of a band picture, which is its least width when a column measures it with no room. In a Stack the measuring run then found the light list shorter than it showed (by 64 pt in the 3D panel test), and "Light behind the object", the last row, lay outside the Stack and took no clicks. The sphere now measures with MeasureCx::picture_size, so the column measures it again at the width it shows at. The light list moves from ui.vertical into form::stacked: each run edits a copy of the values, and the copy from the run that is not a measuring run replaces them. --- crates/ui-egui/src/dialogs/revolve.rs | 3 +-- crates/ui-egui/src/dialogs/revolve_lights.rs | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index a61190970e..a20c8c720b 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -721,7 +721,7 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { fields.remove("__lightPick"); set_light_value(fields, "lightColor", json!(hex)); } - ui.vertical(|ui| { + super::form::stacked(ui, fields, |ui, fields| { let mut list = explicit_lights(fields).unwrap_or_else(|| vec![light_record(fields)]); let mut index = light_index(fields, list.len()); let titles: Vec = (1..=list.len()).map(|i| format!("{} {i}", c3("Light"))).collect(); @@ -767,7 +767,6 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { store_selected(fields, &selected); } }) - .response }) .companions(LIGHT_KEYS.iter().map(|(_, k)| *k).chain(["__light", "__lightPick"])) .on_set(set_light_field) diff --git a/crates/ui-egui/src/dialogs/revolve_lights.rs b/crates/ui-egui/src/dialogs/revolve_lights.rs index 992ccf44ae..342f032808 100644 --- a/crates/ui-egui/src/dialogs/revolve_lights.rs +++ b/crates/ui-egui/src/dialogs/revolve_lights.rs @@ -272,8 +272,8 @@ impl Component for LightSphere<'_> { /// The row's width and the height of the sphere that fits it, with its suns. fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { - let width = cx.picture_width((24.0 + SUN + 8.0) * 2.0, f32::INFINITY); - Vec2::new(width, (radius_in(width) + SUN + 6.0) * 2.0) + // The height follows the width: a column that measures the sphere with no room measures it again at its width. + cx.picture_size((24.0 + SUN + 8.0) * 2.0, f32::INFINITY, |width| (radius_in(width) + SUN + 6.0) * 2.0) } fn sense(&self) -> Sense { From 1693a4f71bfbb08ea0a95e5975d704df9c23d73f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:14:03 -0800 Subject: [PATCH 075/101] Transparency: the mask row renders its thumbnails at the size.thumb.lg token in place of a fixed 48 pt The object and mask thumbnails sit in a large thumbnail row, whose cells take their side from size.thumb.lg, but the pictures were requested at a fixed 48 points. Every built-in size set gives 48 today, so the two only part when the app's sizes change size.thumb.lg; the pictures were then rendered smaller or larger than the cells that show them. The request now reads the token, and a test checks that the picture covers its cell at both densities and with the token changed. --- crates/ui-egui/src/panels/transparency.rs | 53 ++++++++++++++++++++--- 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index 1fafa33563..3f6e38014b 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -24,7 +24,7 @@ use craft::ui::primitives::{ }; use craft::ui::primitives::{Revision, ThumbPaint}; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; -use craft::ui::runtime::env::UnitKind; +use craft::ui::runtime::env::{Env, UnitKind}; use craft::ui::style::DataColor; use craft::ui::text::NumberField; use egui::{Color32, Ui}; @@ -37,10 +37,6 @@ use crate::VectorcraftApp; use crate::edits::{EditPath, apply_edits}; use crate::fields::blend_entries; -/// The side of the mask row's thumbnails, in points. -// PLAN: should come from the `size.thumb.lg` token; the row's `ThumbSize::Large` gives the rect, this only sizes the render. -const THUMB_POINTS: f32 = 48.0; - /// The command ids of the menu's own rows. const THUMBNAILS: &str = "ui.transparency.thumbnails"; const OPTIONS: &str = "ui.transparency.options"; @@ -156,6 +152,12 @@ fn mask_click(m: &OpacityMask, id: NodeId, mods: craft::keymap::Mods, editing: b } } +/// The render request of the mask row's thumbnails: the side `ThumbSize::Large` gives the row's cells +/// (`size.thumb.lg`), in pixels of the screen `ui` shows on. +fn mask_thumb_request(ui: &Ui) -> ThumbRequest { + ThumbRequest::for_cell(Env::of(ui).tokens.size.thumb.lg, ui.ctx().pixels_per_point()) +} + /// The one-row list of the object's and the mask's thumbnails with the mask's link; the events it reported. fn mask_row( app: &VectorcraftApp, @@ -168,7 +170,7 @@ fn mask_row( let Some(st) = app.session.active() else { return vec![] }; let source = MaskThumbs { doc: &st.doc, revision: st.revision }; let store = Thumbnails::::in_context(ui.ctx(), "vc-mask-thumbs", ThumbnailOptions::new()); - let request = ThumbRequest::for_cell(THUMB_POINTS, ui.ctx().pixels_per_point()); + let request = mask_thumb_request(ui); let state_of = |ui: &Ui, node: NodeId, bg, own_mask| { store.state(ui.ctx(), &source, &MaskKey { uid: st.uid, node, bg, own_mask }, &request, Priority::VISIBLE) }; @@ -572,6 +574,45 @@ mod tests { assert_eq!(page(&app), [true, true]); } + /// The mask row's pictures are rendered at the size of the cells a large thumbnail row draws them in, at + /// either density and when the app's sizes change `size.thumb.lg`: at least as many pixels as the cell + /// covers, and less than one request step (16 pixels) more. + #[test] + fn mask_thumbnails_render_at_the_size_of_their_cells() { + use craft::theme::{AppSizes, Size}; + use craft::ui::runtime::env::RootEnv; + use craft::ui::testing::Fixture; + use std::cell::Cell; + use std::rc::Rc; + let ppp = 2.0; + let changed = AppSizes::parse(br#"{"all": {"size.thumb.lg": 72}}"#).expect("a size override"); + for density in [Size::Compact, Size::Comfortable] { + for sizes in [crate::theme::app_sizes(), Arc::new(changed.clone())] { + let (cell, side) = (Rc::new(Cell::new(None)), Rc::new(Cell::new(None))); + let (cell_seen, side_seen) = (Rc::clone(&cell), Rc::clone(&side)); + let mut fixture = Fixture::new(move |ui| { + side_seen.set(Some(mask_thumb_request(ui).side)); + let cell_seen = Rc::clone(&cell_seen); + let keys = [()]; + List::<()>::new("Thumbnails").select(SelectMode::None).natural_height(true).show_items(ui, &keyed(&keys, |_| ()), &mut |_, _| { + let cell_seen = Rc::clone(&cell_seen); + ListRow::new("Row").thumbnails_only().thumb(ThumbSize::Large, move |_: &ContentPainterCx, rect: egui::Rect| { + cell_seen.set(Some(rect)); + }) + }); + }); + let mut root = RootEnv::new().density(density); + root.sizes = sizes; + fixture.root(root).pixels_per_point(ppp); + fixture.frame(vec![]); + fixture.frame(vec![]); + let cell = cell.get().expect("the row draws its thumbnail"); + let (side, covered) = (side.get().expect("the request") as f32, cell.width().max(cell.height()) * ppp); + assert!(side >= covered && side < covered + 16.0, "{density:?}: a {side} px picture for a {covered} px cell"); + } + } + } + /// The panel's state holds the target as the document holds it, a new one after an edit and /// after Undo; the object thumbnail of a masked object draws as the object without its mask. #[test] From 6ac3f3a6c48e2ac8a2d7af2eb0cebe578c005242 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:25:12 -0800 Subject: [PATCH 076/101] Layers: a horizontal and a vertical ruler guide's rows show a glyph of their own, a line across or down from a ruler, as production's rows drew a line across or down --- ASSETS.md | 2 ++ assets/icons/dc-guide-horizontal.svg | 1 + assets/icons/dc-guide-vertical.svg | 1 + crates/ui-egui/src/icon_data.rs | 2 ++ crates/ui-egui/src/panels/layers/model.rs | 9 ++++++++- crates/ui-egui/src/panels/layers/tests.rs | 24 +++++++++++++++++++++++ 6 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 assets/icons/dc-guide-horizontal.svg create mode 100644 assets/icons/dc-guide-vertical.svg diff --git a/ASSETS.md b/ASSETS.md index a21d7a9692..95d1048c61 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -207,6 +207,8 @@ Generated-in-code art is original and has no file to list. This covers the defau | `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 | | +| `assets/icons/dc-guide-horizontal.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a ruler down the left with a line across) | MIT OR Apache-2.0 | | +| `assets/icons/dc-guide-vertical.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a ruler along the top with a line down) | MIT OR Apache-2.0 | | | `assets/icons/dc-help.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a question mark in a circle) | MIT OR Apache-2.0 | | | `assets/icons/dc-join-bevel.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-join-miter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/assets/icons/dc-guide-horizontal.svg b/assets/icons/dc-guide-horizontal.svg new file mode 100644 index 0000000000..941eba1f1d --- /dev/null +++ b/assets/icons/dc-guide-horizontal.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-guide-vertical.svg b/assets/icons/dc-guide-vertical.svg new file mode 100644 index 0000000000..3383fd4c22 --- /dev/null +++ b/assets/icons/dc-guide-vertical.svg @@ -0,0 +1 @@ + diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 8c8962dd50..8d9929e481 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -119,6 +119,8 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("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")), + ("dc-guide-horizontal", include_bytes!("../../../assets/icons/dc-guide-horizontal.svg")), + ("dc-guide-vertical", include_bytes!("../../../assets/icons/dc-guide-vertical.svg")), ("dc-help", include_bytes!("../../../assets/icons/dc-help.svg")), ("dc-join", include_bytes!("../../../assets/icons/dc-join.svg")), ("dc-join-bevel", include_bytes!("../../../assets/icons/dc-join-bevel.svg")), diff --git a/crates/ui-egui/src/panels/layers/model.rs b/crates/ui-egui/src/panels/layers/model.rs index 46d24e0806..7ec3597938 100644 --- a/crates/ui-egui/src/panels/layers/model.rs +++ b/crates/ui-egui/src/panels/layers/model.rs @@ -4,6 +4,7 @@ use std::collections::{HashMap, HashSet}; use std::hash::{Hash as _, Hasher as _}; use std::ops::Deref; +use craft::behavior::IconId; use craft::keymap::Mods; pub(super) use craft::layers::ui::filter::{FilterObject, FilterState}; use craft::layers::ui::filter::{LayerFilter, SmartSource}; @@ -36,6 +37,12 @@ pub(crate) fn shown_name(app: &VectorcraftApp, n: &Node, lang: crate::i18n::Lang listed_name(n, by_xml_id(app), lang) } +/// The glyph of a horizontal ruler guide's row: a line across from a ruler. +const HORIZONTAL_GUIDE_ICON: &str = "dc-guide-horizontal"; + +/// The glyph of a vertical ruler guide's row: a line down from a ruler. +const VERTICAL_GUIDE_ICON: &str = "dc-guide-vertical"; + /// Whether Identify Objects By is XML ID. fn by_xml_id(app: &VectorcraftApp) -> bool { app.session.prefs.identify_objects_by == "xmlId" @@ -411,7 +418,7 @@ impl LayerRows { info.dimmed = !self.shown(layer) || !info.visible; info.color = Some(self.color(layer)); } - // PLAN: dp.L12's horizontal and vertical guide marks need app icons the icon set lacks; the row keeps the kind's ruler glyph. + info.icon = Some(IconId::new(if vertical { VERTICAL_GUIDE_ICON } else { HORIZONTAL_GUIDE_ICON })); info.renamable = false; info.thumbnail = false; info diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 2ac1b0af3f..1cd5128585 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -343,6 +343,30 @@ fn rows_list_by_depth_and_ruler_guide_nodes_get_no_object_row() { assert_eq!(ids, [second, first, rect]); } +/// A horizontal and a vertical ruler guide's rows each show a glyph of their own, in place of the +/// guide kind's ruler, and both glyphs are in the app's icon set. +#[test] +fn horizontal_and_vertical_guide_rows_show_their_own_drawn_glyphs() { + use craft::ui::primitives::{has_icon, register_app_icons}; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("guide.add", &json!({"vertical": false, "pos": 40})).unwrap(); + app.session.execute("guide.add", &json!({"vertical": true, "pos": 60})).unwrap(); + let st = app.session.active().unwrap(); + let rows = LayerRows::new(&app, st); + let icon_of = |vertical: bool| { + let i = st.doc.ruler_guides().iter().position(|g| g.vertical == vertical).unwrap(); + rows.info(&RowId::Guide(i)).icon.unwrap_or_else(|| panic!("the vertical: {vertical} guide row has no glyph of its own")) + }; + let (across, down) = (icon_of(false), icon_of(true)); + assert_ne!(across, down, "the two kinds of guide rows look alike"); + register_app_icons(&crate::icons::APP_ICONS); + for icon in [&across, &down] { + assert!(has_icon(icon), "{icon:?} is in no icon set, so the row draws nothing"); + } +} + /// The undo steps of the active document. pub(super) fn undo_len(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() From c2dc2e8999590beb74561086480396bb09508e34 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 04:47:35 -0800 Subject: [PATCH 077/101] Save for Web: the dialog keeps the remembered Transparency Dither The dialog has no Transparency Dither rows, so its previews, Save, Optimize to File Size and saved presets carry the remembered transparencyDither and transparencyDitherAmount instead of resetting them to none. A preset picked in the dialog does not change them. --- crates/ui-egui/src/dialogs/save_for_web.rs | 45 +++++++++++++------ .../ui-egui/src/dialogs/save_for_web/tests.rs | 25 +++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 58 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index aaaf3d4e1c..0dd9edc19b 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -49,6 +49,19 @@ pub(crate) struct WebExport { optimized: Option, /// The engine's `colorTable` value: the edits the colour table's buttons made. table: Value, + /// The engine's settings the dialog has no option for ([`KEPT`]), as the dialog opened on them + /// or Optimize to File Size found them: the previews, Save… and the presets use them. A preset + /// picked in the dialog does not change them. + kept: Value, +} + +/// The engine's settings keys the dialog does not show; they pass through it unchanged. +const KEPT: [&str; 2] = ["transparencyDither", "transparencyDitherAmount"]; + +/// The [`KEPT`] keys of the engine's settings `s`. +fn kept_of(s: &WebSettings) -> Value { + let engine = s.to_json(); + Value::Object(KEPT.iter().filter_map(|k| engine.get(*k).map(|v| ((*k).to_string(), v.clone()))).collect()) } /// The key of the Original pane's texture in the pump's [`TextureStore`]; the panes use their index. @@ -129,11 +142,15 @@ pub(super) fn options_of(s: &WebSettings, natural: Option) -> SaveFor serde_json::from_value(v).unwrap_or_default() } -/// The engine's settings JSON for the dialog's `options`, the edited colour `table` and an optional -/// `path`: what `webExport.settings`, `document.exportForWeb` and `file.saveForWeb` read. -fn settings_of(options: &SaveForWebOptions, table: &Value, path: Option<&str>) -> Value { +/// The engine's settings JSON for the dialog's `options`, the edited colour `table`, the `kept` +/// settings the dialog does not show ([`WebExport::kept`]) and an optional `path`: what +/// `webExport.settings`, `document.exportForWeb` and `file.saveForWeb` read. +fn settings_of(options: &SaveForWebOptions, table: &Value, kept: &Value, path: Option<&str>) -> Value { let mut v = serde_json::to_value(options).unwrap_or(Value::Null); if let Some(o) = v.as_object_mut() { + if let Some(kept) = kept.as_object() { + o.extend(kept.clone()); + } let [r, g, b] = options.matte; o.insert("matte".into(), json!(format!("#{r:02x}{g:02x}{b:02x}"))); o.remove("colorTable"); @@ -170,7 +187,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let host = app.dialogs().ok_or("no window")?; let ctx = app.ui_ctx.clone().ok_or("no window")?; let s = remembered(app); - app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), ..WebExport::default() }; + app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), kept: kept_of(&s), ..WebExport::default() }; let (name, artboards, slices) = { let st = app.session.active().ok_or("no document")?; let slices: Vec = st @@ -472,7 +489,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { on_dialog(&host, |d| d.answer_optimize(answer.map_err(Into::into))); } if asked.browser { - let p = settings_of(&asked.options, &app.web_export.table, None); + let p = settings_of(&asked.options, &app.web_export.table, &app.web_export.kept, None); if let Err(e) = browser_preview(app, &p) { app.status(e); } @@ -488,11 +505,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { /// The encodes the dialog wants, as pictures, and the Original pane's picture when the rendering is new. fn answer_variants(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::shell::WindowDialogs, wanted: &[WantedVariant]) { - let table = app.web_export.table.clone(); + let (table, kept) = (app.web_export.table.clone(), app.web_export.kept.clone()); let mut answers = Vec::with_capacity(wanted.len()); for w in wanted { let (index, revision) = (w.index, w.request.revision); - let settings = app.session.web_settings(&settings_of(&w.request.options, &table, None)); + let settings = app.session.web_settings(&settings_of(&w.request.options, &table, &kept, None)); let rendered = settings.and_then(|s| render_for(app, &s).map(|(key, r)| (s, key, r))); answers.push(match (rendered, app.session.active()) { (Ok((s, key, r)), Some(st)) => optimise(ctx, &st.doc, &r, &key, &s, w), @@ -532,7 +549,7 @@ fn edit_table(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::s /// The source colours of the palette the dialog's settings `options` show, with the table as it stands. fn shown_colors(app: &mut VectorcraftApp, options: &SaveForWebOptions) -> Result, String> { - let settings = app.session.web_settings(&settings_of(options, &app.web_export.table, None))?; + let settings = app.session.web_settings(&settings_of(options, &app.web_export.table, &app.web_export.kept, None))?; Ok(encoded(app, &settings)?.colors.iter().map(|c| c.source).collect()) } @@ -565,7 +582,7 @@ fn store_presets(app: &mut VectorcraftApp, events: Vec) { for event in events { let r = match event { WebPresetEvent::Saved(p) => { - let mut v = settings_of(&p.options, &app.web_export.table, None); + let mut v = settings_of(&p.options, &app.web_export.table, &app.web_export.kept, None); v["name"] = json!(p.name); app.run("webExport.presets.save", v) } @@ -596,7 +613,7 @@ fn has_slices(app: &VectorcraftApp) -> bool { /// The `webExport.optimizeToFileSize` params: `options`, the desired size and, with slices, what it covers. fn optimize_params(app: &VectorcraftApp, options: &SaveForWebOptions, desired_k: f64, start: Option<&str>, scope: &str) -> Value { - let mut p = settings_of(options, &app.web_export.table, None); + let mut p = settings_of(options, &app.web_export.table, &app.web_export.kept, None); if let Some(o) = p.as_object_mut() { o.insert("desiredK".into(), json!(desired_k)); if let Some(start) = start { @@ -617,7 +634,7 @@ fn optimize_start(app: &mut VectorcraftApp, options: &SaveForWebOptions) -> Opti let r = app.run("webExport.optimizeToFileSize", p).ok()?; return r["achieved"].as_bool().filter(|a| *a).and_then(|_| r["bytes"].as_u64()); } - let s = app.session.web_settings(&settings_of(options, &app.web_export.table, None)).ok()?; + let s = app.session.web_settings(&settings_of(options, &app.web_export.table, &app.web_export.kept, None)).ok()?; encoded(app, &s).ok().map(|o| o.bytes.len() as u64) } @@ -637,6 +654,7 @@ fn run_optimize(app: &mut VectorcraftApp, req: &OptimizeRequest) -> Result Result s, Err(e) => { on_dialog(host, HostedSaveForWeb::cancel_requests); @@ -698,8 +716,9 @@ fn answer_path(app: &VectorcraftApp, id: DialogId, key: &str, path: PathBuf) { /// written. Failures show in the status line; the dialog has closed. fn finish(app: &mut VectorcraftApp, result: SaveForWebResult) { let table = std::mem::take(&mut app.web_export.table); + let kept = std::mem::take(&mut app.web_export.kept); app.web_export = WebExport::default(); - let params = settings_of(&result.options, &table, None); + let params = settings_of(&result.options, &table, &kept, None); if let Err(e) = app.run("webExport.settings", params.clone()) { return app.status(e); } diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests.rs b/crates/ui-egui/src/dialogs/save_for_web/tests.rs index 400e43fe82..85cba5810d 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests.rs @@ -312,6 +312,31 @@ fn save_remembers_and_writes_and_done_only_remembers() { assert!(!dir.join("Untitled-1.png").exists()); } +/// The remembered Transparency Dither, which the dialog does not show, reaches the file Save writes +/// and stays remembered after Done. +#[test] +fn save_keeps_the_remembered_transparency_dither() { + let dir = vectorcraft_testkit::temp_dir("sfw-tdither"); + let (mut app, _) = app(&dir, false); + let mut written = vec![]; + for method in ["none", "noise"] { + app.run("webExport.settings", json!({"format": "gif", "transparency": true, "transparencyDither": method})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + save(&mut app); + let path = dir.join("Untitled-1.gif"); + written.push(std::fs::read(&path).unwrap()); + std::fs::remove_file(&path).unwrap(); + assert_eq!(app.session.last_web_settings().transparency_dither.id(), method, "remembered"); + let expected = app.session.execute("document.exportForWeb", &json!({"format": "gif", "transparencyDither": method})).unwrap(); + assert_eq!(expected["files"][0]["dataBase64"].as_str().and_then(vectorcraft_format::base64_decode).as_ref(), written.last()); + } + assert_ne!(written[0], written[1], "the partly transparent edge is dithered"); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "choice", json!("done")); + confirm(&mut app); + assert_eq!(app.session.last_web_settings().transparency_dither.id(), "noise"); +} + #[test] fn html_output_with_slices_saves_the_page_and_images() { let dir = vectorcraft_testkit::temp_dir("sfw-html"); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6b6829de5a..02833f1005 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1013,7 +1013,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - SVG Options: Show in Browser opens the SVG in the default web browser, beside Show Code, which shows the code instead; the SVG export options on the help page (https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) list both. VectorCraft writes the SVG of the dialog's current choices for one page to a new folder inside `VectorCraft SVG Preview` in the system's temporary folder, which is kept and cleaned up as Save for Web's previews are, and the dialog stays open without remembering the choices or writing the chosen file. The page is VectorCraft's own choice: under Export Selection the selection's crop, otherwise the first artboard the options choose, and a range the document does not have is an error. The web build disables the button, and control and MCP requests for `file.export.svg.browser` are refused. `crates/ui-egui/src/dialogs/svg_options.rs` (`show_in_browser_opens_what_ok_writes_without_confirming`, `show_in_browser_is_refused_on_the_web_and_for_automation`, `svg_preview_folders_leave_save_for_web_previews_alone`). - Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged. - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). - - Save for Web: with Transparency on, GIF and PNG-8 exports take a Transparency Dither (none, diffusion, pattern and noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an amount for diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is none with amount 100; with pattern, noise, or diffusion at amount 100, about as many pixels stay opaque as their opacity says, and a lower diffusion amount comes closer to none; pattern uses an 8×8 ordered pattern and noise a fixed noise, so the same art always gives the same file; amount 0 gives the same file as none; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; without Transparency both settings are kept and do not change the file; presets and the remembered settings keep them (`document.exportForWeb`, `webExport.settings`: `transparencyDither`, `transparencyDitherAmount`). The Save for Web dialog does not show these settings yet. + - Save for Web: with Transparency on, GIF and PNG-8 exports take a Transparency Dither (none, diffusion, pattern and noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an amount for diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is none with amount 100; with pattern, noise, or diffusion at amount 100, about as many pixels stay opaque as their opacity says, and a lower diffusion amount comes closer to none; pattern uses an 8×8 ordered pattern and noise a fixed noise, so the same art always gives the same file; amount 0 gives the same file as none; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; without Transparency both settings are kept and do not change the file; presets and the remembered settings keep them (`document.exportForWeb`, `webExport.settings`: `transparencyDither`, `transparencyDitherAmount`). The Save for Web dialog does not show these settings yet; its previews and Save… use the remembered ones, and a preset picked in the dialog does not change them. - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. - Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). From 9c65a21fce9eeb731ca49d820adf52d8e597548b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 05:03:25 -0800 Subject: [PATCH 078/101] Parametric Shape: W and H keep the center with anchors direct-selected With anchors direct-selected, the shared reference point locator shows the box around those anchors, not the shape's own box. The panel's W and H now leave out the reference point in that case, so the shape keeps its center as it did before. --- crates/ui-egui/src/addons/pathtools/shape.rs | 12 ++++++++++-- crates/ui-egui/src/addons/pathtools/tests.rs | 15 +++++++++++++++ docs/target-app-parity.md | 3 ++- 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/addons/pathtools/shape.rs b/crates/ui-egui/src/addons/pathtools/shape.rs index ba6f17847b..49feea17c0 100644 --- a/crates/ui-egui/src/addons/pathtools/shape.rs +++ b/crates/ui-egui/src/addons/pathtools/shape.rs @@ -70,6 +70,13 @@ pub(super) fn target(app: &VectorcraftApp) -> (Option, ParametricShape) (None, apply(fallback, &app.session.tool_options_of(tool::ID)).unwrap_or(fallback)) } +/// Whether anchors are direct-selected, so that the selection's box is the box around them. +fn anchors_selected(app: &VectorcraftApp) -> bool { + app.session + .active() + .is_some_and(|st| vectorcraft_effects::preview::anchor_bounds_with(&st.selection, &st.doc, app.session.bounds_measure()).is_some()) +} + /// Whether something is selected and none of it is a parametric shape Convert could take. pub(super) fn plain_selected(app: &VectorcraftApp) -> bool { app.session.active().is_some_and(|st| !st.selection.is_empty()) && selected(app).is_none() @@ -144,8 +151,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { (Some(mut p), Some(id)) => { p["id"] = json!(id.0); // The Transform panel and the Control bar share one reference point locator. W and H - // keep the point of the shape's bounding box chosen there in place. - if p.get("width").or_else(|| p.get("height")).is_some() { + // keep the point of the shape's bounding box chosen there in place. With anchors + // direct-selected the locator shows their box, so the shape keeps its center instead. + if p.get("width").or_else(|| p.get("height")).is_some() && !anchors_selected(app) { p["reference"] = json!(app.ui.transform_panel.reference_point); } run(app, "addon.pathtools.shape.set", p); diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 5a5ef823bb..6a92443213 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -133,6 +133,21 @@ fn the_parametric_shape_panels_size_fields_keep_the_shared_reference_point() { let moved = app.selection_box().unwrap().reference_point(refi).distance(was); assert!(moved < 1e-6, "reference {refi}, rotation {rotation}: the reference point moved {moved} pt"); } + // With an anchor direct-selected the locator shows the anchors' box, so W keeps the shape's center. + let mut app = app(); + let params = json!({"kind": "rectangle", "center": [150, 150], "width": 100, "height": 60}); + let id = vectorcraft_doc::NodeId(app.run("addon.pathtools.shape.create", params).unwrap()["id"].as_u64().unwrap()); + app.session + .select(|_, sel| { + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + app.ui.transform_panel.reference_point = 0; + let mut panel = Panel::new(app, super::shape::show); + panel.type_into("W", "160"); + let app = panel.app(); + let after = vectorcraft_tools::addons::parametric_shape::read(app.session.active().unwrap().doc.node(id).unwrap()).unwrap(); + assert!((after.width - 160.0).abs() < 1e-6 && after.center.distance(vectorcraft_geom::Point::new(150.0, 150.0)) < 1e-6, "{after:?}"); } /// The Corner Tool and Shared Edge Merge Tool items leave a floating Anchor Inspector showing diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 18d03d101d..7b428e7827 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2862,7 +2862,8 @@ The add-on's Parametric Shape Tool (2026-10-30) draws ten kinds of shape that st ellipse, polygon and star with 3 to 1,000 sides or points, ring, arrow, cross, heart, gear, speech bubble; corner radius limited to the middle of a side): a drag from the centre sizes and turns one, the arrow keys change its count and values while dragging, handles edit a selected one, a double-click places one with the last settings, and its panel edits the -numbers (its W and H keep the point chosen in the shared reference point locator in place). A shape is a plain path +numbers (its W and H keep the point chosen in the shared reference point locator in place, and the center when anchors +are direct-selected). A shape is a plain path whose numbers and outline fingerprint sit in one object-data entry that SVG export leaves out; moving, rotating or scaling it keeps it editable, editing its anchors makes it a plain path. Convert to Parametric Shape recognises plain rectangles, ellipses and regular polygons. Geometry in From 73822f7acabdcad70f32bea67c1fbd7433c42bc5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 05:33:24 -0800 Subject: [PATCH 079/101] Docs: the pen-value limits name the stylus wheel and the seventh point field The Blob Brush and Eraser Tool Options line now says the Blob Brush's Size also offers Stylus Wheel, and the line on refused pen values names the wheel's 0 to 1 range and allows seven numbers per point, with the wheel seventh, as path.blob and path.freehand read them. --- docs/target-app-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 62cbd64d95..9a0e446379 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1445,8 +1445,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Select ▸ Update Selection replaces the objects of the saved selection last recalled with the selected objects, in one undo step that marks the document changed (`select.update`). After Edit Selection… renames that saved selection, Update Selection replaces it under the new name; after Edit Selection… deletes it, Update Selection is disabled until another saved selection is recalled or the delete is undone. Undo and Redo do not change which saved selection is recalled. - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). In Draw Behind, an Alt-drag copy made with the Selection or Direct Selection tool goes directly below its original and is selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists duplicating by Alt-drag among the actions the mode applies to; with several objects, each copy goes below its own original in that original's group or layer, the copy of the clipping path of a clip group or a clipping layer goes directly above it so the clipping path stays the bottom object, and in Draw Normal and Draw Inside, and for the transform dialogs' Copy, Duplicate and Transform Again, copies still go above (VectorCraft's own rules). In Draw Behind, a placed symbol instance (Place Symbol Instance in the Symbols panel, and a symbol dragged onto the canvas from the Symbols panel or a symbol library) goes directly below the selected object, or at the bottom of the current layer with nothing selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) describes for placing symbols; below the bottommost of several selected objects, beside the compound path that holds a selected path, and above a clipping path are VectorCraft's own rules. Draw Normal and Draw Inside keep it on top of the current layer. - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). - Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. - `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). + Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961), and the Blob Brush's Size also offers Stylus Wheel (see Blob Brush Size on the stylus wheel): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. + `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360°, a stylus wheel reading outside 0 to 1 and a point array of more than seven numbers (the wheel is the seventh), with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation, rotation and wheel ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). With the Blob Brush, Shift held during a drag keeps the stroke on the horizontal or vertical line through the press point, whichever is nearer to the pointer (90° steps from the Constrain Angle preference), and the points dragged since Shift went down move to the other line when the pointer crosses to it; the points dragged while Shift is up follow the pointer. With the Blob Brush, Alt held before the press, or pressed before the drag has moved, switches to the Smooth tool, as the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists: the cursor shows the Smooth tool (Not Allowed with no path selected that it can act on), the drag shows a thin line and, with a path selected that it can smooth, the dashed band it smooths, without the length label, Shift does not constrain it, and the release smooths the selected paths under the drag (`path.smoothRegion`) instead of painting; with nothing selected the release changes no path. A stroke that has moved keeps painting when Alt goes down. Curvature point markers are circular, with no direction handles. While drawing, its own point feedback replaces generic selection markers; existing paths use the selection overlay, including partial selections and Hide Edges. Anchor Size applies, and Direct Selection and Pen retain their handles. The real egui-frame regressions in `crates/ui-egui/src/canvas.rs` verify marker positions, counts and unchanged documents (#1236, in part); the existing-path interpolation request remains open. The curve through the points (`curvature_spline` in `crates/tools/src/draw2.rs`) makes each stretch of three points follow the circle through them: a smooth point's handles lie along that circle's tangent, each `chord / (3 cos²(α/2))` long (α between handle and chord, capped at 90°), and the ends of an open path mirror their neighbour's tangent in their chord, so a J or a U curves evenly, a turn tighter than 30° comes to a point, and uneven spacing doesn't loop; the rubber band, a dragged or inserted point and `path.convertAnchor` to smooth use the same rule, while the Pencil's fitting keeps its own; `tests/draw2.rs` checks that the rubber band is the path the click makes (#1236, in part). The Smooth tool smooths only the stretch of path under the drag (#1547, fixes #1512). A path the Smooth tool changes stays selected whole, and the anchor points and segments selected on it with Direct Selection are deselected. Selected paths the drag does not change keep their selected anchors, and undo restores the earlier selection (`tests/draw2.rs`, `smoothing_a_path_drops_its_direct_selected_anchors`). While the Smooth tool drags with a path selected that it can smooth, a dashed outline shows the band it smooths: everything within its radius of the drag (12 screen pixels, VectorCraft's own value), round at both ends; Alt smoothing with the Pencil, Paintbrush and Blob Brush shows the same band. From 3a0bfba3254abc9eff8a44a71a593457d52e7885 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 09:15:23 -0800 Subject: [PATCH 080/101] File dialogs: a replace confirmation runs under the file access of the request that asked A file dialog's answer runs its continuation under the file-access scope and automation flag of the request that opened the dialog. The questions that follow a request did not keep them, and ran what OK allows in the unconfined UI frame: - the Replace question after a save picker names an existing file (file_asks::ask_replace); - the question whether a save or export may replace the files it writes beside the one picked (confirm::ask_replace_files), also when a Background Save or Export asks it after the request has ended; - a confirmation whose OK runs a command (confirm::ask), such as the question before a save loses data. A save, export or open started by a request confined to its automation roots could then reach files outside those roots once the person answered OK, and it no longer ran as automation. Each question now captures ScopeHandle::capture() and automation_asked() when it is asked, and its OK runs under them, as a picker's answer does. A background save or export captures them before it leaves the request. --- crates/ui-egui/src/dialogs/confirm.rs | 40 ++++++++++++--- crates/ui-egui/src/file_asks.rs | 16 ++++-- crates/ui-egui/src/io/export.rs | 4 +- crates/ui-egui/src/io/save.rs | 24 +++++++-- crates/ui-egui/src/tests/picks.rs | 74 +++++++++++++++++++++++++++ crates/ui-egui/src/tests/save.rs | 32 ++++++++++++ 6 files changed, 174 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 9584166098..12e13a36b3 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -7,6 +7,7 @@ use craft::ui::dialog::{Alert, DialogHost, DialogId, DialogResult, HostedAlert, PromptChoice, StackDialog, StandardPrompt, StartupStage}; use egui::Context; use serde_json::{Value, json}; +use vectorcraft_engine::file_access::ScopeHandle; use crate::VectorcraftApp; @@ -81,8 +82,18 @@ macro_rules! wrapped_dialog { } pub(crate) use wrapped_dialog; -/// A confirmation: its tag is the command OK runs and that command's params. +/// A confirmation: its tag is an [`Asked`]. pub(crate) struct Question(StandardPrompt); + +/// The tag of a confirmation ([`ask`]): the command OK runs, and the access it runs under. +struct Asked { + command: String, + params: Value, + /// The automation roots in force when asked: the command runs under them. + scope: ScopeHandle, + /// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs as automation. + automated: bool, +} wrapped_dialog!(Question, StandardPrompt, KIND); /// A message with a Close button. @@ -110,6 +121,10 @@ pub(crate) struct ReplaceFiles { pub(crate) command: String, /// Its params. pub(crate) params: Value, + /// The automation roots in force when asked: the command runs again under them. + pub(crate) scope: ScopeHandle, + /// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs again as automation. + pub(crate) automated: bool, } /// Ask `message` (with an optional `detail` line), both in the UI language; OK runs `command` @@ -123,7 +138,8 @@ pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, if !detail.is_empty() { prompt = prompt.paragraph(detail.to_string()); } - let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag((command.to_string(), params)); + let asked = Asked { command: command.to_string(), params, scope: ScopeHandle::capture(), automated: app.automation_asked() }; + let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag(asked); dialogs.with(|host| host.open(Question(prompt))); } @@ -184,6 +200,8 @@ pub(crate) fn ask_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[Str allowed: allowed.to_vec(), command: command.to_string(), params, + scope: ScopeHandle::capture(), + automated: app.automation_asked(), }); // Asked when a Background Save or Export ends: a dialog open then stays, and this waits its turn // (however many messages wait: the save or export needs the answer). @@ -240,8 +258,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { }; if let Some(DialogResult::Ok(mut answer)) = dialogs.with(|host| host.take::()) && answer.choice == PromptChoice::Proceed - && let Some((command, params)) = answer.take_tag::<(String, Value)>() - && let Err(e) = app.run(&command, params) + && let Some(Asked { command, params, scope, automated }) = answer.take_tag::() + && let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params))) { app.status(e); } @@ -273,8 +291,8 @@ pub(crate) fn pump_missing_font(app: &mut VectorcraftApp, _ctx: &Context) { pub(crate) fn open_question(app: &VectorcraftApp) -> Option<(String, String, String)> { app.dialogs()?.with(|host| { let prompt = &host.get::()?.0; - let (command, _) = prompt.tag_as::<(String, Value)>()?; - Some((prompt.shown_message(&app.host), prompt.shown_paragraphs(&app.host).join("\n"), command.clone())) + let asked = prompt.tag_as::()?; + Some((prompt.shown_message(&app.host), prompt.shown_paragraphs(&app.host).join("\n"), asked.command.clone())) }) } @@ -290,3 +308,13 @@ pub(crate) fn open_message(app: &VectorcraftApp) -> Option<(String, String)> { pub(crate) fn open_replace_files(app: &VectorcraftApp) -> Option> { app.dialogs()?.with(|host| host.get::().and_then(|q| q.0.tag_as::().map(|tag| tag.files.clone()))) } + +/// Whether the open question about replacing files runs its command confined to automation roots, +/// and whether as automation, while it is open. +#[cfg(test)] +pub(crate) fn open_replace_files_access(app: &VectorcraftApp) -> Option<(bool, bool)> { + app.dialogs()?.with(|host| { + let tag = host.get::()?.0.tag_as::()?; + Some((tag.scope.clone().run(vectorcraft_engine::file_access::current).is_some(), tag.automated)) + }) +} diff --git a/crates/ui-egui/src/file_asks.rs b/crates/ui-egui/src/file_asks.rs index 9624d81a5e..93f05ed678 100644 --- a/crates/ui-egui/src/file_asks.rs +++ b/crates/ui-egui/src/file_asks.rs @@ -51,6 +51,10 @@ struct Waiting { /// A replace question on the dialog host, and what proceeding runs. struct Replacing { dialog: DialogId, + /// The automation roots in force when asked, as [`Waiting::scope`]. + scope: ScopeHandle, + /// Automation asked, as [`Waiting::automated`]. + automated: bool, then: Proceed, } @@ -155,7 +159,8 @@ pub(crate) fn ask_replace( app.file_asks.next_question += 1; let prompt = StandardPrompt::replace_file(name(path), Some(name(answered))).instance(("vectorcraft.replaceFile", app.file_asks.next_question)); let dialog = dialogs.with(|host| host.open(prompt)); - app.file_asks.replacing.push(Replacing { dialog, then: Box::new(then) }); + let (scope, automated) = (ScopeHandle::capture(), app.automation_asked()); + app.file_asks.replacing.push(Replacing { dialog, scope, automated, then: Box::new(then) }); json!({ "pending": "replaceFile" }) } @@ -307,7 +312,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let files = dialogs.with(|host| { for r in previous { match host.take_by_id::(r.dialog) { - Some(DialogResult::Ok(answer)) if answer.choice == PromptChoice::Proceed => proceed.push(r.then), + Some(DialogResult::Ok(answer)) if answer.choice == PromptChoice::Proceed => proceed.push(r), Some(_) => {} None if host.get_by_id::(r.dialog).is_some() => open.push(r), // Neither open nor holding a result: closed from outside. @@ -317,8 +322,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { host.take::() }); app.file_asks.replacing.extend(open); - for then in proceed { - let result = then(app); + for Replacing { scope, automated, then, .. } in proceed { + let result = scope.run(|| as_automated(app, automated, then)); report(app, result); } if let Some(DialogResult::Ok(mut answer)) = files @@ -328,7 +333,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { { let all: Vec = r.files.iter().chain(&r.allowed).cloned().collect(); crate::io::save::allow_replacing(app, &all); - let result = app.run(&r.command, r.params); + let ReplaceFiles { scope, automated, command, params, .. } = r; + let result = scope.run(|| as_automated(app, automated, |app| app.run(&command, params))); report(app, result); } } diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index 8f19aaef13..e3acc7f9b8 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -157,6 +157,8 @@ fn write_export(app: &mut VectorcraftApp, export: Export, path: String) -> Resul let (exists, allowed) = checks_replaced(app); let allowed_before = allowed.clone(); let rerun = with_path(&again, &path); + // The question whether the export may replace files is asked under the request's scope. + let asked_access = (vectorcraft_engine::file_access::ScopeHandle::capture(), app.automation_asked()); let work = move |write: Writer| { progress::scope(&reporting, || { cancel::check().map_err(|e| e.to_string())?; @@ -192,7 +194,7 @@ fn write_export(app: &mut VectorcraftApp, export: Export, path: String) -> Resul // Nothing written: asked first. if let Some(files) = r.get("replaces").and_then(Value::as_array) { let files: Vec = files.iter().filter_map(Value::as_str).map(str::to_string).collect(); - return Ok(ask_to_replace_files(app, uid, &files, &allowed_before, "file.exportAs", &rerun)); + return Ok(ask_to_replace_files(app, uid, &files, &allowed_before, "file.exportAs", &rerun, asked_access)); } let what = match r["files"].as_array() { Some(files) => format!("{} files", files.len()), diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 322ab69b1f..97c9c89be2 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -13,6 +13,7 @@ use craft::platform::watch::FileWatch; use craft::ui::dialog::DialogId; #[cfg(not(target_arch = "wasm32"))] use craft::ui::dialog::{DialogResult, PromptChoice, StandardPrompt}; +use vectorcraft_engine::file_access::ScopeHandle; use super::export::file_url; use super::open::note_recent; @@ -811,9 +812,22 @@ pub(super) fn checks_replaced(app: &mut VectorcraftApp) -> (Option Value { - dialogs::confirm::ask_replace_files(app, doc, files, allowed, command, params.clone()); +/// (those an earlier OK allowed); Cancel writes nothing → `{pending}`. `asked` is the file-access +/// scope and automation flag of the request that started the save or export, captured before it +/// went to the background: OK runs `command` again under them. +pub(super) fn ask_to_replace_files( + app: &mut VectorcraftApp, + doc: u64, + files: &[String], + allowed: &[String], + command: &str, + params: &Value, + asked: (ScopeHandle, bool), +) -> Value { + let (scope, automated) = asked; + scope.run(|| { + file_asks::as_automated(app, automated, |app| dialogs::confirm::ask_replace_files(app, doc, files, allowed, command, params.clone())); + }); json!({ "pending": dialogs::confirm::REPLACE_FILES }) } @@ -1017,6 +1031,8 @@ fn write_plan( // Capture the caller before background work leaves the request: it must never open a panel // or error dialog later, when answering_control has been reset. let by_control = app.automation_asked(); + // The question whether the save may replace files is asked under the request's scope. + let asked_scope = ScopeHandle::capture(); let location_refused = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let refused_by_work = location_refused.clone(); let own_path = target.clone(); @@ -1099,7 +1115,7 @@ fn write_plan( // Nothing written either: asked first. if let Some(files) = r.get("replaces").and_then(Value::as_array) { let files: Vec = files.iter().filter_map(Value::as_str).map(str::to_string).collect(); - return Ok(ask_to_replace_files(app, uid, &files, &allowed, again.0, &again.1)); + return Ok(ask_to_replace_files(app, uid, &files, &allowed, again.0, &again.1, (asked_scope, by_control))); } // The document may have closed meanwhile: the file is written all the same. done.complete(&mut app.session, uid); diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index 0b081f125c..7511d656d3 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -15,6 +15,7 @@ use craft::ui::runtime::requests::{PathKind, PathRequest}; use egui::{Pos2, Rect, vec2}; use serde_json::{Value, json}; use vectorcraft_engine::Session; +use vectorcraft_engine::file_access; use crate::dialogs::confirm::REPLACE_FILES; use crate::{Services, VectorcraftApp, file_asks}; @@ -394,6 +395,79 @@ fn a_pdf_automation_asked_for_is_not_opened_when_its_save_panel_answers() { assert!(matches!(urls.as_slice(), [url] if url.ends_with("/art/mine.pdf")), "{urls:?}"); } +/// A replace question automation asked while confined to a folder: what Replace allows runs as +/// automation's, with that folder still the only place it may write, as the answer of a file dialog does. +#[test] +fn a_replace_question_goes_on_under_the_access_it_was_asked_with() { + let mut app = app(); + app.ui_ctx = Some(crate::testing::ui_context()); + let (inside, outside) = (vectorcraft_testkit::TempDir::new("replace-scope-in"), vectorcraft_testkit::TempDir::new("replace-scope-out")); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let path = inside.join("Art.svg").to_string_lossy().into_owned(); + let elsewhere = outside.join("Art.svg").to_string_lossy().into_owned(); + let seen = Rc::new(RefCell::new(None)); + let s = seen.clone(); + file_access::confine(roots.as_ref(), || { + file_asks::as_automated(&mut app, true, |app| { + file_asks::ask_replace(app, &path, "Art", move |app| { + *s.borrow_mut() = Some((file_access::check_write(&elsewhere).is_ok(), app.automation_asked())); + Ok(Value::Null) + }) + }) + }); + assert_eq!(replace_asked(&app).as_deref(), Some("Art.svg")); + answer_replace(&mut app, true); + assert_eq!(*seen.borrow(), Some((false, true)), "(may write outside the folder, runs as automation's)"); +} + +/// The question whether a save or export may replace files, asked by automation confined to a +/// folder: OK runs the command again with that folder still the only place it may read. +#[test] +fn a_replace_files_question_runs_its_command_under_the_access_it_was_asked_with() { + let mut app = app(); + app.ui_ctx = Some(crate::testing::ui_context()); + app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); + let (inside, outside) = + (vectorcraft_testkit::TempDir::new("replace-files-scope-in"), vectorcraft_testkit::TempDir::new("replace-files-scope-out")); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let elsewhere = outside.join("Other.svg"); + std::fs::write(&elsewhere, SVG).unwrap(); + let elsewhere = elsewhere.to_string_lossy().into_owned(); + let doc = app.session.active().unwrap().uid; + let there = [inside.join("Art.svg").to_string_lossy().into_owned()]; + file_access::confine(roots.as_ref(), || { + file_asks::as_automated(&mut app, true, |app| { + crate::dialogs::confirm::ask_replace_files(app, doc, &there, &[], "file.open", json!({ "path": elsewhere })); + }) + }); + assert_eq!(crate::dialogs::confirm::open_replace_files(&app), Some(there.to_vec())); + answer_replace(&mut app, true); + assert!(app.ui.status.contains("outside the read root"), "the file outside the folder is refused: {}", app.ui.status); + assert_eq!(app.session.documents().len(), 1, "nothing else opened"); +} + +/// A confirmation automation asked while confined to a folder: OK runs its command as automation's, +/// with that folder still the only place it may read. +#[test] +fn a_confirmation_runs_its_command_under_the_access_it_was_asked_with() { + let mut app = app(); + app.ui_ctx = Some(crate::testing::ui_context()); + let (inside, outside) = (vectorcraft_testkit::TempDir::new("confirm-scope-in"), vectorcraft_testkit::TempDir::new("confirm-scope-out")); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + let elsewhere = outside.join("Other.svg"); + std::fs::write(&elsewhere, SVG).unwrap(); + let elsewhere = elsewhere.to_string_lossy().into_owned(); + file_access::confine(roots.as_ref(), || { + file_asks::as_automated(&mut app, true, |app| { + crate::dialogs::confirm::ask(app, "Open it?", "", "file.open", json!({ "path": elsewhere })); + }) + }); + let id = open_dialogs(&app).last().map(|d| d.id).expect("the question is open"); + answer_dialog(&mut app, id, &[], true); + assert!(app.ui.status.contains("outside the read root"), "the file outside the folder is refused: {}", app.ui.status); + assert!(app.session.documents().is_empty(), "nothing opened"); +} + /// A Browse row's answer fills the open dialog's field; an answer after the dialog closed does nothing. #[test] fn a_dialogs_folder_button_fills_its_field_when_the_picker_answers() { diff --git a/crates/ui-egui/src/tests/save.rs b/crates/ui-egui/src/tests/save.rs index 2c1fc025df..c5a2815463 100644 --- a/crates/ui-egui/src/tests/save.rs +++ b/crates/ui-egui/src/tests/save.rs @@ -420,6 +420,38 @@ fn an_eps_save_with_use_artboards_asks_before_replacing_an_artboard_file_that_is let _ = std::fs::remove_dir_all(d); } +/// A background save that automation confined to a folder started asks about the files it would +/// replace once its result arrives, outside the request; OK still runs the save again under that +/// folder and as automation. +#[test] +fn a_background_save_asks_about_replacing_files_under_the_access_of_the_request_that_started_it() { + let d = dir("eps-artboards-confined"); + let path = d.join("Art.eps").to_string_lossy().to_string(); + let options = json!({"useArtboards": true, "previewFormat": "none", "thumbnails": false}); + let mut other = app(); + other.run("file.new", json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + let _ = other.run("file.saveAs", json!({"path": path, "options": options})); + let there = artboard_files(&d); + assert_eq!(there.len(), 2, "{there:?}"); + std::fs::remove_file(&path).unwrap(); + let mut app = app(); + checks_files_there(&mut app); + app.services.write_shared = Some(std::sync::Arc::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + rect(&mut app); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[d.as_path()], &[d.as_path()]).unwrap(); + let r = vectorcraft_engine::file_access::confine(roots.as_ref(), || { + crate::file_asks::as_automated(&mut app, true, |app| app.run("file.saveAs", json!({"path": path, "options": options}))) + }) + .unwrap(); + assert_eq!(r["background"], true, "{r}"); + // The save's result is applied outside the request, as the next frame does. + crate::background::wait_all(&mut app); + assert_eq!(confirm::open_replace_files(&app), Some(there.clone())); + assert_eq!(confirm::open_replace_files_access(&app), Some((true, true)), "(confined, as automation)"); + let _ = std::fs::remove_dir_all(d); +} + #[test] fn native_saves_stream_into_the_file() { let d = dir("stream"); From 05b6a15d487de2a215885fee9cbc555e939f245d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 10:37:15 -0800 Subject: [PATCH 081/101] =?UTF-8?q?Guides:=20selected=20ruler=20guides=20r?= =?UTF-8?q?otate=20with=20the=20Rotate=20tool=20and=20Object=20=E2=80=BA?= =?UTF-8?q?=20Transform=20=E2=80=BA=20Rotate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A selected ruler guide was left out of every transform but a move: the Rotate tool did nothing with only guides selected, and Object › Transform › Rotate… refused with "nothing selected". Each selected ruler guide now transforms as the line Release Guides makes of it (across its artboard, or across the artboards' bounds for a canvas guide), about the center of the selected objects' box and those lines together. A guide that ends up vertical or horizontal stays a ruler guide: a half turn keeps it and a quarter turn makes a horizontal guide vertical. At any other angle it becomes a guide path along its line, on the guide's layer, so it snaps, releases, locks and saves as other guide paths do. - Object › Transform › Rotate… (Copy included), Transform Again and the Rotate tool's drag and Alt-click work with only guides selected, in one undo step. A turn that leaves the guides where they were records none. - Scale, Reflect, Shear and the bounding box now transform selected guides along with the selected objects and direct-selected anchors, where before the guides stayed put. - Locked and hidden guides, guides with ids given and guides with Transform Objects off do not transform. `absolute` with only guides selected is an error. Part of #2418. --- crates/doc/src/document_guides.rs | 65 +++++++++++++ crates/doc/src/lib.rs | 1 + crates/engine/src/cmd/docmenu.rs | 9 +- crates/engine/src/cmd/object/commands.rs | 6 +- crates/engine/src/cmd/object/transform.rs | 44 ++++++++- crates/engine/src/cmd/path.rs | 15 ++- crates/engine/src/tests/menucmds.rs | 109 ++++++++++++++++++++++ crates/tools/src/xform/transform.rs | 71 ++++++++++++-- docs/mcp.md | 10 ++ docs/target-app-parity.md | 1 + 10 files changed, 309 insertions(+), 22 deletions(-) diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index ba203610d6..909fedd04d 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -5,6 +5,15 @@ use super::node::{held_guides, map_held, strip_held}; use super::{Affine, Arc, Document, Node, NodeId, NodeKind, PatternDef, Point, Rect, Selection, SymbolBoxes, Vec2, artboard_holds}; use std::collections::{BTreeMap, HashSet}; +/// What a transform makes of a ruler guide ([`Document::transformed_guide`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum GuideTransform { + /// It stays a ruler guide: vertical at x `pos`, or horizontal at y `pos`. + Ruler { vertical: bool, pos: f64 }, + /// It becomes a guide path along the line between the two points. + Path(Point, Point), +} + impl Document { /// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol /// instances measured by their art ([`Node::geometric_bounds_with`]). @@ -369,6 +378,62 @@ impl Document { Some(if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }) } + /// The line ruler guide `g` stands for as a path: across its artboard for an artboard guide, + /// and across the bounds of all the artboards for a canvas guide. None when there is no + /// artboard to measure a canvas guide by. + pub fn guide_line(&self, g: &Guide) -> Option<(Point, Point)> { + let artboards = || self.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)); + let (a, b) = self.guide_span(g).or_else(|| artboards().map(|r| if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }))?; + Some(if g.vertical { (Point::new(g.pos, a), Point::new(g.pos, b)) } else { (Point::new(a, g.pos), Point::new(b, g.pos)) }) + } + + /// What `xf` makes of ruler guide `g` ([`Self::transform_ruler_guides`]), or None when the + /// document has no line for it ([`Self::guide_line`]). + pub fn transformed_guide(&self, g: &Guide, xf: Affine) -> Option { + let (a, b) = self.guide_line(g)?; + let (a, b) = (xf * a, xf * b); + let tol = 1e-9 * a.distance(b).max(1.0); + Some(if (a.x - b.x).abs() <= tol { + GuideTransform::Ruler { vertical: true, pos: (a.x + b.x) / 2.0 } + } else if (a.y - b.y).abs() <= tol { + GuideTransform::Ruler { vertical: false, pos: (a.y + b.y) / 2.0 } + } else { + GuideTransform::Path(a, b) + }) + } + + /// Apply `xf` to the ruler guides selected in `sel`, each as the line [`Self::guide_line`] + /// gives it. A line that stays vertical or horizontal stays a ruler guide, at its new place. A + /// line at any other angle becomes a guide path with that line, on the guide's layer, named + /// as the guide was; `sel` then holds the path as a selected object instead of the guide. + /// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are. + pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) { + for id in sel.guides.clone() { + let Some(g) = self.ruler_guide(id).filter(|g| self.guide_editable(g)) else { continue }; + let (a, b) = match self.transformed_guide(&g, xf) { + Some(GuideTransform::Ruler { vertical, pos }) => { + self.edit_ruler_guide(id, |g| (g.vertical, g.pos) = (vertical, pos)); + continue; + } + Some(GuideTransform::Path(a, b)) => (a, b), + None => continue, + }; + let Some(layer) = self.parent_of(id) else { continue }; + let path = self.alloc_id(); + let look = crate::Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0); + let mut n = Node::path(path, vectorcraft_geom::shapes::line(a, b), look); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + n.name = g.name.clone(); + if self.insert(Some(layer), usize::MAX, n).is_err() { + continue; + } + self.retain_guides(sel, |g| g.id != Some(id)); + sel.objects.push(path); + } + } + /// The ruler guide node `g` names, if this document has it. fn guide_node(&self, g: &Guide) -> Option { g.id.filter(|id| self.node(*id).is_some_and(Node::is_ruler_guide)) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2ee96ec2f1..5c52b167a1 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -168,6 +168,7 @@ pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, Retire pub use canvas_range::BeyondCanvas; #[cfg(test)] use document_ext::free_id; +pub use document_guides::GuideTransform; pub use graphic_style::{DEFAULT_GRAPHIC_STYLE, GraphicStyle}; pub use guides::{GridPrefs, Guide, RulerMode}; #[cfg(test)] diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 717c9cdc14..1cf7af0334 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -14,8 +14,8 @@ use super::panelcmds::artboard_at; use super::pathops::Beside; use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable}; use super::{ - CommandSpec, EngineError, Point, Result, Session, bad, checked_ids_param, cmd, f64_req, has_doc, has_selection, id_param, number_or, ok, - str_param, switch_or, text_param, + CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, f64_req, has_doc, has_selection, id_param, number_or, ok, str_param, + switch_or, text_param, }; pub fn specs() -> Vec { @@ -730,13 +730,10 @@ fn release_guides(s: &mut Session, p: &Value) -> Result { }; // Find each ruler guide's line and its parent: the guide's layer, else where new art goes. let st = s.doc()?; - let artboards = st.doc.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)); let mut lines = Vec::with_capacity(rulers.len()); for &i in &rulers { let Some(g) = st.doc.ruler_guide(i) else { continue }; - let span = st.doc.guide_span(&g).or_else(|| artboards.map(|r| if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) })); - let Some((a, b)) = span else { continue }; - let (a, b) = if g.vertical { (Point::new(g.pos, a), Point::new(g.pos, b)) } else { (Point::new(a, g.pos), Point::new(b, g.pos)) }; + let Some((a, b)) = st.doc.guide_line(&g) else { continue }; let parent = match g.layer.filter(|l| st.doc.node(*l).is_some_and(Node::is_layer)) { Some(l) => Some(l), None => st.target_parent()?, diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 8ce478ad97..182dc0601f 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -34,8 +34,8 @@ pub fn specs() -> Vec { "Rotate…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), angle: deg (counter-clockwise), absolute?: bool (angle is the bounding box's new angle, not an amount), origin?: [x,y] (default: the bounding box centre), copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)} → {ids}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", - has_selection, + "{ids?: [id…] (selected first; default: the selection), angle: deg (counter-clockwise), absolute?: bool (angle is the bounding box's new angle, not an amount), origin?: [x,y] (default: the bounding box centre), copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)} → {ids}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box. Selected ruler guides that can be edited rotate too (without ids), each as the line view.guides.release makes of it, and the default origin is the center of the objects' box and those lines together: a guide that ends up vertical or horizontal stays a ruler guide, and one at any other angle becomes a selected guide path along its line. absolute with only ruler guides selected is an error.", + has_selection_or_guides, rotate ), cmd!( @@ -71,7 +71,7 @@ pub fn specs() -> Vec { ["Object", "Transform"], Some("Cmd+D"), "{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)", - has_selection, + has_selection_or_guides, transform_again ), cmd!( diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 1ccd74d57f..68c681b0a5 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -16,7 +16,27 @@ fn origin_of(s: &Session, p: &Value, ids: &[NodeId]) -> Result { { return Ok(b.center()); } - s.transform_box(ids).map(|b| b.center()).ok_or_else(|| EngineError::Other("selection has no bounds".into())) + // Selected ruler guides transform with the selection (not with objects named by `ids`, nor + // with Transform Objects off), so the center is that of the objects' box and the guides' + // lines together. + let guides = if p.get("ids").is_none_or(Value::is_null) && transforms_objects(p) { editable_guides(s)? } else { vec![] }; + let boxed = s.transform_box(ids); + if guides.is_empty() { + return boxed.map(|b| b.center()).ok_or_else(|| EngineError::Other("selection has no bounds".into())); + } + let objects = boxed.map(|b| { + let c = b.corners(); + c.iter().fold(Rect::from_points(c[0], c[0]), |r, p| r.union_pt(*p)) + }); + let lines = guides.into_iter().filter_map(|g| st.doc.guide_line(&g)).map(|(a, b)| Rect::from_points(a, b)); + let b = lines.fold(objects, |acc, r| Some(acc.map_or(r, |acc| acc.union(r)))); + b.map(|b| b.center()).ok_or_else(|| EngineError::Other("selection has no bounds".into())) +} + +/// The selected ruler guides that a transform changes: those that can be edited. +fn editable_guides(s: &Session) -> Result> { + let st = s.doc()?; + Ok(st.selection.guides.iter().filter_map(|id| st.doc.ruler_guide(*id)).filter(|g| st.doc.guide_editable(g)).collect()) } /// What a transform command scales besides geometry: Scale Strokes & Effects and Scale Corners from @@ -125,8 +145,18 @@ fn apply_transform_moving_guides( let c = xf.as_coeffs(); let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9; let delta = guides.unwrap_or(Vec2::new(c[4], c[5])); - let with_guides = objects && p.get("ids").is_none_or(Value::is_null) && is_translation; - let has_guides = with_guides && !s.doc()?.selection.guides.is_empty(); + // The selected ruler guides transform with the selection: a move moves them, and any other + // transform maps the line each one stands for ([`Document::transform_ruler_guides`]). + let with_guides = objects && p.get("ids").is_none_or(Value::is_null); + // A transform that leaves every guide where it is (a scale of a guide along its own line) + // changes no guide; with a copy, the guides are copied all the same. + let has_guides = with_guides && { + let d = &s.doc()?.doc; + let same = |g: &vectorcraft_doc::Guide| { + d.transformed_guide(g, xf) == Some(vectorcraft_doc::GuideTransform::Ruler { vertical: g.vertical, pos: g.pos }) + }; + editable_guides(s)?.iter().any(|g| is_translation || copy || !same(g)) + }; // A transform of ids that name no object, or an identity transform without a copy, moves // nothing: the document and its undo history stay as they are, and Transform Again repeats it. // With a copy, the reply lists the copies, and there are none. @@ -196,10 +226,12 @@ fn apply_transform_moving_guides( crate::cmd::patterncmds::move_tile_with_art(d, &targets, before); } } - if with_guides && (delta.x != 0.0 || delta.y != 0.0) { + if with_guides && is_translation && (delta.x != 0.0 || delta.y != 0.0) { for i in sel.guides.clone() { d.edit_ruler_guide(i, |g| *g = g.moved(delta)); } + } else if with_guides && !is_translation { + d.transform_ruler_guides(sel, xf); } Ok(targets) })? @@ -388,6 +420,10 @@ pub(super) fn rotate(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.rotate")?; check_switches(p, &["absolute"], "object.rotate")?; let ids = selected_roots_to_transform(s)?; + // A bounding box angle is that of objects; ruler guides selected alone have none. + if bool_or(p, "absolute", false) && ids.is_empty() { + return Err(bad("object.rotate", "absolute needs objects selected: ruler guides have no bounding box angle")); + } let o = origin_of(s, p, &ids)?; let mut angle = f64_or(p, "angle", 0.0); if bool_or(p, "absolute", false) { diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index b7df3dc467..8ac85b72fe 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -328,10 +328,21 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res Ok(on) } -/// [`transform_selected`] on the active document's selection, as one undo step `label`. +/// [`transform_selected`] on the active document's selection, as one undo step `label`. A +/// transform other than a move also transforms the selected ruler guides +/// ([`Document::transform_ruler_guides`]). pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { let sel = s.doc()?.selection.clone(); - s.edit(label, |doc, _| transform_selected(doc, &sel, xf, sc, interpolate)) + // As [`transform_selected`] tells a move apart, which moves the guides itself. + let c = xf.as_coeffs(); + let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9; + s.edit(label, |doc, live| { + transform_selected(doc, &sel, xf, sc, interpolate)?; + if !is_translation { + doc.transform_ruler_guides(live, xf); + } + Ok(()) + }) } /// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index a23fab2209..d922be19dd 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4535,6 +4535,115 @@ fn release_guides_turns_ruler_guides_into_paths() { assert_eq!(guides(&s).len(), 1); } +/// The direction of a two-anchor line, in degrees from the page's x axis (y down), from 0 to 180. +fn line_angle(ends: &[(f64, f64)]) -> f64 { + let [(x0, y0), (x1, y1)] = ends[..] else { panic!("not a line of two anchors") }; + (y1 - y0).atan2(x1 - x0).to_degrees().rem_euclid(180.0) +} + +/// A selected ruler guide rotates with `object.rotate` on its own, in one undo step, about the +/// middle of the line Release Guides makes of it. At 30° it becomes a selected guide path along +/// the turned line; Transform Again turns that path on, and undo gives the ruler guide back. +#[test] +fn rotating_a_ruler_guide_makes_an_angled_guide() { + let mut s = session(); + s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + let line = s.doc().unwrap().doc.guide_line(&s.doc().unwrap().doc.ruler_guides()[0]).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let n = undo_len(&s); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + assert_eq!(undo_len(&s), n + 1); + assert!(guides(&s).is_empty(), "the ruler guide is replaced"); + let [path] = selected(&s)[..] else { panic!("one guide path selected") }; + assert!(selected_guides(&s).is_empty()); + let (ends, guide) = line_ends(&s, path); + assert!(guide, "the path is a guide"); + let (mid, len) = (line.0.midpoint(line.1), line.0.distance(line.1)); + let (a, b) = (vectorcraft_geom::Point::new(ends[0].0, ends[0].1), vectorcraft_geom::Point::new(ends[1].0, ends[1].1)); + assert!(a.midpoint(b).distance(mid) < 1e-6 && close(a.distance(b), len), "it turns about its middle"); + // Counter-clockwise on the page: the downward vertical line now points 30° toward the right. + assert!(close(line_angle(&ends), 60.0), "{ends:?}"); + s.execute("object.transformAgain", &json!({})).unwrap(); + assert!(close(line_angle(&line_ends(&s, path).0), 30.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(guides(&s), vec![(true, 100.0)]); + assert!(s.doc().unwrap().doc.node(path).is_none()); +} + +/// A ruler guide turned by a quarter turn stays a ruler guide, horizontal now, through the same +/// middle; a turn of 0 changes nothing and records no undo step; a copy leaves the guide where it +/// was; and locked guides cannot be rotated. +#[test] +fn ruler_guides_turned_square_stay_ruler_guides() { + let mut s = session(); + s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + let mid = { + let d = &s.doc().unwrap().doc; + let (a, b) = d.guide_line(&d.ruler_guides()[0]).unwrap(); + a.midpoint(b) + }; + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let n = undo_len(&s); + s.execute("object.rotate", &json!({"angle": 0})).unwrap(); + assert_eq!((guides(&s), undo_len(&s)), (vec![(true, 100.0)], n)); + // Guides alone have no bounding box angle for `absolute` to set. + assert!(s.execute("object.rotate", &json!({"angle": 90, "absolute": true})).is_err()); + assert_eq!((guides(&s), undo_len(&s)), (vec![(true, 100.0)], n)); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let [(vertical, pos)] = guides(&s)[..] else { panic!("one ruler guide") }; + assert!(!vertical && close(pos, mid.y), "{pos}"); + assert_eq!((selected_guides(&s), undo_len(&s)), (vec![0], n + 1)); + // A copy at 45° adds a guide path and keeps the ruler guide. + s.execute("object.rotate", &json!({"angle": 45, "copy": true})).unwrap(); + assert_eq!(guides(&s).len(), 1); + let [path] = selected(&s)[..] else { panic!("the copy is selected") }; + assert!(line_ends(&s, path).1); + // Locked guides are deselected, and nothing is left to rotate. + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + assert!(s.execute("object.rotate", &json!({"angle": 30})).is_err()); + assert_eq!(guides(&s).len(), 1); +} + +/// Art and a ruler guide selected together rotate about the center of the art's box and the +/// guide's line together, and the angled guide survives a save and reopen as a guide path. +#[test] +fn a_ruler_guide_rotates_with_the_selected_art() { + let mut s = session(); + let a = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap(); + sel(&mut s, &[a]); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert_eq!((selected(&s), selected_guides(&s)), (vec![a], vec![0])); + let center = { + let d = &s.doc().unwrap().doc; + let (p, q) = d.guide_line(&d.ruler_guides()[0]).unwrap(); + Rect::from_points(p, q).union(bounds(&s, a)).center() + }; + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let [(vertical, pos)] = guides(&s)[..] else { panic!("one ruler guide") }; + assert!(vertical && close(pos, center.x + (50.0 - center.y)), "{pos}"); + let turned = bounds(&s, a); + assert!(close(turned.center().x, center.x + (150.0 - center.y)), "{turned:?}"); + s.execute("object.rotate", &json!({"angle": 20})).unwrap(); + let paths: Vec = selected(&s).into_iter().filter(|id| *id != a).collect(); + let [path] = paths[..] else { panic!("the guide path is selected with the art") }; + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let saved = back.node(path).unwrap(); + assert!(matches!(&saved.kind, NodeKind::Path { guide: true, path: p, .. } if *p == match &node(&s, path).kind { + NodeKind::Path { path, .. } => path.clone(), + _ => panic!("not a path"), + })); + // With anchors selected with Direct Selection, the selected guide turns with them. + s.execute("guide.add", &json!({"vertical": true, "pos": 600})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert!(!s.doc().unwrap().selection.anchors.is_empty()); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + assert!(!guides(&s)[0].0, "the vertical guide is horizontal now: {:?}", guides(&s)); +} + #[test] fn ruler_guides_and_lock() { let mut s = session(); diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index d0ff487af8..9483dea88f 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -128,6 +128,11 @@ pub struct TransformTool { snap: Option, } +/// The selected objects and ruler guides, which a reference point set by a click belongs to. +fn selected_ids(cx: &ToolContext) -> Vec { + cx.selection.objects.iter().chain(&cx.selection.guides).copied().collect() +} + fn about(o: Point, a: Affine) -> Affine { Affine::translate(o.to_vec2()) * a * Affine::translate(-o.to_vec2()) } @@ -170,10 +175,11 @@ impl TransformTool { } /// The effective reference point: the custom one if it belongs to the current selection, - /// otherwise the centre of its bounding box (rotated with rotated objects). + /// otherwise the centre of its bounding box (rotated with rotated objects). With ruler guides + /// selected, it is the center of the objects' box and the guides' lines together. pub fn reference_point(&self, cx: &ToolContext) -> Option { if let Some((p, ids)) = &self.origin - && *ids == cx.selection.objects + && *ids == selected_ids(cx) && !ids.is_empty() { return Some(*p); @@ -181,7 +187,29 @@ impl TransformTool { // Anchors selected with Direct Selection transform alone, about their own centre. vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()) .map(|b| b.center()) - .or_else(|| selection_box(cx).map(|b| b.center())) + .or_else(|| if self.guide_lines(cx).is_empty() { selection_box(cx).map(|b| b.center()) } else { self.bounds(cx).map(|b| b.center()) }) + } + + /// The selected ruler guides the tool transforms, as the boxes of the lines they stand for + /// ([`vectorcraft_doc::Document::guide_line`]): those that can be edited, with objects + /// selected, and with the Rotate tool also without. + fn guide_lines(&self, cx: &ToolContext) -> Vec { + if cx.selection.is_empty() && self.kind != TransformKind::Rotate { + return vec![]; + } + let d = cx.doc; + let guides = cx.selection.guides.iter().filter_map(|id| d.ruler_guide(*id)).filter(|g| d.guide_editable(g)); + guides.filter_map(|g| d.guide_line(&g)).map(|(a, b)| Rect::from_points(a, b)).collect() + } + + /// The bounding box of the selected objects and the lines of the guides the tool transforms. + fn bounds(&self, cx: &ToolContext) -> Option { + self.guide_lines(cx).into_iter().fold(selection_bounds(cx), |acc, r| Some(acc.map_or(r, |acc| acc.union(r)))) + } + + /// Is there anything selected for the tool to transform? + fn has_target(&self, cx: &ToolContext) -> bool { + !cx.selection.is_empty() || !self.guide_lines(cx).is_empty() } /// Transform for dragging from `start` to `p` about `o`; returns the matrix and a readout. @@ -331,7 +359,7 @@ impl Tool for TransformTool { let p = ev.pos; match ev.kind { PointerKind::Down => { - let Some(bounds) = selection_bounds(cx) else { return vec![] }; + let Some(bounds) = self.bounds(cx) else { return vec![] }; self.hover.clear(); let (pick, _) = snap_pick(cx, p); // Alt: decided on release. A click sets the point and opens the dialog; a drag @@ -422,7 +450,7 @@ impl Tool for TransformTool { } else { // A click sets the reference point; with Alt, it opens the dialog too. With the // Reflect tool, a plain click also sets the first point of an axis. - self.origin = Some((d.pick, cx.selection.objects.clone())); + self.origin = Some((d.pick, selected_ids(cx))); self.drop_axis(); if d.alt { vec![self.dialog(d.pick)] @@ -450,7 +478,7 @@ impl Tool for TransformTool { PointerKind::TripleClick => vec![], PointerKind::Move => { if self.drag.is_none() { - let (pick, hover) = if cx.selection.is_empty() { (p, vec![]) } else { snap_pick(cx, p) }; + let (pick, hover) = if self.has_target(cx) { snap_pick(cx, p) } else { (p, vec![]) }; self.hover = hover; self.axis_to = self.axis_first(cx).map(|_| pick); } @@ -525,7 +553,7 @@ impl Tool for TransformTool { } fn cursor(&self, cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { - if cx.selection.is_empty() { + if !self.has_target(cx) { return Cursor::NotAllowed; } match self.kind { @@ -657,6 +685,35 @@ mod tests { assert_eq!(up.last(), Some(&Action::Commit)); } + /// With only a ruler guide selected, the Rotate tool drags about the middle of the guide's + /// line, and Alt-click opens its dialog; the Scale tool still needs objects. + #[test] + fn the_rotate_tool_turns_a_selected_ruler_guide_alone() { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let g = d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 100.0)); + let mut s = Selection::default(); + s.guides.push(g); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = TransformTool::new(TransformKind::Rotate); + assert_eq!(t.reference_point(&cx), Some(Point::new(100.0, 250.0))); + assert_ne!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::NotAllowed); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 200.0, 250.0)).is_empty()); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 100.0, 350.0)); + assert_eq!(a[0], Action::Begin("Rotate".into())); + let m = matrix(&a[1]); + assert!((m * Point::new(100.0, 250.0)).distance(Point::new(100.0, 250.0)) < 1e-9); + assert!((m * Point::new(200.0, 250.0)).distance(Point::new(100.0, 350.0)) < 1e-9); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 100.0, 350.0)).last(), Some(&Action::Commit)); + t.pointer(&cx, &ev(PointerKind::Down, 50.0, 60.0).with_mods(alt())); + let up = t.pointer(&cx, &ev(PointerKind::Up, 50.0, 60.0).with_mods(alt())); + assert!(matches!(up.as_slice(), [Action::Dialog(id, _)] if id == "rotate"), "{up:?}"); + let mut scale = TransformTool::new(TransformKind::Scale); + assert_eq!(scale.reference_point(&cx), None); + assert!(scale.pointer(&cx, &ev(PointerKind::Down, 200.0, 250.0)).is_empty()); + assert!(scale.pointer(&cx, &ev(PointerKind::Drag, 100.0, 350.0)).is_empty()); + } + #[test] fn click_sets_reference_point_then_drag_uses_it() { let (d, id) = doc_with_rect(); diff --git a/docs/mcp.md b/docs/mcp.md index ab941e6eab..6660c393e8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3967,6 +3967,16 @@ Selection tool, a double-click with Cmd/Ctrl and Shift held releases the ruler g (`pointer_gesture` with a `doubleclick` event and `mods: {cmd: true, shift: true}`), unless guides are hidden or locked. +Selected ruler guides rotate with the Rotate tool, `object.rotate` (Object › Transform › Rotate…, with `copy` for +Copy) and `object.transformAgain`, also when no object is selected, in one undo step. `object.transform`, +`object.scale`, `object.reflect` and `object.shear` transform them too when objects are selected with them. Each +guide transforms as the line `view.guides.release` makes of it, and the default origin is the center of the selected +objects' box and those lines together. A guide that ends up vertical or horizontal stays a ruler guide at its new +place: a turn of 180° keeps it, and a turn of 90° makes a horizontal guide vertical. A guide at any other angle +becomes a guide path along its line, on the guide's layer, and is selected as one. Locked or hidden guides do not +transform, nor do guides when `ids` is given or `objects` is false. `object.rotate` with `absolute` and only ruler +guides selected is an error, as guides have no bounding box angle. + The Selection, Direct Selection and Group Selection tools pick a guide within the selection tolerance, over the art (an anchor on it comes first with Direct Selection), and drag the selected guides: `mods.alt` copies them, `mods.shift` snaps the dragged guide to the ruler's ticks, and otherwise it snaps to whole pixels, the grid or, with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c16b4c9567..f13a28d709 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -641,6 +641,7 @@ since 2026-10-01. - **Guide row highlight (#7344):** `guide_row_highlight_stays_selected_without_hover` in `crates/ui-egui/src/panels/layers/tests.rs` checks selected guide background after the pointer leaves, with unselected guide and ordinary row controls. Guide selection, dragging and deletion are unchanged. Scores and estimates unchanged. - **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). A drag or double-click on a ruler makes no guide while it is on (no preview, no undo step, a status message). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths`, `trim_view_makes_no_guide_from_the_rulers` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`. +- **Rotating ruler guides (part of #2418):** unlocked guides can be moved, modified and deleted ([user guide, Use guides](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=90)). A selected ruler guide rotates with the Rotate tool, Object › Transform › Rotate… (Copy included) and Transform Again, also with no object selected, in one undo step, and transforms with the selected objects under Scale, Reflect and Shear. Each guide transforms as the line Release Guides makes of it, about the center of that line and the objects' box together. By VectorCraft's own rule, a guide that ends up vertical or horizontal stays a ruler guide, and one at any other angle becomes a guide path along its line, which saves and opens as other guide paths do. `rotating_a_ruler_guide_makes_an_angled_guide`, `ruler_guides_turned_square_stay_ruler_guides`, `a_ruler_guide_rotates_with_the_selected_art` in `crates/engine/src/tests/menucmds.rs`; `the_rotate_tool_turns_a_selected_ruler_guide_alone` in `crates/tools/src/xform/transform.rs`. - **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. From b54121fde3e4f8fed4e462409aa154c933305321 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 11:17:26 -0800 Subject: [PATCH 082/101] .ai export: the distorted-image depth warnings name the depth they apply at Both .ai writers write a distorted image at the nearest parallelogram when it sits 8 deep in opacity masks, symbols, live objects or pattern tiles (the editing data) or in symbols and live objects (legacy .ai), and leave out art nested deeper. Their warnings said "more than 8 deep", which named images the writers never reach. Both now say "nested 8 deep", as docs/mcp.md does. --- crates/eps/src/ai_editing/writer.rs | 2 +- crates/eps/src/legacy_ai.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 8065b8cbb5..d95b1279c2 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -69,7 +69,7 @@ pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths tha pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; pub(super) const LIVE: &str = "repeats, placed documents, intertwines and distorted images are written as their art in the editing data for other apps"; -pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort more than 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps"; +pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort nested 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps"; pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps"; pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; pub(super) const ITEM_TRANSPARENCY: &str = diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index d1ae8ef9ab..8fbfcf3e83 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -130,7 +130,7 @@ const STROKES: &str = const IMAGE_ALPHA: &str = "transparent image pixels are written over white"; const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents, intertwines and distorted images are written as their art"; const DEEP_DISTORTED: &str = - "images changed by Perspective Distort or Free Distort more than 8 deep in symbols and live objects are written as the nearest parallelogram"; + "images changed by Perspective Distort or Free Distort nested 8 deep in symbols and live objects are written as the nearest parallelogram"; const GRAPHS: &str = "graphs are written as their art, without their data or settings"; /// The warning for an image left out because it can't be decoded: the note raster exports give /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). From 36d3cd0a155d0d2f0a3bd9bbc1602b4cb0e79c65 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 11:38:03 -0800 Subject: [PATCH 083/101] Layers: Shift-click in the selection column selects the art of a range of rows After a selection square is clicked, Shift-clicking another selects the art of every row listed from the last square clicked to this one, down or up and across sublayers and groups. Shift+Ctrl/Cmd-click adds that art to the selection. Hidden and locked rows and art outside the isolated group are left out, and a range does not move where the next Shift-click starts. Before any square is clicked, Shift-click still adds one row's art or takes it out. Ctrl/Cmd-click on a square now does the same; it used to select the row's art alone, as a plain click does. The panel menu's Select Art of Highlighted Rows selects the art of the highlighted rows by the same rules. - layer.selectAll takes {range: [id...], add?}, gathered with Selection::target_range as the target circles' ranges are. - layer.selectHighlighted {add?} is new. Neither is an undo step, and the highlighted rows stay. - Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/layer.rs | 61 +++++++++++- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests/layers.rs | 99 +++++++++++++++++++ crates/ui-egui/src/panels/layers.rs | 16 ++- crates/ui-egui/src/panels/layers/cells.rs | 25 +++-- crates/ui-egui/src/panels/layers/controls.rs | 1 + crates/ui-egui/src/panels/layers/rows.rs | 34 +++++-- crates/ui-egui/src/panels/layers/tests.rs | 61 +++++++++++- docs/mcp.md | 7 +- docs/target-app-parity.md | 1 + 10 files changed, 284 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 73c92877e9..7d8213c3d2 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -102,10 +102,19 @@ pub fn specs() -> Vec { "Select Art", [], None, - "{id, add?: bool} the Layers panel's selection column: select the visible, unlocked art of a layer (its sublayers' too), or the object itself; `add` (Shift-click) adds it to the selection, or removes it when it is all selected already → {selected: [..]}", + "{id, add?: bool} or {range: [id…], add?: bool} the Layers panel's selection column: select the visible, unlocked art of a layer (its sublayers' too), or the object itself; `add` (Shift-click with no square clicked before, or Ctrl/Cmd-click) adds it to the selection, or removes it when it is all selected already. `range` (Shift-click, the rows from the last square clicked to this one): the art of every listed row that is visible, unlocked and inside the isolated art is selected, or added to the selection with `add` (Shift+Ctrl/Cmd-click); a range with no such row is an error. Not an undo step; the highlighted rows stay → {selected: [..]} (with `range`: {range, selected})", has_doc, select_art ), + cmd!( + "layer.selectHighlighted", + "Select Art of Highlighted Rows", + [], + None, + "{add?: bool} select the art of the Layers panel's highlighted rows, as clicking each row's selection square does: a layer's or sublayer's visible, unlocked art (its sublayers' too), or the group or object itself; hidden and locked rows and rows outside the isolated art are left out. `add` adds the art to the selection. No highlighted row, or none that is visible and unlocked, is an error. Not an undo step; the highlighted rows stay → {rows, selected: [..]}", + has_doc, + select_highlighted + ), cmd!( "layer.move", "Move Rows", @@ -753,6 +762,11 @@ fn in_isolation(doc: &Document, isolation: Option, id: NodeId) -> bool { /// The selection column: select a row's art. fn select_art(s: &mut Session, p: &Value) -> Result { const C: &str = "layer.selectAll"; + if let Some(ids) = ids_param(p, "range", C)? { + let add = switch_or(p, "add", false, C)?; + let (range, selected) = select_rows_art(s, ids, add, C, "no row in the range is visible, unlocked and inside the isolated art")?; + return Ok(json!({ "range": range, "selected": selected })); + } let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; let add = switch_or(p, "add", false, C)?; let st = s.doc()?; @@ -789,6 +803,51 @@ fn select_art(s: &mut Session, p: &Value) -> Result { Ok(json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::>() })) } +/// Select Art of Highlighted Rows: the art of the highlighted rows, as their selection squares +/// select it. +fn select_highlighted(s: &mut Session, p: &Value) -> Result { + const C: &str = "layer.selectHighlighted"; + let add = switch_or(p, "add", false, C)?; + let rows = s.doc()?.highlighted_rows(); + if rows.is_empty() { + return Err(bad(C, "no row is highlighted")); + } + let (rows, selected) = select_rows_art(s, rows, add, C, "no highlighted row is visible, unlocked and inside the isolated art")?; + Ok(json!({ "rows": rows, "selected": selected })) +} + +/// Selects the art of the Layers panel rows `ids` (at most [`MAX_ROWS`]), or adds it to the +/// selection with `add`: each row that is visible, unlocked and inside the isolated art (or is the +/// isolated layer) gives what its selection square selects, a layer's visible, unlocked art (its +/// sublayers' too) or the group or object itself, as [`Selection::target_range`] gathers it for a +/// range of target circles. Nothing is targeted and the highlighted rows stay. Without such a row it +/// is the error `none`. Returns the rows used and the selected objects. +/// +/// [`Selection::target_range`]: vectorcraft_doc::Selection::target_range +fn select_rows_art(s: &mut Session, mut ids: Vec, add: bool, c: &str, none: &str) -> Result<(Vec, Vec)> { + ids.truncate(MAX_ROWS); + let rows = { + let st = s.doc()?; + // Measures the locked artboards once for every row, not once per row. + let editable = st.doc.editable(); + ids.retain(|id| { + st.doc.node(*id).is_some_and(|n| { + let isolated_layer = st.isolation == Some(*id) && n.is_layer(); + !n.is_ruler_guide() && editable(*id) && (isolated_layer || in_isolation(&st.doc, st.isolation, *id)) + }) + }); + st.layer_rows.clone() + }; + if ids.is_empty() { + return Err(bad(c, none)); + } + s.select(|d, sel| sel.target_range(d, &ids, add))?; + let st = s.doc_mut()?; + // The selection column leaves the highlighted rows as they are. + st.layer_rows = rows; + Ok((ids.iter().map(|i| i.0).collect(), st.selection.objects.iter().map(|i| i.0).collect())) +} + #[derive(Clone, Copy, PartialEq, Eq)] enum Place { Above, diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index ec7d3ac989..abc11515e7 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -243,6 +243,7 @@ pub(super) const ALLOWED: &[&str] = &[ "layer.releaseToLayersBuild", "layer.reverse", "layer.selectAll", + "layer.selectHighlighted", "layer.setCurrent", "layer.setProps", "layer.showAll", diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index 22edfec458..f606e11a75 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -390,6 +390,105 @@ fn the_selection_column_selects_a_rows_art_and_shift_adds_or_removes_it() { assert_eq!(ids_sel(&run(&mut s, "layer.target", json!({"id": layer.0}))), vec![c, a, g]); } +/// The selection as a sorted list. +fn sorted_sel(s: &Session) -> Vec { + let mut ids = s.doc().unwrap().selection.objects.clone(); + ids.sort(); + ids +} + +/// The art the selection squares of `rows` select, each clicked alone, put together and sorted. +/// Leaves nothing selected. +fn each_rows_art(s: &mut Session, rows: &[NodeId]) -> Vec { + run(s, "select.none", json!({})); + let mut art = vec![]; + for row in rows { + art.extend(ids_sel(&run(s, "layer.selectAll", json!({"id": row.0})))); + } + art.sort(); + art.dedup(); + run(s, "select.none", json!({})); + art +} + +/// `layer.selectAll` with `range` (a Shift-click from the last selection square clicked) selects +/// the art of every row in the range, across the sublayer and the group, as each row's square +/// selects it; hidden and locked rows are left out, and `add` adds to the selection. The +/// highlighted rows stay, and no undo step is recorded. +#[test] +fn the_selection_column_selects_the_art_of_a_range_of_rows() { + let mut s = session(); + let (layer, sub, a, g, b, c) = tree(&mut s); + run(&mut s, "layer.setCurrent", json!({"id": sub.0})); + let undo = undos(&s); + // The rows top down: the layer, the sublayer, the group, its rectangle, then a and c. + let range = [g, b, a, c]; + let want = each_rows_art(&mut s, &range); + let reply = run(&mut s, "layer.selectAll", json!({"range": range.map(|r| r.0)})); + assert_eq!(sorted_sel(&s), want, "the group, its member's row, the sublayer's rectangle and the top layer's rectangle"); + assert!(want.contains(&a) && want.contains(&c), "{want:?}"); + assert_eq!(ids_sel(&reply).len(), s.doc().unwrap().selection.objects.len()); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub], "the highlighted row stays"); + assert_eq!(undos(&s), undo, "a selection change is not an undo step"); + // A range given bottom up selects the same art. + run(&mut s, "layer.selectAll", json!({"range": [c.0, a.0, b.0, g.0]})); + assert_eq!(sorted_sel(&s), want); + // `add` keeps what was selected. + run(&mut s, "select.set", json!({"ids": [c.0]})); + run(&mut s, "layer.selectAll", json!({"range": [a.0], "add": true})); + let got = sorted_sel(&s); + assert!(got.len() == 2 && got.contains(&a) && got.contains(&c), "{got:?}"); + // A range holding a layer row takes that layer's art, its sublayer's too. + run(&mut s, "layer.selectAll", json!({"range": [layer.0, sub.0]})); + assert_eq!(sorted_sel(&s), each_rows_art(&mut s, &[layer])); + // Locked and hidden rows are left out. + run(&mut s, "layer.setProps", json!({"ids": [a.0], "locked": true})); + run(&mut s, "layer.setProps", json!({"ids": [c.0], "visible": false})); + run(&mut s, "layer.selectAll", json!({"range": range.map(|r| r.0)})); + let got = sorted_sel(&s); + assert!(!got.is_empty() && !got.contains(&a) && !got.contains(&c), "{got:?}"); + // A range of only hidden and locked rows changes nothing and says why. + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(s.execute("layer.selectAll", &json!({"range": [a.0, c.0]})).is_err()); + assert_eq!(sorted_sel(&s), vec![g]); +} + +/// `layer.selectHighlighted` selects the art of the highlighted rows, as their selection squares +/// do, leaving out hidden and locked rows; `add` adds it. The highlighted rows stay, no undo step is +/// recorded, and with no row highlighted it is an error. +#[test] +fn select_highlighted_selects_the_art_of_the_highlighted_rows() { + let mut s = session(); + let (_, _, a, g, _, c) = tree(&mut s); + let want = each_rows_art(&mut s, &[g, c]); + run(&mut s, "layer.highlight", json!({"ids": [g.0, c.0], "mode": "set"})); + let rows = s.doc().unwrap().highlighted_rows(); + let undo = undos(&s); + run(&mut s, "layer.selectHighlighted", json!({})); + assert_eq!(sorted_sel(&s), want); + assert_eq!(s.doc().unwrap().highlighted_rows(), rows, "the highlighted rows stay"); + assert_eq!(undos(&s), undo, "a selection change is not an undo step"); + // `add` keeps what was selected. + run(&mut s, "select.set", json!({"ids": [a.0]})); + // Selecting art in another layer let go of the highlighted rows. + run(&mut s, "layer.highlight", json!({"ids": [g.0, c.0], "mode": "set"})); + run(&mut s, "layer.selectHighlighted", json!({"add": true})); + let mut with_a = want.clone(); + with_a.push(a); + with_a.sort(); + assert_eq!(sorted_sel(&s), with_a); + // A hidden row is left out. + run(&mut s, "layer.setProps", json!({"ids": [c.0], "visible": false})); + run(&mut s, "layer.highlight", json!({"ids": [g.0, c.0], "mode": "set"})); + run(&mut s, "layer.selectHighlighted", json!({})); + assert!(!sorted_sel(&s).contains(&c)); + // With no row highlighted, nothing changes. + run(&mut s, "layer.highlight", json!({"ids": [], "mode": "set"})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + assert!(s.execute("layer.selectHighlighted", &json!({})).is_err()); + assert_eq!(sorted_sel(&s), vec![a]); +} + /// The rows of [`column_start`]: [`tree`]'s, plus a rectangle `o` on a second layer and an empty /// third layer `e`. #[derive(Clone, Copy)] diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 59582a80c4..67d534c178 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -179,6 +179,8 @@ pub struct LayersUi { pub focused: bool, /// The target circle clicked last, with its document's `uid`: where a Shift-click on another circle starts. pub target_anchor: Option<(u64, NodeId)>, + /// The selection square clicked last, with its document's `uid`: where a Shift-click on another square starts. + pub art_anchor: Option<(u64, NodeId)>, /// The active document's rows with the [`LayerRows::key`] they were listed at. rows: Option<(u64, Tracked)>, } @@ -188,7 +190,7 @@ impl Default for LayersUi { fn default() -> Self { let mut filter = LayerFilter::default(); filter.by = FilterBy::Objects; - Self { filter, rename: None, focused: false, target_anchor: None, rows: None } + Self { filter, rename: None, focused: false, target_anchor: None, art_anchor: None, rows: None } } } @@ -214,6 +216,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut footer = Vec::new(); let mut picks = Vec::new(); let mut target_click = None; + let mut art_click = None; let thumbnails = thumbs::layer_thumbnails(ui.ctx(), uid); // A drag's previews keep the shown pictures; the rows render once it ends. thumbnails.hold(app.session.active().is_some_and(|st| st.interaction.is_some()) || app.session.tool_busy()); @@ -232,7 +235,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .blend_rows(false) .deletable(true) .takes_drop::(cells::accepts_art(&tree)) - .trailing(|id, info| cells::build(&tree, id, info), |id, shown| cells::output(&mut picks, &mut target_click, id, shown)) + .trailing(|id, info| cells::build(&tree, id, info), |id, shown| cells::output(&mut picks, &mut target_click, &mut art_click, id, shown)) .row_menu(|target| controls::row_menu(&tree, target)) .footer(|ui| controls::footer(&tree, ui, &mut footer)) .document(uid); @@ -246,13 +249,20 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // A Shift-click starts at the last circle clicked in this document, else at the targeted row. let anchor = app.ui.layers_ui.target_anchor.filter(|(doc, _)| *doc == uid).map(|(_, id)| id); let target = target_click.map(|(id, mods)| (id, rows::target_click(&tree, &filter, anchor, id, mods))); + // A Shift-click on a selection square starts at the last square clicked in this document. + let art_anchor = app.ui.layers_ui.art_anchor.filter(|(doc, _)| *doc == uid).map(|(_, id)| id); + let art = art_click.map(|(id, mods)| (id, rows::art_click(&tree, &filter, art_anchor, id, mods))); app.ui.layers_ui.filter = filter; if let Some((id, (_, true))) = &target { app.ui.layers_ui.target_anchor = Some((uid, *id)); } + if let Some((id, (_, true))) = &art { + app.ui.layers_ui.art_anchor = Some((uid, *id)); + } app.ui.layers_ui.focused = output.focused; rows::apply(app, output.events); - for (c, p) in footer.into_iter().chain(picks).chain(target.map(|(_, (command, _))| command)) { + let clicks = art.into_iter().chain(target).map(|(_, (command, _))| command); + for (c, p) in footer.into_iter().chain(picks).chain(clicks) { app.run(&c, p).ok(); } // The panel's own commands reveal nothing for the selection they made: Locate Selected Objects diff --git a/crates/ui-egui/src/panels/layers/cells.rs b/crates/ui-egui/src/panels/layers/cells.rs index c557023bcf..1b9bdadd43 100644 --- a/crates/ui-egui/src/panels/layers/cells.rs +++ b/crates/ui-egui/src/panels/layers/cells.rs @@ -4,7 +4,8 @@ //! ([`rows::target_click`](super::rows::target_click)); dragging it carries the appearance //! ([`PanelDrag::Appearance`]) onto another row's circle (Alt copies it) or the trash. A circle //! lights up while another row's appearance is held over it. -//! - The selection square selects the row's art (Shift adds or removes); a row whose art is +//! - The selection square selects the row's art, with the modifier rules of +//! [`rows::art_click`](super::rows::art_click) (Shift selects a range of rows); a row whose art is //! selected shows it in its layer's colour, a row holding selected art a small one, and dragging //! either onto another row moves the selected art there (Alt copies it). //! @@ -42,8 +43,9 @@ pub(super) struct ArtDrag(pub(super) Vec); enum CellPick { /// The circle was clicked with these modifiers. Target(Mods), - /// The square was clicked: select the row's art (Shift adds or removes). - SelectArt { add: bool }, + /// The square was clicked with these modifiers: select the row's art, by the rules of + /// [`rows::art_click`](super::rows::art_click). + SelectArt(Mods), /// Another row's appearance was dropped on the circle (Alt copies it). TakeAppearance { source: NodeId, copy: bool }, } @@ -248,7 +250,7 @@ impl Component for SelectionSquare { return; } if let Some(activation) = cx.activation() { - self.pick = Some(CellPick::SelectArt { add: activation.mods.shift }); + self.pick = Some(CellPick::SelectArt(activation.mods)); } if (self.selected || self.holds) && !self.art.is_empty() && primary_drag_start(cx) { cx.start_drag(ArtDrag(self.art.clone()), DragPreview::None); @@ -382,14 +384,21 @@ pub(super) fn build(tree: &DocLayers<'_>, row: &RowId, info: &LayerInfo) -> Cell } } -/// What row `row`'s cells reported: the commands `layer.selectAll` and `appearance.transfer` on the row's node, added to -/// `out`, and a click on its target circle with its modifiers, which the panel resolves once it knows its rows. -pub(super) fn output(out: &mut Vec<(String, Value)>, target: &mut Option<(NodeId, Mods)>, row: &RowId, shown: CellsOutput) { +/// What row `row`'s cells reported: the command `appearance.transfer` on the row's node, added to `out`, and a click on +/// its target circle (`target`) or its selection square (`art`) with its modifiers, which the panel resolves once it +/// knows its rows. +pub(super) fn output( + out: &mut Vec<(String, Value)>, + target: &mut Option<(NodeId, Mods)>, + art: &mut Option<(NodeId, Mods)>, + row: &RowId, + shown: CellsOutput, +) { let RowId::Node(id) = *row else { return }; for pick in shown.picks { match pick { CellPick::Target(mods) => *target = Some((id, mods)), - CellPick::SelectArt { add } => out.push(("layer.selectAll".to_string(), json!({"id": id.0, "add": add}))), + CellPick::SelectArt(mods) => *art = Some((id, mods)), CellPick::TakeAppearance { source, copy } => { out.push(("appearance.transfer".to_string(), json!({"source": source.0, "target": id.0, "copy": copy}))); } diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index 3ac7f25522..b337508c90 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -121,6 +121,7 @@ fn items(app: &VectorcraftApp) -> Vec { } else { command("layer.locate", json!({}), tl!("Locate Object"), has_sel) }, + command("layer.selectHighlighted", json!({}), tl!("Select Art of Highlighted Rows"), !rows.is_empty()), save_selection(app), Item::Separator, command("layer.merge", json!({}), tl!("Merge Selected"), rows.len() >= 2), diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 20c81d8f91..6cf12c1a95 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -156,20 +156,38 @@ pub(super) fn full_layers(doc: &Document, sel: &HashSet) -> HashSet, filter: &LayerFilter, anchor: Option, id: NodeId, mods: Mods) -> ((String, Value), bool) { if mods.shift - && let Some(start) = anchor.or(tree.state().selection.target) + && let Some(range) = anchor.or(tree.state().selection.target).and_then(|start| listed_range(tree, filter, start, id)) { - let order = listed_nodes(tree, filter); - let at = |k: NodeId| order.iter().position(|r| *r == k); - if let (Some(i), Some(j)) = (at(start), at(id)) { - let range: Vec = order.get(i.min(j)..=i.max(j)).unwrap_or_default().iter().map(|r| r.0).collect(); - let params = if mods.cmd { json!({"range": range, "add": true}) } else { json!({"range": range}) }; - return (("layer.target".into(), params), false); - } + let params = if mods.cmd { json!({"range": range, "add": true}) } else { json!({"range": range}) }; + return (("layer.target".into(), params), false); } let params = if mods.cmd { json!({"id": id.0, "add": true}) } else { json!({"id": id.0}) }; (("layer.target".into(), params), true) } +/// The `layer.selectAll` of a click with `mods` on the selection square of `id`. A plain click selects the row's art. +/// Shift selects the art of every row `filter` lists from `anchor` (the last square clicked) to it, and Shift+Ctrl/Cmd +/// adds that art to the selection. With no anchor listed, Shift adds the row's art or removes it when it is all +/// selected, and so does Ctrl/Cmd. With it, whether the click moves the anchor to `id`: every click but a Shift range. +pub(super) fn art_click(tree: &DocLayers<'_>, filter: &LayerFilter, anchor: Option, id: NodeId, mods: Mods) -> ((String, Value), bool) { + if mods.shift + && let Some(range) = anchor.and_then(|start| listed_range(tree, filter, start, id)) + { + let params = if mods.cmd { json!({"range": range, "add": true}) } else { json!({"range": range}) }; + return (("layer.selectAll".into(), params), false); + } + let params = if mods.shift || mods.cmd { json!({"id": id.0, "add": true}) } else { json!({"id": id.0}) }; + (("layer.selectAll".into(), params), true) +} + +/// The rows `filter` lists from `start` to `end`, both included, top-down; `None` when either is not listed. +fn listed_range(tree: &DocLayers<'_>, filter: &LayerFilter, start: NodeId, end: NodeId) -> Option> { + let order = listed_nodes(tree, filter); + let at = |k: NodeId| order.iter().position(|r| *r == k); + let (i, j) = (at(start)?, at(end)?); + Some(order.get(i.min(j)..=i.max(j)).unwrap_or_default().iter().map(|r| r.0).collect()) +} + /// The layer, group and object rows the panel over `tree` lists under `filter`, top-down: the children of open rows, /// and while the filter is on every row it keeps and every row holding one, open or not. fn listed_nodes(tree: &DocLayers<'_>, filter: &LayerFilter) -> Vec { diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 172bf59860..32c8add30f 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -562,6 +562,65 @@ fn the_target_circle_anchor_does_not_carry_over_to_another_document() { assert_eq!(targeted(&panel.app()), (Some(b2), vec![b2])); } +/// Shift-clicking a selection square selects the art of every row from the last square clicked to +/// it, down or up and across a sublayer and a group, leaving out locked and hidden rows, and +/// Shift+Ctrl/Cmd adds that art. A plain click selects one row's art, and Ctrl/Cmd adds it or takes +/// it out again. +#[test] +fn shift_clicking_a_selection_square_selects_the_art_of_a_range_of_rows() { + use crate::tests::panel_harness::Panel; + use egui::Modifiers; + let (mut app, [_, _, g, b, a, c]) = nested(); + for (id, name) in [(g, "G"), (b, "B"), (a, "A"), (c, "C")] { + name_row(&mut app, id, name); + } + // Rows top down: the layer, the sublayer, G, B (in G), A, then C on the layer itself. + let mut panel = Panel::new(app, show); + panel.click_with("Select art of A", Modifiers::NONE); + assert_eq!(targeted(&panel.app()), (None, vec![a]), "a plain click selects one row's art"); + panel.click_with("Select art of C", Modifiers::SHIFT); + let (_, sel) = targeted(&panel.app()); + assert!(sel.len() == 2 && sel.contains(&a) && sel.contains(&c), "a range down, out of the sublayer: {sel:?}"); + // A range starts at the last square clicked, not at the end of the last range. + panel.click_with("Select art of G", Modifiers::SHIFT); + let (_, sel) = targeted(&panel.app()); + assert!(sel.contains(&g) && sel.contains(&a) && !sel.contains(&c), "a range up, across the group: {sel:?}"); + // Shift+Ctrl/Cmd adds a range: from A down to C. + panel.click_with("Select art of C", Modifiers::SHIFT | Modifiers::COMMAND); + let (_, sel) = targeted(&panel.app()); + assert!(sel.contains(&g) && sel.contains(&a) && sel.contains(&c), "{sel:?}"); + // Ctrl/Cmd takes one row's art out again. + panel.click_with("Select art of C", Modifiers::COMMAND); + let (_, sel) = targeted(&panel.app()); + assert!(sel.contains(&g) && !sel.contains(&c), "{sel:?}"); + // Locked and hidden rows in a range stay unselected. + panel.app().session.execute("layer.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + panel.app().session.execute("layer.setProps", &json!({"ids": [b.0], "visible": false})).unwrap(); + panel.click_with("Select art of G", Modifiers::NONE); + panel.click_with("Select art of C", Modifiers::SHIFT); + let (_, sel) = targeted(&panel.app()); + assert!(sel.contains(&g) && sel.contains(&c) && !sel.contains(&a) && !sel.contains(&b), "{sel:?}"); +} + +/// With no selection square clicked yet, Shift-clicking one adds its row's art, or takes it out +/// when it is all selected, and that square becomes where the next Shift-click starts. +#[test] +fn shift_clicking_the_first_selection_square_adds_or_removes_one_row() { + use crate::tests::panel_harness::Panel; + use egui::Modifiers; + let (mut app, [_, _, g, _, a, c]) = nested(); + for (id, name) in [(g, "G"), (a, "A"), (c, "C")] { + name_row(&mut app, id, name); + } + app.session.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap(); + let mut panel = Panel::new(app, show); + panel.click_with("Select art of A", Modifiers::SHIFT); + assert_eq!(targeted(&panel.app()), (None, vec![c]), "a selected row's art is taken out"); + panel.click_with("Select art of C", Modifiers::SHIFT); + let (_, sel) = targeted(&panel.app()); + assert!(sel.contains(&a) && sel.contains(&c) && !sel.contains(&g), "the range from A to C: {sel:?}"); +} + /// The rows among `rows` whose selection square is full-sized, then those whose square is the /// small one, in the order given. fn squares(app: &VectorcraftApp, rows: &[NodeId]) -> (Vec, Vec) { @@ -598,7 +657,7 @@ fn a_layer_with_all_its_art_selected_shows_the_full_square() { assert_eq!(squares(&panel.app(), &rows), (vec![sub, g, a], vec![layer]), "the sublayer, its group and rectangle full, the layer small"); panel.click_with("Select art of Top", Modifiers::NONE); assert_eq!(squares(&panel.app(), &rows), (vec![layer, sub, g, a, c], vec![]), "the layer and the sublayer full, with each row's art"); - panel.click_with("Select art of A", Modifiers::SHIFT); + panel.click_with("Select art of A", Modifiers::COMMAND); assert_eq!(squares(&panel.app(), &rows), (vec![g, c], vec![layer, sub]), "one rectangle let go: the layer and the sublayer small again"); // Locked art cannot be selected, so it does not keep the layer's square small. panel.app().session.execute("layer.setProps", &json!({"ids": [c.0], "locked": true})).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 5f3af5e49f..cfd411823a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6506,7 +6506,12 @@ and `layerRows`, the rows highlighted in the panel. set|add|toggle}` is Shift-click (a range) and Ctrl/Cmd-click (toggle). Selecting art makes its layer current. Without `ids`, the panel commands below act on the highlighted rows, else on the current layer. - **Selection column**: `layer.selectAll {id, add?}` selects a row's visible, unlocked art (a layer's sublayers' - too); `add` (Shift) adds it, or removes it when it's all selected. Alt-click on a layer's or sublayer's name runs + too); `add` (Ctrl/Cmd, or Shift before any square was clicked) adds it, or removes it when it's all selected. + `layer.selectAll {range: [id…], add?}` is a Shift-click on a square after another was clicked: the art of every + row listed from the last square clicked to this one, across sublayers and groups, leaving out hidden and locked + rows; Shift+Ctrl/Cmd adds it to the selection. A range does not move where the next Shift-click starts. + `layer.selectHighlighted {add?}` (the panel menu's Select Art of Highlighted Rows) selects the art of the highlighted rows by the + same rules. Neither is an undo step, and the highlighted rows stay. Alt-click on a layer's or sublayer's name runs `layer.selectAll {id}` and then `layer.setCurrent {id}`. - **Eye and lock**: `layer.setProps {ids?, visible?, locked?, name?}` for any rows, plus Layer Options for layers: `template` (also locks the layer and dims its images to 50% unless given), `printable`, `preview` (off: the layer diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2b8a108a5f..49ee00286b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -773,6 +773,7 @@ since 2026-10-01. - **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`. - **Shift-click in the Layers panel's selection column on a large layer:** `layer.selectAll {id, add: true}` checks whether the row's art is all selected with a set of the selected objects, and removes or adds that art in one pass instead of once per object. The resulting selection, its order, the reply and the highlighted rows are the same as before. On a layer of 50,000 objects the whole command took a median of 733 ms before and 6.9 ms after when all of the layer's art was selected, and 369 ms before and 24 ms after when every other object was, in 7 runs each, wall clock on Linux while other builds were running (`cargo run --release -p vectorcraft-engine --example layer_select_bench`). Regression test: `a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id` in `crates/engine/src/tests/layers.rs`. - **Ctrl/Cmd-click and Shift-click on Layers panel target circles (#8639):** the target circles follow the same modifier rules as the row names, as the help page describes for selecting objects in the Layers panel: Shift for adjacent objects, Ctrl or Command for non-adjacent ones ([Move objects to different layers](https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/move-objects-to-different-layers.html)). Ctrl/Cmd-click adds the item (a layer: its art) to the selection or takes it out, which Shift-click did before (#913); Shift-click selects the art of every row from the last circle clicked (else the targeted row) to this one, and Shift+Ctrl/Cmd-click adds it (`layer.target {range, add?}`). Hidden or locked art and art outside the isolated group in the range is left out, and nothing stays targeted. Regression tests: `clicking_a_target_circle_targets_the_layer` and `shift_clicking_a_target_circle_selects_a_range_of_rows` in `crates/ui-egui/src/panels/layers/tests.rs`. +- **Shift-click in the Layers panel's selection column selects the art of a range of rows:** after a selection square is clicked, Shift-clicking another selects the art of every row listed from the last square clicked to this one, down or up and across sublayers and groups, and Shift+Ctrl/Cmd-click adds that art to the selection (`layer.selectAll {range, add?}`). Hidden and locked rows and art outside the isolated group are left out, and a range does not move where the next Shift-click starts. Ctrl/Cmd-click adds one row's art or takes it out, and so does Shift-click before any square was clicked. The panel menu's Select Art of Highlighted Rows (`layer.selectHighlighted`) selects the art of the highlighted rows by the same rules. These are VectorCraft's own rules. Regression tests: `shift_clicking_a_selection_square_selects_the_art_of_a_range_of_rows` and `shift_clicking_the_first_selection_square_adds_or_removes_one_row` in `crates/ui-egui/src/panels/layers/tests.rs`, `the_selection_column_selects_the_art_of_a_range_of_rows` and `select_highlighted_selects_the_art_of_the_highlighted_rows` in `crates/engine/src/tests/layers.rs`. - **Layers added to the selection from their target circles show as targeted (#8646):** with several items picked from their circles (nothing targeted), a layer or sublayer's circle shows its inner ring while all of its visible, unlocked art is selected, as an object's circle does while the object is selected. A layer is never selected itself, only its art, so its circle used to keep a single ring. Regression test: `a_layer_added_from_its_target_circle_shows_as_targeted` in `crates/ui-egui/src/panels/layers/tests.rs`. - **A targeted item with an appearance of its own shows both marks (#8711):** its target circle keeps the inner ring of a targeted item, with the appearance dot drawn smaller inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) do. The dot used to cover the ring. Regression test: `a_targeted_circle_with_an_appearance_shows_both_ring_and_dot` in `crates/ui-egui/src/panels/layers/tests.rs`. - **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. From 9567d7349ac7776d2737bc9ee75b6bc3c71eafbc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 12:21:49 -0800 Subject: [PATCH 084/101] Fill Area: clipped art bounds areas only where its mask shows it Fill Area used the full outline of art inside a clipping group, so a click in the part a mask hides still found an area, and the new path above the clipping group showed art the mask hid. Now each clipped path is cut to every mask around it before it bounds areas, nested clipping groups and clipped layers included: a filled path keeps its overlap with the mask, and the outline of an unfilled path and open paths keep only their pieces inside it. A mask that clips to nothing hides what it clips. The new path still goes above the clipping group. Follows #8001. --- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/tests/fill_area.rs | 61 ++++++++++++++++++++++++++ crates/tools/src/builder/fill_area.rs | 63 ++++++++++++++++++++++++++- docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 5 files changed, 128 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 692545d828..5ab9da102c 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Fill Area", [], None, - "{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, only the paths of the listed objects that are in it), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}", + "{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, only the paths of the listed objects that are in it), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}", has_doc, sb_copy_region ), diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index 6625c7e150..6703d4f928 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -189,6 +189,67 @@ fn fill_area_stacks_above_the_group_that_holds_the_paths() { assert_eq!(members(&s, clip), before); } +/// `ids` clipped by a new rectangle mask in front of them, as the clipping group's id. +fn clip_by(s: &mut Session, ids: &[NodeId], x: f64, y: f64, w: f64, h: f64) -> NodeId { + let mask = rect(s, x, y, w, h); + let ids: Vec = ids.iter().map(|i| i.0).chain([mask.0]).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()) +} + +/// Clipped art bounds areas only where its clipping mask shows it: a click in the part the mask +/// hides finds no area and changes nothing, and a click in the part it shows fills only that part. +#[test] +fn fill_area_takes_clipped_art_only_where_its_mask_shows_it() { + let mut s = session(); + let square = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + let clip = clip_by(&mut s, &[square], 0.0, -10.0, 100.0, 120.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [125, 50]})).is_err()); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [75, 50]})).unwrap(); + assert!((area(&s, id_of(&r)) - 5000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + assert_eq!(stack(&s), vec![clip, id_of(&r)], "the new path goes above the clipping group"); + + // Without a fill only the outline shows, and the mask's edge does not close the part it shows. + let mut s = session(); + let square = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + clip_by(&mut s, &[square], 0.0, -10.0, 100.0, 120.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [75, 50]})).is_err()); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); + + // Lines the mask cuts bound no area where the parts that close it are hidden. + let mut s = session(); + let lines = triangle(&mut s); + clip_by(&mut s, &lines, -20.0, -20.0, 60.0, 140.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [30, 75]})).is_err()); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); +} + +/// In a clipping group inside another, clipped art shows only where both masks show it. +#[test] +fn fill_area_takes_art_in_nested_clipping_groups_only_where_every_mask_shows_it() { + let mut s = session(); + let square = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + let inner = clip_by(&mut s, &[square], 0.0, -10.0, 100.0, 120.0); + let outer = clip_by(&mut s, &[inner], 0.0, -20.0, 80.0, 140.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + for p in [[125, 50], [90, 50]] { + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": p})).is_err(), "{p:?}"); + } + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [65, 50]})).unwrap(); + assert!((area(&s, id_of(&r)) - 3000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + assert_eq!(stack(&s), vec![outer, id_of(&r)]); +} + /// In isolation mode only the isolated group's paths bound areas, for the command and the tool: a /// click in an area that art outside the group encloses adds nothing, and the new path goes inside /// the group, above the path along the area. diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index f535bd0aa3..367ff09318 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -146,6 +146,64 @@ fn within(inner: &Rect, outer: &Rect) -> bool { inner.x0 >= outer.x0 && inner.x1 <= outer.x1 && inner.y0 >= outer.y0 && inner.y1 <= outer.y1 } +/// The outlines of the clipping masks [`unmasked`] has read, by the clipping group or clipped +/// layer: None for one whose mask clips to nothing, which hides all it clips. +type Masks = std::collections::HashMap>; + +/// `shape`, the outline of `leaf`, cut to where every clipping mask around `leaf` shows it +/// ([`clip_to`]). A path in a mask is not cut by that mask. None when the masks hide all of it. +fn unmasked(doc: &Document, leaf: &Node, mut shape: po::Shape, masks: &mut Masks) -> Option { + let Some(line) = doc.ancestry(leaf.id) else { return Some(shape) }; + let filled = leaf.appearance.has_drawn_fill(); + for a in line.iter().filter(|a| **a != leaf.id) { + let Some(n) = doc.node(*a).filter(|n| n.clips()) else { continue }; + let Some(mask) = n.children().and_then(|c| c.first()) else { continue }; + if line.contains(&mask.id) { + continue; + } + let outline = masks.entry(*a).or_insert_with(|| { + vectorcraft_effects::clip_outline(mask).map(|(bp, rule)| (PathData::from_bezpath(&bp), rule)).filter(|(p, _)| !p.is_empty()) + }); + let (m, rule) = outline.as_ref()?; + shape = clip_to(shape, filled, m, *rule)?; + } + Some(shape) +} + +/// `shape` cut to `mask` (filled with `rule`). With `filled` (the path's fill draws), its closed +/// subpaths are cut to their overlap with the mask, whose edge then bounds the fill. Its other +/// subpaths, and every subpath of a path without a fill, are cut to their pieces inside the mask, +/// so a hidden part of an outline does not close an area. A subpath with more segments or +/// crossings than [`po::addons::pathtools::crossings_on`] takes is left out. None when nothing of +/// it is inside. +fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> Option { + let (b, mb) = (shape.path.bounds()?, mask.bounds()?); + if !meet(&b, &mb) { + return None; + } + let (closed, lines): (Vec, Vec) = shape.path.subpaths.into_iter().partition(|sp| filled && sp.closed); + let had_closed = !closed.is_empty(); + let mut subs = if had_closed { po::boolean(&PathData::new(closed), shape.rule, mask, rule, po::BoolOp::Intersect).subpaths } else { vec![] }; + for sp in lines { + let one = PathData::new(vec![sp]); + // A subpath whose crossings with the mask are past what can be found is left out, so no + // part of it the mask hides bounds an area. + let Some(crossed) = po::addons::pathtools::crossings_on(&one, &[mask]) else { continue }; + let places: Vec<(usize, f64)> = crossed.into_iter().map(|(_, s, t)| (s, t)).collect(); + let Some(sp) = one.subpaths.first() else { continue }; + let (cut, at) = po::addons::pathtools::insert_at(sp, &places); + subs.extend(cut.cut_at(&at).into_iter().filter(|piece| { + let n = piece.segment_count(); + n > 0 && path_contains(mask, rule, piece.segment(n / 2).eval(0.5)) + })); + } + if subs.is_empty() { + return None; + } + let rule = if had_closed { FillRule::NonZero } else { shape.rule }; + Some(po::Shape::new(PathData::new(subs), rule, shape.key)) +} + /// The object directly in `scope` (the isolated object in isolation mode), or else directly in a /// layer (or sublayer), that holds `id`: `id` itself when `scope` or a layer holds it, or when `id` /// is `scope`. @@ -217,7 +275,8 @@ pub fn fill_area_roots(doc: &Document, isolation: Option, named: Option< impl AreaFinder { /// The finder over the paths of `roots` (layers or objects) that the Shape Builder takes: /// visible, unlocked paths, compound paths and Live Paint faces and edges that draw, not on a - /// locked artboard. Gaps up to `gap` close, and with `open_filled_as_closed` a filled open path + /// locked artboard. A path a clipping mask clips counts only where the mask shows it + /// ([`unmasked`]). Gaps up to `gap` close, and with `open_filled_as_closed` a filled open path /// bounds an area as if an invisible edge closed it. With `scope` (the isolated object in /// isolation mode), an area's new path goes directly above the object in `scope` that holds the /// front-most path along it, so it stays inside the isolated object. @@ -225,11 +284,13 @@ impl AreaFinder { let roots = sorted_roots(doc, roots); let (shapes, leaves) = shape_builder_shapes(doc, &roots, open_filled_as_closed); let editable = doc.editable(); + let mut masks = Masks::new(); let inputs: Vec<(po::Shape, Rect, NodeId)> = shapes .into_iter() .zip(leaves) .filter(|(_, l)| editable(l.id)) .filter_map(|(s, l)| { + let s = unmasked(doc, l, s, &mut masks)?; let b = s.path.bounds()?; Some((s, b, outermost(doc, l.id, scope))) }) diff --git a/docs/mcp.md b/docs/mcp.md index 5f3af5e49f..9b6fa795e0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14059,7 +14059,9 @@ a stroke when it has `rect`. With both `rect` and `points`, the command also tou The Fill Area tool (`fillArea`, in the Live Paint Bucket's group) adds a new closed path of the area under a click and leaves the paths around it as they are. Nothing needs to be selected: the visible, unlocked paths on every layer -bound areas, filled or not, open paths included, and the overlap of two filled shapes is an area of its own. While the +bound areas, filled or not, open paths included, and the overlap of two filled shapes is an area of its own. A path +that a clipping mask clips bounds areas only where every mask around it shows it, so a click where a mask hides the art +finds no area there. While the pointer hovers an area, the tool outlines it in red and the pointer shows the bucket with paint; elsewhere the pointer shows the empty bucket, and a click there does nothing. The new path appears on the press and is kept on the release; Escape or a canceled touch before the release takes it back. In a document of more than 128 path segments the tool looks diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1fb0f13c0f..c0a86d936e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1599,7 +1599,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Pick Color From Artwork, a merged shape takes the appearance, opacity and blending mode of the object where the drag starts, else of the object where it ends, else of the front-most selected object, as the [Shape Builder combine page](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. A click in an area that no selected object covers, such as a hole other shapes enclose, takes the front-most selected object's look (`shapeBuilder.merge` `points`: the first point is where the drag starts, and the last point is where it ends). A Shift-drag with the Shape Builder tool draws a rectangular marquee for merging many paths at once, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes: the regions it reaches are shaded while it is drawn and merge into one shape on release, or with Alt they are deleted. The marquee reaches each region whose outline crosses it or has an anchor inside it, and the region that holds the whole marquee; this rule is VectorCraft's own. For Pick Color From Artwork, the marquee's starting corner is where the drag starts and the opposite corner is where it ends (`shapeBuilder.merge` `rect`). The Shape Builder works on the selected paths, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. As VectorCraft's own rule, a click or drag that builds nothing says why in the status bar when it is released: "Shape Builder: select paths or compound paths" when nothing is selected or the selection holds no unlocked, visible path; "Shape Builder: select all paths you want to merge" when the release is over a path or compound path that is not selected; and "Shape Builder: no region under the pointer" otherwise. The document, the selection and the undo history stay as they were, and the next gesture that builds something clears the message. Regression tests: `shape_builder_with_nothing_selected_says_what_to_select`, `shape_builder_names_the_unselected_path_under_a_release_that_built_nothing` and `shape_builder_replayed_gesture_over_nothing_gives_its_status_once` in `builder/tests.rs`, and `tests::build::shape_builder_click_that_builds_nothing_shows_why`. - As VectorCraft's own tool, Fill Area (in the Live Paint Bucket's group) adds a new closed path of the area under a click with the current fill and stroke, directly above the front-most object along it, and leaves the paths around it as they are. It needs no selection: the visible, unlocked paths on every layer bound areas, open paths and the overlap of filled shapes included, and it uses the Shape Builder's Gap Detection (`shapeBuilder.copyRegion`). In isolation mode only the isolated layer or group's paths bound areas and the new path goes inside it. It finds no area while the isolated object is not a layer or group, is a group that makes, moves or combines its own art (Live Paint, compound shapes, Shaper groups, graphs, Image Trace results, dimensions, flares, Objects on Path), is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope. Regression tests: `tests::fill_area::*`. + As VectorCraft's own tool, Fill Area (in the Live Paint Bucket's group) adds a new closed path of the area under a click with the current fill and stroke, directly above the front-most object along it, and leaves the paths around it as they are. It needs no selection: the visible, unlocked paths on every layer bound areas, open paths and the overlap of filled shapes included, and it uses the Shape Builder's Gap Detection (`shapeBuilder.copyRegion`). A path that a clipping mask clips bounds areas only where every mask around it shows it. In isolation mode only the isolated layer or group's paths bound areas and the new path goes inside it. It finds no area while the isolated object is not a layer or group, is a group that makes, moves or combines its own art (Live Paint, compound shapes, Shaper groups, graphs, Image Trace results, dimensions, flares, Objects on Path), is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope. Regression tests: `tests::fill_area::*`. Shape Builder pieces on dense hatches (lines at exact 0.25 or 0.5 pt steps across another line) come back one per stretch between crossings, with no speck where the sweep cut a line's two passes a rounding error apart: the planar map contracts the stub between such cuts into one vertex, bounded by each cluster's extent so a run of tiny level segments keeps its length (`crates/pathops/src/planar.rs` tests `a_dense_hatch_at_exact_binary_steps_cuts_each_line_once_per_crossing`, `a_run_of_tiny_level_segments_is_not_contracted_as_stubs`, `a_line_crossed_where_its_two_passes_part_is_cut_once`). The Shape Builder's gray hatch over the region under the pointer and the regions a drag has touched is drawn by a sweep that tests each hatch line only against the region's edges that span it, instead of every edge on every line. The hatch lines are the same, coordinate for coordinate; on a 2,000-sided region 1,000 hatches take about 83 ms of CPU time instead of 356 ms (release build, median of 7 alternating runs), and on a region of 40 sides the time is about the same, so the gain is on large, complex regions such as traced art (`crates/tools/src/builder/tests.rs` tests `hatch_matches_testing_every_edge`, `hatch_tests_only_the_edges_spanning_each_line` and `hatch_sweep_finds_the_crossings_of_every_edge`; timing: `hatch_perf`). The planar map's edge-source grid stays linear in memory on any input: a segment is filed once per cell it crosses, and the grid holds at most a budget of cell references (a few dozen per item plus a few rows' worth), past which the remaining items go to a short scanned list and are still found, so thousands of coincident segments cannot make the index quadratic (`crates/pathops/src/planar.rs` test `rect_index_holds_a_bounded_number_of_references`). From 187e9c9c8a180be8522576bb91c4da13d8000c2b Mon Sep 17 00:00:00 2001 From: ncic <1848265+ncic@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:51:08 +0100 Subject: [PATCH 085/101] Pencil: a redraw stroke's bend stops at the edit distance, and its preview shows on top in any drawing mode (#8438) Most of this pull request reached main with #4221 (the smooth join and the redraw preview). What is left: - A redraw stroke's end bends onto the path over Edit selected paths' distance. When the stroke's points are far apart (a fast stroke), the bend used to run on to the next point; a point is now added where the bend stops, and only one where both ends' bends stop at the same place. - The preview of a redraw stroke is drawn on top, as with Draw Normal, in Draw Behind and Draw Inside too; before, it went behind the path or into its clip group. path.freehand's `leaveSelection` becomes `preview`, which does both. --- crates/engine/src/cmd/draw2/commands.rs | 2 +- crates/engine/src/cmd/draw2/freehand.rs | 68 +++++++++++++++++++++++-- crates/engine/src/tests/brushsym.rs | 5 +- crates/engine/src/tests/draw2.rs | 30 ++++++++++- crates/tools/src/draw2/gesture.rs | 7 +-- crates/tools/src/draw2/gesture/tests.rs | 2 +- 6 files changed, 99 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 9a2ee80033..3928118c3b 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -12,7 +12,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one that leaves the bigger shape; on an open one the way the stroke runs along it at each end decides: it replaces the part it runs along where it starts and joins the part it runs into where it lands, so it replaces the part between, keeps it and closes the path along the stroke, or, when its ends disagree, ends where it is lifted; an end that leaves or meets the path squarely follows the other end, and when both do it closes only if it goes round both pieces beyond), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), preview?: bool (false; true: the stroke is drawn as a new path on top, as with Draw Normal, and the selection stays as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one that leaves the bigger shape; on an open one the way the stroke runs along it at each end decides: it replaces the part it runs along where it starts and joins the part it runs into where it lands, so it replaces the part between, keeps it and closes the path along the stroke, or, when its ends disagree, ends where it is lifted; an end that leaves or meets the path squarely follows the other end, and when both do it closes only if it goes round both pieces beyond), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes", has_doc, freehand ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 5f281e2e34..b6911a5858 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -130,8 +130,9 @@ fn fit_from(a: Point, pts: &[Point], tol: Option, reach: f64) -> Vec, b: Option, reach: f64) { +/// lands on its target and the other end's bend doesn't move it off. Where a bend stops between two +/// points far apart, a point is added there, so the stroke beyond `reach` stays as drawn. +fn bend_ends(stroke: &mut Vec, a: Option, b: Option, reach: f64) { let (Some(&first), Some(&last)) = (stroke.first(), stroke.last()) else { return }; // How far along the stroke each point lies, measured before anything moves. let mut along = Vec::with_capacity(stroke.len()); @@ -153,6 +154,39 @@ fn bend_ends(stroke: &mut [Point], a: Option, b: Option, reach: f6 } return; } + // A point where each bend stops, when that falls between two points (strokes sent by a script + // can have few, far apart): without it, the straight piece to the next point would tilt beyond + // `reach`. + let (mut c0, mut c1) = (a.map(|_| reach), b.map(|_| total - reach)); + if let (Some(x), Some(y)) = (c0, c1) + && x > y + { + (c0, c1) = (Some(y), Some(x)); + } + // Both bends stop at the same place (a stroke twice `reach` long): one point there. + if let (Some(x), Some(y)) = (c0, c1) + && (y - x).abs() < 1e-9 + { + c1 = None; + } + let mut points = Vec::with_capacity(stroke.len() + 2); + let mut dists = Vec::with_capacity(stroke.len() + 2); + let mut before: Option<(Point, f64)> = None; + for (&p, &d) in stroke.iter().zip(&along) { + if let Some((q, e)) = before { + for c in [c0, c1].into_iter().flatten() { + if e + 1e-9 < c && c < d - 1e-9 { + points.push(q.lerp(p, (c - e) / (d - e))); + dists.push(c); + } + } + } + points.push(p); + dists.push(d); + before = Some((p, d)); + } + *stroke = points; + let along = dists; let weight = |d: f64| (1.0 - d / reach).max(0.0); let (shift_a, shift_b) = (a.map(|a| a - first), b.map(|b| b - last)); for (p, &d) in stroke.iter_mut().zip(&along) { @@ -528,7 +562,7 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s let keep_selected = switch_or(p, "keepSelected", true, C)?; // The Pencil's preview of a stroke that redraws a path draws it as a new path but leaves the // selection as it is: the path being redrawn stays selected until the release redraws it. - let leave_selection = switch_or(p, "leaveSelection", false, C)?; + let preview = switch_or(p, "preview", false, C)?; let filled = switch_or(p, "fill", false, C)?; let extend = p.get("extend").filter(|v| !v.is_null()); if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) { @@ -779,8 +813,13 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s st.brush = Some(name.to_string()); } } - let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?; - if !keep_selected && !leave_selection { + // A preview goes on top as Draw Normal places it: Draw Inside would put it in the selected + // path's clip group, clipped, and Draw Behind behind the path. + let mode = if preview { std::mem::replace(&mut s.draw_mode, crate::DrawMode::Normal) } else { s.draw_mode }; + let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected && !preview); + s.draw_mode = mode; + let out = out?; + if !keep_selected && !preview { // A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke // by dropping the earlier selection, it does not keep it (#5752). s.select(|_, sel| sel.clear())?; @@ -975,4 +1014,23 @@ mod bend_tests { assert_eq!(pts[2], Point::new(48.0, 0.0), "{pts:?}"); assert_eq!(pts[1], Point::new(44.0, 0.0), "halfway, half of each end's shift: {pts:?}"); } + + /// With points far apart (a stroke sent by a script), the bend still stops `reach` along the + /// stroke: a point is added there, and the stroke beyond it stays as drawn. + #[test] + fn bend_ends_stops_at_the_reach_between_points_far_apart() { + let mut pts = vec![Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(200.0, 0.0)]; + bend_ends(&mut pts, Some(Point::new(0.0, 10.0)), Some(Point::new(200.0, 0.0)), 40.0); + assert_eq!(pts.first(), Some(&Point::new(0.0, 10.0)), "{pts:?}"); + assert!(pts.contains(&Point::new(40.0, 0.0)), "a point where the bend stops: {pts:?}"); + assert!(pts.iter().filter(|p| p.x >= 40.0).all(|p| p.y == 0.0), "beyond the reach, as drawn: {pts:?}"); + } + + /// Where both bends stop at the same place, one point is added there, not two. + #[test] + fn bend_ends_adds_one_point_where_both_bends_stop() { + let mut pts = vec![Point::new(0.0, 0.0), Point::new(100.0, 0.0)]; + bend_ends(&mut pts, Some(Point::new(0.0, 10.0)), Some(Point::new(100.0, 10.0)), 50.0); + assert_eq!(pts, [Point::new(0.0, 10.0), Point::new(50.0, 0.0), Point::new(100.0, 10.0)]); + } } diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 427def6754..7ac6b8c4e2 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1357,10 +1357,7 @@ fn brush_freehand_refuses_unknown_keys() { let spec = crate::cmd::find_command("brush.freehand").unwrap(); let mut keys = crate::cmd::params::accepted_keys(spec.params).expect("the description names every key"); keys.sort_unstable(); - assert_eq!( - keys, - ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "leaveSelection", "points", "redraw", "style"] - ); + assert_eq!(keys, ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "points", "preview", "redraw", "style"]); let mut s = session(); let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); select(&mut s, &[a]); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 5017316c44..45800e5831 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -552,6 +552,28 @@ fn pencil_redraws_the_shorter_way_round_a_closed_path() { assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "redraw": {"id": id.0, "within": -1}})).is_err()); } +/// `preview` draws the stroke as a new path on top, beside the selected path, and leaves the +/// selection as it was, in Draw Behind and Draw Inside too, as the Pencil previews a stroke that +/// redraws a selected path. +#[test] +fn pencil_preview_draws_on_top_and_leaves_the_selection_as_it_was() { + for mode in ["normal", "behind", "inside"] { + let mut s = session(); + let r = rect(&mut s, 400.0, 400.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + s.execute("view.drawMode", &json!({ "mode": mode })).unwrap(); + let (parent, _, _) = s.doc().unwrap().doc.position(r).unwrap(); + let out = + s.execute("path.freehand", &json!({"points": [[100, 200], [150, 220], [200, 200]], "keepSelected": false, "preview": true})).unwrap(); + let id = NodeId(out["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let ((rp, ri, _), (np, ni, _)) = (d.position(r).unwrap(), d.position(id).unwrap()); + assert!(rp == parent && np == parent, "{mode}: beside the path, in no clip group"); + assert!(ni > ri, "{mode}: on top of the path"); + assert_eq!(s.doc().unwrap().selection.objects, vec![r], "{mode}: the selection as it was"); + } +} + /// With Keep selected off, a new stroke leaves nothing selected (the earlier selection goes too, /// as Illustrator starts the stroke by dropping it, #5752); a continued or redrawn path is /// deselected and the rest of the selection stays. The stroke is one undo step. @@ -617,8 +639,14 @@ fn freehand_with_fit_off_joins_the_points_with_straight_segments() { .unwrap(); let sp = path(&s, r).subpaths[0].clone(); assert!(corners(&sp), "{:?}", sp.anchors); + // Each end's bend stops `within` (4) along the stroke, at a point added on its first and last + // piece; the drawn points beyond stay as drawn. let inner: Vec<_> = at(&sp).into_iter().filter(|p| p.1 < 499.0).collect(); - assert_eq!(inner, [(125.0, 470.0), (150.0, 460.0), (175.0, 470.0)]); + let t = 4.0 / 25f64.hypot(31.0); + let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9; + assert_eq!(inner.len(), 5, "{inner:?}"); + assert!(near(inner[0], (100.0 + 25.0 * t, 501.0 - 31.0 * t)) && near(inner[4], (200.0 - 25.0 * t, 501.0 - 31.0 * t)), "{inner:?}"); + assert_eq!(inner[1..4], [(125.0, 470.0), (150.0, 460.0), (175.0, 470.0)]); assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "fit": "no"})).is_err()); } diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 4f2fb7b463..ca37456e92 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1563,8 +1563,9 @@ impl GestureTool { /// The preview of a stroke being drawn: [`Self::freehand_params`], except that a stroke that /// redraws a selected path is shown as it is drawn, joined at its start to the point of the - /// path nearest to it, with no fill, and leaves the path and the selection as they are: where - /// the stroke ends is only known at the release, which redraws the path (`finish`). + /// path nearest to it, with no fill, on top in any drawing mode, and leaves the path and the + /// selection as they are: where the stroke ends is only known at the release, which redraws + /// the path (`finish`). fn drawing_params(&self, cx: &ToolContext) -> Value { let mut v = self.freehand_params(cx, false); let Some((id, _)) = self.redraw else { return v }; @@ -1573,7 +1574,7 @@ impl GestureTool { } v["fill"] = json!(false); v["keepSelected"] = json!(false); - v["leaveSelection"] = json!(true); + v["preview"] = json!(true); let on = self.points.first().and_then(|&p| cx.doc.node(id)?.path_data()?.nearest(p)).map(|n| n.3); if let (Some(on), Some(pts)) = (on, v["points"].as_array_mut()) { pts.insert(0, json!([on.x, on.y])); diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 24a0e1e5e6..f88c2afeac 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -882,7 +882,7 @@ fn pencil_previews_a_redraw_as_the_stroke_drawn_and_redraws_at_the_release() { let previews: Vec<&Value> = drawing.iter().flatten().filter_map(|a| if let Action::Preview(_, v) = a { Some(v) } else { None }).collect(); assert!(!previews.is_empty(), "{acts:?}"); for v in previews { - assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false && v["leaveSelection"] == true, "{v}"); + assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false && v["preview"] == true, "{v}"); assert_eq!(v["points"][0], json!([350.0, 300.0]), "joined to the path where it starts: {v}"); assert_eq!(v["points"][1], json!([350.0, 304.0]), "{v}"); } From 0c65a8442bc4eeb020b6d7545bc32d4f91aa4efd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:02:16 -0800 Subject: [PATCH 086/101] Fill Area: a path left out of the search stops an area only when it reaches it When the paths together are over the segment limit, the search maps the paths near the point and leaves out the ones with the most segments. A path left out made the search give up on an area when it came within the gap plus 1 pt of the area's outline, so with Gap Detection off a long line 0.75 pt outside a square stopped a click inside the square from filling it. A gap bridge reaches at most the gap, so the check now uses the gap plus the map's 0.05 pt contact tolerance. The 1 pt padding still decides which paths the search picks. --- crates/engine/src/tests/fill_area.rs | 34 +++++++++++++++++++++++++++ crates/tools/src/builder/fill_area.rs | 11 +++++---- docs/mcp.md | 4 +++- 3 files changed, 44 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index 6703d4f928..d6e82af05b 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -582,6 +582,40 @@ fn fill_area_fills_an_l_whose_empty_corner_holds_a_left_out_path() { assert!((area(&s, id_of(&r)) - 70_000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); } +/// Draws a 100 pt square at the origin and, in front of it, an open path with too many segments +/// that runs from x -20 to 120 at `y` and up to 0.1 pt above it, then clicks at `click` with +/// `gap`. Gives the area of the new path, or None when the click finds no area. +fn square_beside_a_huge_line(y: f64, gap: f64, click: (f64, f64)) -> Option { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS; + let pts: Vec = (0..=n).map(|k| Point::new(-20.0 + 140.0 * k as f64 / n as f64, y - (k % 2) as f64 * 0.1)).collect(); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [click.0, click.1], "gap": gap})).ok()?; + Some(area(&s, id_of(&r))) +} + +/// With Gap Detection off, a path with too many segments 0.75 pt outside a square is left out and +/// does not touch the square, so a click in the square fills it. One that crosses the square still +/// stops the fill. +#[test] +fn fill_area_fills_a_square_a_left_out_path_passes_close_to() { + let a = square_beside_a_huge_line(-0.75, 0.0, (50.0, 50.0)).expect("the square"); + assert!((a - 10_000.0).abs() < 1.0, "{a}"); + assert_eq!(square_beside_a_huge_line(60.0, 0.0, (50.0, 25.0)), None); +} + +/// With a gap, a path with too many segments farther from the square than the gap is left out and +/// does not stop the square from being filled. One that crosses the square still stops the fill. +#[test] +fn fill_area_gap_fills_a_square_a_left_out_path_passes_beyond_the_gap() { + let a = square_beside_a_huge_line(-2.75, 2.0, (50.0, 50.0)).expect("the square"); + assert!((a - 10_000.0).abs() < 1.0, "{a}"); + assert_eq!(square_beside_a_huge_line(60.0, 2.0, (50.0, 25.0)), None); +} + /// A filled contour with too many segments on a higher layer surrounds a small square, its outline /// far from it: it is left out of the map, and the new path still goes above it, since it covers /// the area. diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index 367ff09318..2ce72b15f3 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -74,7 +74,8 @@ struct Reach<'a> { face: &'a PathData, bez: &'a vectorcraft_geom::kurbo::BezPath, zone: Rect, - /// How close (pt) to the outline a path may come and still change the area: the gap and 1 pt. + /// How close (pt) to the outline a path may come and still change the area: the gap and + /// [`CONTACT`]. reach: f64, } @@ -359,13 +360,15 @@ impl AreaFinder { let before = window; match bounds { // A path left out that crosses the area or comes within its reach could cut it, and - // only the map of every path holds both. + // only the map of every path holds both. A bridge reaches at most `gap`, so a path + // farther than that from the outline, give or take [`CONTACT`], does not change it. Some(rb) if within(&rb, &window) => { - let reached = rb.inflate(reach, reach); + let contact = self.gap + CONTACT; + let reached = rb.inflate(contact, contact); let mut budget = CUT_BUDGET; let cut = any_left_out && face.is_none_or(|(region, bez, _)| { - let area = Reach { face: ®ion.path, bez, zone: reached, reach }; + let area = Reach { face: ®ion.path, bez, zone: reached, reach: contact }; self.inputs.iter().zip(&left_out).any(|((s, b, _), out)| *out && meet(b, &reached) && cuts(&s.path, &area, &mut budget)) }); if !cut { diff --git a/docs/mcp.md b/docs/mcp.md index 3a496a84df..8bd390d263 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14082,7 +14082,9 @@ Objects on Path group, is a layer or group with a live effect or a clipping mask inside an envelope. A point in no enclosed area is the error "Fill Area: no enclosed area under the pointer" and records no undo step; a `gap` outside 0 to 72 is an error. It returns `{id, above}`. The command looks for the area among the paths near the point first. When the paths together have more than 65,536 segments and the paths near the point do not -enclose it, the point counts as in no enclosed area. +enclose it, the point counts as in no enclosed area. A path that this search leaves out to stay within that limit +stops the command from finding the area only when it crosses the area or comes within the gap plus 0.05 pt of its +outline. ```json {"name":"run_command","arguments":{"command":"shapeBuilder.copyRegion","params":{"point":[50,70],"gap":3}}} From bd929322eaa587e4d098185133f5b7a320ed5e30 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:35:55 -0800 Subject: [PATCH 087/101] File dialogs: a replace question after a save panel keeps the request's file access A save that a confined automation request started stores that request's file-access scope and automation flag. When the save panel answers in a later frame, the save pump runs its next step under them, so the question before replacing a file the panel did not ask about, and its OK, stay under the request's roots instead of the desktop's access. --- crates/ui-egui/src/file_asks.rs | 8 ++++++++ crates/ui-egui/src/io/save.rs | 14 ++++++++++++-- crates/ui-egui/src/tests/saveext.rs | 25 +++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/file_asks.rs b/crates/ui-egui/src/file_asks.rs index 93f05ed678..ba6a6f57dd 100644 --- a/crates/ui-egui/src/file_asks.rs +++ b/crates/ui-egui/src/file_asks.rs @@ -78,6 +78,14 @@ impl FileAsks { pub(crate) fn asking(&self) -> bool { !self.waiting.is_empty() || !self.replacing.is_empty() } + + /// Whether the newest open replace question goes on confined to automation roots, and whether + /// as automation. + #[cfg(test)] + pub(crate) fn replace_access(&self) -> Option<(bool, bool)> { + let r = self.replacing.last()?; + Some((r.scope.clone().run(vectorcraft_engine::file_access::current).is_some(), r.automated)) + } } // PLAN: callers use the function form of `BUSY` and `CLOSED`; `tl!` is a runtime lookup, so they are not consts. diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 97c9c89be2..98f082b312 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -42,6 +42,9 @@ struct SaveDone { retry: Option, /// The changed-on-disk question, while it is open. question: Option, + /// The file-access scope and automation flag of the request that started the save: the steps + /// [`pump`] runs once the flow answers run under them, not under the desktop's access of that frame. + asked: (ScopeHandle, bool), then: Option, } @@ -136,8 +139,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { app.saves.watch.forget(&uid); continue; } - let Some(step) = next_step(app, uid) else { continue }; - if let Err(e) = run_step(app, uid, step) + let (scope, automated) = app.saves.done.get(&uid).map_or_else(|| (ScopeHandle::capture(), app.automation_asked()), |d| d.asked.clone()); + let r = scope.run(|| { + file_asks::as_automated(app, automated, |app| { + let step = next_step(app, uid)?; + Some(run_step(app, uid, step)) + }) + }); + if let Some(Err(e)) = r && e != "cancelled" { app.status(e); @@ -279,6 +288,7 @@ fn start_flow(app: &mut VectorcraftApp, first: &SavePlan, s: Start<'_>) -> Resul retrying: s.retrying, retry: s.retry, question: None, + asked: (ScopeHandle::capture(), app.automation_asked()), then, }; app.saves.done.insert(uid, done); diff --git a/crates/ui-egui/src/tests/saveext.rs b/crates/ui-egui/src/tests/saveext.rs index d3ed6f1a3e..dd058a6043 100644 --- a/crates/ui-egui/src/tests/saveext.rs +++ b/crates/ui-egui/src/tests/saveext.rs @@ -302,6 +302,31 @@ fn a_replaced_extension_asks_before_replacing_a_file_there() { } } +/// A save that automation confined to a folder started: its panel answers in a later frame, outside +/// the request, and the question before replacing a file the panel did not ask about goes on under +/// that folder and as automation. +#[test] +fn a_replace_question_after_a_save_panel_goes_on_under_the_access_of_the_request() { + let (mut app, picker, w) = saving_app(); + let inside = vectorcraft_testkit::TempDir::new("save-replace-scope"); + let typed = inside.join("card.png").to_string_lossy().into_owned(); + let there = inside.join("card.vectorcraft").to_string_lossy().into_owned(); + let t = there.clone(); + app.services.exists = Some(Arc::new(move |p: &str| p == t)); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + vectorcraft_engine::file_access::confine(roots.as_ref(), || { + crate::file_asks::as_automated(&mut app, true, |app| { + let _ = app.run("file.save", json!({})); + }) + }); + picker.answer_saved(&typed, None); + poll(&mut app); + assert_eq!(replace_asked(&app).as_deref(), Some("card.vectorcraft")); + assert_eq!(app.file_asks.replace_access(), Some((true, true)), "(confined, as automation)"); + answer_replace(&mut app, true); + assert_eq!(*w.borrow(), [there]); +} + /// Save As to the type picked asks for that format's options: the .ai options (Version first), /// not VectorCraft's. #[test] From e7bb81d80e02c36bc742f48a3acf00bab7f14067 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:20:00 -0800 Subject: [PATCH 088/101] Plug-ins: a script's command reads no plug-in folder file whose name isn't valid text A plug-in folder load checks each file against the automation roots and, in a command a script runs, the script's read gate. A file whose name isn't valid text cannot be checked by name, and without automation roots it loaded unchecked, also in a script's command. A link with such a name, in a folder the script may read, loaded a module from anywhere. Such a file is now refused in a script's command, as it already was under automation roots. Outside both, it still loads. --- crates/engine/src/cmd/plugin.rs | 8 ++++--- crates/engine/src/tests/plugins.rs | 36 ++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 30515fcb45..84b98cb54e 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1533,9 +1533,11 @@ fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending let allow = move |f: &std::path::Path| { scope.clone().run(|| match f.to_str() { Some(f) => crate::file_access::check_read(f), - // A lossy name would check another file than the one loaded. - None if crate::file_access::current().is_none() => Ok(()), - None => Err(format!("automation path rejected: {} isn't valid text", f.display())), + // A lossy name would check another file than the one loaded, so such a file loads only + // where no read is checked: without roots and outside a script's command. + None if crate::file_access::current().is_some() => Err(format!("automation path rejected: {} isn't valid text", f.display())), + None if crate::file_access::in_script_command() => Err(format!("Script file access denied: {} isn't valid text", f.display())), + None => Ok(()), }) }; // The modules start loading once the loads queued before them are done. diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 855952fcb2..f5ffc17f9d 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2126,6 +2126,42 @@ fn plugin_list_leaves_out_paths_outside_the_read_root() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A command a script runs loads a plug-in folder's files through the script's read gate also +/// without automation roots: a link in a folder the script may read, to a module outside it, is +/// refused whether or not its name is valid text. +#[cfg(unix)] +#[test] +fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_text() { + use crate::file_access::{ScriptGate, ScriptScope, with_script_gate}; + use std::os::unix::ffi::OsStrExt; + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let base = crate::tests_links::Folder::new("plugin-script-name-not-text"); + let (inside, outside) = (base.0.join("in"), base.0.join("out")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let (text_id, bytes_id) = ("test.engine.script.textname", "test.engine.script.bytesname"); + for (id, file, link) in [(text_id, "text.wasm", &b"a.wasm"[..]), (bytes_id, "bytes.wasm", &b"b\xff.wasm"[..])] { + let src = tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#); + std::fs::write(outside.join(file), wat::parse_str(src).unwrap()).unwrap(); + std::os::unix::fs::symlink(outside.join(file), inside.join(std::ffi::OsStr::from_bytes(link))).unwrap(); + } + let gate = ScriptGate { + read: ScriptScope::of_folder(&inside), + write: ScriptScope::default(), + documents: vec![], + linked: Default::default(), + also: None, + }; + let mut s = session(); + let folder = inside.to_string_lossy().to_string(); + let r = with_script_gate(gate, || s.execute("plugin.reload", &json!({"path": folder}))); + let installed = [text_id, bytes_id].map(vectorcraft_plugins::registry::remove); + assert_eq!(installed, [false, false], "a script loaded a module from outside its folder: {r:?}"); + let r = r.unwrap(); + assert_eq!(r["loaded"], json!([]), "{r}"); + assert_eq!(r["failed"].as_array().map(Vec::len), Some(2), "{r}"); +} + /// Under automation read roots, a plug-in turned off for the next launch is listed with a file /// outside them named by its file name, and `plugin.setEnabled` turns it on by that name. #[test] From 9cd83e93424595c31bc41457aa5b8cd78f916be1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:28:23 -0800 Subject: [PATCH 089/101] Learn: a click or Enter on the skill or tutorial opened before opens it again Follow-up to #8800. The Learn panel's skill and tutorial lists keep their selection, and a click on the row that is already selected reports CollectionEvent::Picked rather than a selection change, so after Back a click on the skill or tutorial opened before did nothing. Enter on that row reports Activate, which the lists also ignored. The lists now open the item on Picked and Activate as well as on a selection change, as every row click did before the port. --- crates/ui-egui/src/panels/learn.rs | 6 +-- crates/ui-egui/src/panels/learn/tests.rs | 49 ++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/learn.rs b/crates/ui-egui/src/panels/learn.rs index d765fe48c3..985871889c 100644 --- a/crates/ui-egui/src/panels/learn.rs +++ b/crates/ui-egui/src/panels/learn.rs @@ -73,10 +73,12 @@ fn run(app: &mut VectorcraftApp, cmd: &str, params: Value) { } } -/// The key a collection's last selection change set, if any: a click on a row or a tab. +/// The key a collection's last pick chose, if any: a click on a row or a tab, a click on the row or tab already +/// selected, or Enter on one. fn picked(events: Vec>) -> Option { events.into_iter().rev().find_map(|event| match event { CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => keys.into_iter().last(), + CollectionEvent::Picked { key, .. } | CollectionEvent::Activate(key) => Some(key), _ => None, }) } @@ -158,8 +160,6 @@ fn skill_list(app: &mut VectorcraftApp, ui: &mut Ui) { let rings: Vec<(&'static catalog::Skill, SkillRing)> = catalog::SKILLS.iter().map(|s| (s, SkillRing { done: progress.done(s), total: s.tutorials.len() })).collect(); let source = keyed(&keys, |key: &&'static str| *key); - // PLAN: a single-select list keeps its last pick highlighted and reports no change when the same key is - // picked again; the keys differ between the levels, but the list is the framework's to reset on a new view. // A few skills: the list is as tall as its rows, so Reset progress shows under them. let out = List::new(tl!("Skills")).select(SelectMode::Single).natural_height(true).show_items(ui, &source, &mut |key, _| { let row = ListRow::new(*key); diff --git a/crates/ui-egui/src/panels/learn/tests.rs b/crates/ui-egui/src/panels/learn/tests.rs index 78a2c12e08..d47f6a39b9 100644 --- a/crates/ui-egui/src/panels/learn/tests.rs +++ b/crates/ui-egui/src/panels/learn/tests.rs @@ -400,6 +400,55 @@ fn the_tabs_rows_and_back_run_their_commands() { press(&mut app, "Back", View { tab: Tab::Skills, skill: None, tutorial: None }); } +/// A click on the skill or the tutorial that was opened before, after Back, opens it again. +#[test] +fn a_click_on_the_skill_or_tutorial_opened_before_opens_it_again() { + let mut app = app(); + let ctx = app.ui_ctx.clone().expect("a window"); + let (skill, tutorial) = catalog::tutorial("gradient").unwrap(); + let open_skill = View { tab: Tab::Skills, skill: Some(skill.id), tutorial: None }; + let open_tutorial = View { tutorial: Some(tutorial.id), ..open_skill.clone() }; + let skills = View { tab: Tab::Skills, skill: None, tutorial: None }; + for (name, view) in [ + ("Skills", skills.clone()), + (skill.title, open_skill.clone()), + (tutorial.title, open_tutorial.clone()), + ("Back", open_skill.clone()), + (tutorial.title, open_tutorial.clone()), + ("Back", open_skill.clone()), + ("Back", skills.clone()), + (skill.title, open_skill.clone()), + ] { + click(&mut app, &ctx, name, show); + assert_eq!(app.ui.learn, view, "{name}"); + } +} + +/// Enter on the tutorial that was opened before, after Back and Tab into the list, opens it again. +#[test] +fn enter_on_the_tutorial_opened_before_opens_it_again() { + let mut app = app(); + let ctx = app.ui_ctx.clone().expect("a window"); + let (_, tutorial) = catalog::tutorial("gradient").unwrap(); + app.run("learn.show", json!({"tutorial": tutorial.id})).unwrap(); + let opened = app.ui.learn.clone(); + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + click(&mut app, &ctx, "Back", show); + click(&mut app, &ctx, tutorial.title, show); + assert_eq!(app.ui.learn, opened, "a click opens it"); + click(&mut app, &ctx, "Back", show); + let focused = |app: &mut VectorcraftApp, events| { + let input = egui::RawInput { events, screen_rect: Some(SCREEN), ..Default::default() }; + let update = crate::testing::part_frame(app, &ctx, input, show).platform_output.accesskit_update?; + update.nodes.into_iter().find(|(id, _)| *id == update.focus).and_then(|(_, n)| n.label().map(str::to_owned)) + }; + let on_row = (0..10).any(|_| focused(&mut app, vec![key(egui::Key::Tab)]).as_deref() == Some(tutorial.title)); + assert!(on_row, "Tab reaches the tutorial's row"); + frame(&mut app, &ctx, vec![key(egui::Key::Enter)], show); + frame(&mut app, &ctx, vec![], show); + assert_eq!(app.ui.learn, opened, "Enter opens it"); +} + /// `learn.tab` switches tabs and keeps what the Skills tab had open; `learn.skill` opens a skill's /// tutorials and answers the skill as `learn.list` lists it; `learn.back` goes up one level and /// keeps the view on the list of skills and on the For you tab. From 11af59a2b5b05bfec32db1ae075d50bf580ccb57 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:57:29 -0800 Subject: [PATCH 090/101] Panels: the Cycle Display Sizes button is named by its label The double-triangle button at the left end of a panel's tab strip ran window.panel.cycleOptions with no label of its own. No menu item runs that command, so it has no command definition, and the button took the command id as its accessible name: screen readers read "window.panel.cycleOptions" and the button showed no tooltip. The button now carries the "Cycle Display Sizes" label, which names it and gives it its tooltip. The string is already in the word catalogs. A test opens the Stroke panel, reads the access tree and checks that the button is named "Cycle Display Sizes" and that no button in the window is named by a command id. --- crates/ui-egui/src/panel_docking.rs | 7 +++++-- crates/ui-egui/src/panel_docking/tests.rs | 13 +++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index c9d8c8dd7c..dce3c4aa7b 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use craft::behavior::{Axis, DockSide, IconId}; use craft::ui::buttons::IconButton; -use craft::ui::contract::{Bind, BodyCx, PlainData, Show as _, Tracked}; +use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _, Tracked}; use craft::ui::docking::{ ColumnCards, DockCommands, DockConfig, DockEvent, DockGrid, DockPanels, DockScene, DockSizes, DockTo, DragUnit, FloatSpace, GroupAt, HidePanels, PanelKey, PanelSpec, PanelSpecs, actions as command_actions, move_actions, request_actions, @@ -1255,7 +1255,10 @@ impl DockPanels for Panels<'_> { fn group_header(&mut self, panels: &[String], active: usize, ui: &mut egui::Ui, _cx: &mut BodyCx<'_>) { let Some(panel) = panels.get(active).filter(|p| sizes::has_sizes(p)) else { return }; - IconButton::command(IconId::new("dc-cycle-sizes"), CommandRef::with_params("window.panel.cycleOptions", json!({"panel": panel}))).show(ui); + // The command has no menu item, so its label comes from here: the button and its tooltip are named by it. + IconButton::command(IconId::new("dc-cycle-sizes"), CommandRef::with_params("window.panel.cycleOptions", json!({"panel": panel}))) + .label(tl!("Cycle Display Sizes")) + .show(ui); } fn panel_rows(&mut self, panel: &String) -> Vec { diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index b3eb083b42..dd996ee1dd 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -911,6 +911,19 @@ fn cycle_options_steps_through_the_sizes_and_returns_to_the_largest() { assert!(!crate::panels::part_hidden(&h.app, "tr-hide-thumbs"), "the largest size shows the thumbnails"); } +/// The tab strip's Cycle Display Sizes button is named by its label, and no button of a panel's tab +/// strip is named by a command id. +#[test] +fn tab_strip_buttons_are_named_by_their_labels() { + let mut h = Harness::new(); + h.app.run("window.panel.activate", json!({"panel": "stroke"})).unwrap(); + h.frames(3); + let buttons: Vec<&str> = h.nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Button).filter_map(|(_, n)| n.label()).collect(); + assert!(buttons.contains(&"Cycle Display Sizes"), "{buttons:?}"); + let ids: Vec<&&str> = buttons.iter().filter(|l| !l.contains(' ') && l.contains('.') && l.starts_with(|c: char| c.is_ascii_lowercase())).collect(); + assert!(ids.is_empty(), "buttons named by a command id: {ids:?}"); +} + /// A panel the Window menu floats opens tall enough for its content: every control of Asset Export, /// and every Image Trace control down to the top of its Advanced section, lies between the body's /// top and bottom, none scrolled or clipped away. From 6c29bf9937e6a4f98c8b840514875c5c360c5f44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:03:26 -0800 Subject: [PATCH 091/101] Transform Each: screen readers tell the Scale and Move fields apart Transform Each and Effect > Distort & Transform > Transform named both the Scale and the Move slider and number field "Horizontal:" and "Vertical:", so only the unit in the value told them apart. Each control's accessible name now starts with its row ("Scale Horizontal:", "Move Vertical:"), and the visible label describes it, as Split Into Grid names its Gutter and Total fields. The visible labels are unchanged. --- crates/ui-egui/src/dialogs/tests.rs | 47 ++++++++++++++++++++ crates/ui-egui/src/dialogs/transform_each.rs | 28 +++++++----- 2 files changed, 63 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 273853c045..1eeec2d52d 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -429,6 +429,53 @@ fn the_transform_effect_dialog_has_its_controls_previews_them_and_shows_them_aga assert_eq!((flag(&app, "objects"), flag(&app, "strokes")), (true, true)); } +/// The names of the sliders and number fields in the window's access tree. +fn slider_and_field_names(app: &mut VectorcraftApp) -> Vec { + let out = frame(app, vec![]); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + update + .nodes + .iter() + .filter(|(_, node)| matches!(node.role(), Role::TextInput | Role::SpinButton | Role::Slider)) + .filter_map(|(_, node)| node.label()) + .map(str::to_owned) + .collect() +} + +/// Each Scale and Move slider and number field carries its row in its name, so the two Horizontal and two Vertical +/// labels are told apart; the visible labels only describe them. +fn assert_scale_and_move_names(names: &[String]) { + for name in ["Scale Horizontal:", "Scale Vertical:", "Move Horizontal:", "Move Vertical:"] { + let count = names.iter().filter(|n| n.as_str() == name).count(); + assert_eq!(count, 2, "a slider and a number field named {name}: {names:?}"); + } + for bare in ["Horizontal:", "Vertical:"] { + assert!(!names.iter().any(|n| n == bare), "no control named only {bare}: {names:?}"); + } +} + +/// Effect > Distort & Transform > Transform names its Scale and Move controls by their row. +#[test] +fn the_transform_effect_names_scale_and_move_controls_by_their_row() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": "distort.transform"})).unwrap(); + settle(&mut app); + assert_scale_and_move_names(&slider_and_field_names(&mut app)); +} + +/// Object > Transform > Transform Each shares the rows, and so the names. +#[test] +fn transform_each_names_scale_and_move_controls_by_their_row() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap(); + app.run("select.all", json!({})).unwrap(); + open_each(&mut app, false); + settle(&mut app); + assert_scale_and_move_names(&slider_and_field_names(&mut app)); +} + /// Transform Each opened by its menu item, on Absolute when `absolute` (as it was last confirmed). fn open_each(app: &mut VectorcraftApp, absolute: bool) { if absolute { diff --git a/crates/ui-egui/src/dialogs/transform_each.rs b/crates/ui-egui/src/dialogs/transform_each.rs index 0ca75cd8e0..3672552552 100644 --- a/crates/ui-egui/src/dialogs/transform_each.rs +++ b/crates/ui-egui/src/dialogs/transform_each.rs @@ -17,7 +17,7 @@ use craft::behavior::Mixed; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel}; use craft::ui::dialog::{DialogHost, DialogId, FieldRefusal}; use craft::ui::display::Text; use craft::ui::form::Field; @@ -290,30 +290,32 @@ enum Measure { } /// One captioned side: a slider over `rail` and a number field in ±`limit`, `value` being none -/// while the objects differ (the field reads Mixed). Returns the value the user set this pass. +/// while the objects differ (the field reads Mixed). `caption` is the row (Scale or Move) and the +/// visible label; the label repeats in each row, so it only describes the controls, and their +/// names start with the row. Returns the value the user set this pass. fn side( ui: &mut Ui, key: &'static str, - label: impl Into