diff --git a/crates/apischema/src/lib.rs b/crates/apischema/src/lib.rs index 5db24230e1..cff749e84f 100644 --- a/crates/apischema/src/lib.rs +++ b/crates/apischema/src/lib.rs @@ -250,7 +250,8 @@ impl ParamSchema { /// What is wrong with the schema itself, or `None`: a parameter name that is empty, repeated /// or holds `.`, `[` or `]`; a required parameter with a default; a default that isn't JSON or /// doesn't pass its parameter's type; an enum with no names or a repeated name; a range with - /// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`]. + /// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`], or a + /// [`Type::Ids`] or [`Type::Point`], whose values are all lists, at the nesting limit. pub fn definition_problem(&self) -> Option { object_problem("", self.params, 0) } @@ -319,7 +320,9 @@ pub enum Problem { Missing, /// The value is not of the parameter's type: `expected` says what it must be. WrongType { expected: String, got: String }, - /// The schema nests deeper than [`MAX_DEPTH`] here ([`ParamSchema::definition_problem`]). + /// The value nests deeper than [`MAX_DEPTH`] here: a list given for a [`Type::Color`] at the + /// nesting limit, or any value under a schema that nests too deeply itself + /// ([`ParamSchema::definition_problem`]). TooDeep, } @@ -779,6 +782,8 @@ fn type_problem(at: &str, ty: &Type, depth: usize) -> Option { Type::Object(params) => object_problem(at, params, depth + 1), Type::Array(_) if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")), Type::Array(item) => type_problem(&format!("{at}[]"), item, depth + 1), + // Every value of these is a list, and a list at the nesting limit is refused. + Type::Ids | Type::Point if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")), _ => None, } } diff --git a/crates/apischema/src/tests.rs b/crates/apischema/src/tests.rs index 30b939879a..4b8d51d8b0 100644 --- a/crates/apischema/src/tests.rs +++ b/crates/apischema/src/tests.rs @@ -156,6 +156,36 @@ fn id_lists_points_and_color_lists_count_toward_the_nesting_limit() { assert!(check(MAX_DEPTH, &Type::Color, &json!("#ff0000")).is_ok()); } +/// `ty` inside `levels` lists. +fn in_lists(levels: usize, ty: Type) -> Type { + (0..levels).fold(ty, |inner, _| Type::Array(Box::leak(Box::new(inner)))) +} + +/// `v` inside `levels` lists. +fn wrapped(levels: usize, v: Value) -> Value { + (0..levels).fold(v, |inner, _| Value::Array(vec![inner])) +} + +/// The schema check and the value check agree on the fixed-shape lists at the nesting limit: an id +/// list or a point there could take no value, so the schema is wrong in itself, and a color there +/// takes a string, while a color list is refused as nested too deeply, at its path. +#[test] +fn fixed_shape_lists_at_the_nesting_limit_follow_the_schema_check() { + for ty in [Type::Ids, Type::Point, Type::Color] { + assert_eq!(one(in_lists(MAX_DEPTH - 1, ty)).definition_problem(), None, "{ty:?}"); + } + for ty in [Type::Ids, Type::Point] { + let problem = one(in_lists(MAX_DEPTH, ty)).definition_problem(); + assert!(problem.as_deref().is_some_and(|p| p.contains("nests deeper")), "{ty:?}: {problem:?}"); + } + let color = one(in_lists(MAX_DEPTH, Type::Color)); + assert_eq!(color.definition_problem(), None); + assert_eq!(color.validate(&json!({"x": wrapped(MAX_DEPTH, json!("#ff0000"))})).unwrap(), None); + let e = color.validate(&json!({"x": wrapped(MAX_DEPTH, json!([1, 0, 0]))})).unwrap_err(); + assert_eq!(e.problem, Problem::TooDeep); + assert_eq!(e.path, format!("x{}", "[0]".repeat(MAX_DEPTH))); +} + #[test] fn a_saved_retired_key_past_the_nesting_limit_is_refused() { let params = holding("older", nested_lists(500_000)); diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 0379fc4ea5..4860e4989a 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -672,7 +672,7 @@ impl<'a> Scene<'a> { self.shape(n, &bp, *rule); } NodeKind::Text(t) => self.text(n, t), - NodeKind::Image(im) => self.image(im), + NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)), NodeKind::SymbolInstance { symbol, xf } => { let doc = self.doc; if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES { diff --git a/crates/doc/src/color_mask.rs b/crates/doc/src/color_mask.rs new file mode 100644 index 0000000000..8905d6fe60 --- /dev/null +++ b/crates/doc/src/color_mask.rs @@ -0,0 +1,197 @@ +//! Image Tools › Color Mask: colors of an image object that are hidden while its pixels stay as +//! they are. +//! +//! A masked image is an ordinary image ([`NodeKind::Image`]) with a [`ColorMask`] in its extras +//! ([`crate::node::NodeExtras::color_mask`]). The record holds the mask's settings and the key of +//! the image's pixels with the hidden colors made clear ([`ColorMask::key`]), made by the engine +//! from the pixels named by [`ColorMask::from`]. The image's own key keeps naming its own pixels, +//! so removing the mask gives them back. While the image's key is [`ColorMask::from`], it is drawn +//! and output with the masked pixels ([`Document::shown_image`]); when another key replaced it +//! (a link updated, the image cropped), it shows its own pixels until the engine makes the masked +//! pixels again. +//! +//! The concept is that of PDF's color key masking (ISO 32000-1, 8.9.6.4): samples in the chosen +//! colors are not painted and what is behind the image shows through. Which colors match, and how +//! near ones fade out, are VectorCraft's own rules. + +use std::borrow::Cow; + +use serde::{Deserialize, Serialize}; + +use crate::{Document, ImageObject, Node, NodeKind}; + +/// Where a color mask's colors come from. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum MaskBackground { + /// The most common color along the image's edges. + #[default] + Edges, + /// The average of the image's corner pixels that are not clear. + Corners, + /// The colors in [`ColorMask::colors`]. + Colors, +} + +/// How near a color must be to a masked one. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum MaskMatch { + /// The RGB distance, as a percentage of the largest one. + #[default] + Distance, + /// The largest difference on one of red, green and blue, as a percentage of a channel's range. + Channels, +} + +/// The colors an image object hides (see the module docs). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ColorMask { + /// Key into [`Document::images`]: the pixels of [`Self::from`] with the hidden colors made + /// clear. Named `key` in the file, so the file keeps those pixels with the document. + pub key: String, + /// The image's own key when the masked pixels were made. + pub from: String, + #[serde(default)] + pub background: MaskBackground, + /// The hidden colors (8-bit RGB) with [`MaskBackground::Colors`]. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub colors: Vec<[u8; 3]>, + /// Only the matching pixels that reach in from an edge are hidden. A record without it reads + /// as `true`, the command's default. + #[serde(default = "default_contiguous")] + pub contiguous: bool, + #[serde(default, rename = "match")] + pub measure: MaskMatch, + /// How near a color must be to be hidden, 0 to 100 (see [`MaskMatch`]). A record without it + /// reads as 10, the command's default. + #[serde(default = "default_percent")] + pub tolerance: f64, + /// The band past the tolerance over which pixels fade from hidden to shown, 0 to 100. A record + /// without it reads as 10, the command's default. + #[serde(default = "default_percent")] + pub softness: f64, +} + +fn default_contiguous() -> bool { + true +} + +fn default_percent() -> f64 { + 10.0 +} + +impl ColorMask { + /// Whether the masked pixels were made from the pixels of `im`. + pub fn made_for(&self, im: &ImageObject) -> bool { + im.pixels.is_none() && self.from == im.key + } +} + +impl Document { + /// Image `im` of node `n` as it is drawn and output. With a color mask whose masked pixels were + /// made from the image's own pixels and are in this document ([`ColorMask::made_for`]): a copy + /// that shows those pixels and links to no file, so an output that refers to a linked file + /// writes the masked pixels instead. Otherwise, and for a mask that hides nothing (its masked + /// pixels are the image's own), `im` itself. + pub fn shown_image<'a>(&self, n: &Node, im: &'a ImageObject) -> Cow<'a, ImageObject> { + match n.extras().color_mask.as_deref() { + Some(m) if m.key != im.key && m.made_for(im) && self.images.contains_key(&m.key) => { + Cow::Owned(ImageObject { key: m.key.clone(), link: None, ..im.clone() }) + } + _ => Cow::Borrowed(im), + } + } + + /// The color mask of image node `n`, if it has one. + pub fn color_mask_of(n: &Node) -> Option<&ColorMask> { + matches!(n.kind, NodeKind::Image(_)).then(|| n.extras().color_mask.as_deref()).flatten() + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use vectorcraft_geom::Affine; + + use super::*; + use crate::{ImageBlob, NodeId}; + + fn image(key: &str) -> ImageObject { + ImageObject { key: key.into(), width: 2, height: 2, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None } + } + + fn mask(key: &str, from: &str) -> ColorMask { + ColorMask { + key: key.into(), + from: from.into(), + background: MaskBackground::Colors, + colors: vec![[255, 255, 255]], + contiguous: false, + measure: MaskMatch::Distance, + tolerance: 10.0, + softness: 0.0, + } + } + + #[test] + fn a_masked_image_shows_its_masked_pixels_while_they_were_made_from_its_own() { + let mut d = Document::new(100.0, 100.0); + d.images.insert("own".into(), ImageBlob::png(vec![1])); + d.images.insert("masked".into(), ImageBlob::png(vec![2])); + let mut n = Node::new(NodeId(5), NodeKind::Image(Box::new(image("own")))); + let NodeKind::Image(im) = &n.kind else { unreachable_kind() }; + assert_eq!(d.shown_image(&n, im).key, "own", "no mask: its own pixels"); + n.extras_mut().color_mask = Some(Box::new(mask("masked", "own"))); + let NodeKind::Image(im) = &n.kind else { unreachable_kind() }; + assert_eq!(d.shown_image(&n, im).key, "masked"); + // Linked: the shown copy links to nothing, so outputs write the masked pixels. + let mut linked = (**im).clone(); + linked.link = Some(crate::LinkInfo::new("/a.png")); + assert_eq!(d.shown_image(&n, &linked).link, None); + // Made from other pixels: its own until they are made again. + assert_eq!(d.shown_image(&n, &image("other")).key, "other"); + // Masked pixels the document doesn't have: its own. + n.extras_mut().color_mask = Some(Box::new(mask("gone", "own"))); + let NodeKind::Image(im) = &n.kind else { unreachable_kind() }; + assert_eq!(d.shown_image(&n, im).key, "own"); + // Pixels an image holds itself are drawn as they are. + let own = ImageObject { pixels: Some(Arc::new(ImageBlob::png(vec![3]))), ..image("own") }; + n.extras_mut().color_mask = Some(Box::new(mask("masked", "own"))); + assert_eq!(d.shown_image(&n, &own).key, "own"); + // A mask that hides nothing (its masked pixels are the image's own): the image itself, so + // a linked image stays linked in outputs. + n.extras_mut().color_mask = Some(Box::new(mask("own", "own"))); + assert_eq!(d.shown_image(&n, &linked).link, linked.link); + } + + #[test] + fn a_mask_saves_and_reads_back_with_its_node() { + let mut n = Node::new(NodeId(5), NodeKind::Image(Box::new(image("own")))); + n.extras_mut().color_mask = Some(Box::new(mask("masked", "own"))); + let json = serde_json::to_value(&n).unwrap(); + assert_eq!(json["color_mask"]["key"], "masked", "the masked pixels' key is a `key` member: {json}"); + assert_eq!(json["color_mask"]["match"], "distance"); + let back: Node = serde_json::from_value(json).unwrap(); + assert_eq!(back, n); + // A node without one writes none. + let plain = Node::new(NodeId(6), NodeKind::Image(Box::new(image("own")))); + assert!(serde_json::to_value(&plain).unwrap().get("color_mask").is_none()); + } + + /// A record that leaves out settings reads them as the command's defaults: edge color, + /// contiguous, distance, tolerance and softness 10. + #[test] + fn a_record_without_settings_reads_the_defaults() { + let m: ColorMask = serde_json::from_value(serde_json::json!({"key": "masked", "from": "own"})).unwrap(); + assert_eq!( + (m.background, m.colors.len(), m.contiguous, m.measure, m.tolerance, m.softness), + (MaskBackground::Edges, 0, true, MaskMatch::Distance, 10.0, 10.0) + ); + } + + fn unreachable_kind() -> ! { + panic!("an image node") + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2a970f2686..3c4bcc20a5 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -11,6 +11,7 @@ pub mod blend; pub mod cancel; pub mod clipnest; pub mod cmyk; +pub mod color_mask; pub mod compound_shape; pub mod corners; pub mod depth; diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index d1eb20ed21..b4c0f9fdd8 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -1025,6 +1025,37 @@ mod tests { assert_eq!(m.locate_within(Point::new(30.0, 60.0), 3.0), m.locate(Point::new(30.0, 60.0))); } + /// A point on a mesh's outline locates on the edge it lies on, on all four sides alike, with no + /// tolerance; a point just outside does not, and a tolerance reaches only as far as it says. + /// A point that isn't finite locates nowhere. + #[test] + fn mesh_locate_takes_a_point_on_any_side_of_the_outline() { + for (rows, cols) in [(1, 1), (2, 3)] { + let m = + GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0) + .unwrap(); + let sides = [ + ("top", Point::new(30.0, 0.0), Vec2::new(0.0, -0.01)), + ("bottom", Point::new(30.0, 100.0), Vec2::new(0.0, 0.01)), + ("left", Point::new(0.0, 70.0), Vec2::new(-0.01, 0.0)), + ("right", Point::new(100.0, 70.0), Vec2::new(0.01, 0.0)), + ]; + for (side, p, out) in sides { + let (r, c, u, v) = m.locate(p).unwrap_or_else(|| panic!("{rows}×{cols} {side}: {p:?} is not located")); + assert!(r < m.rows as usize && c < m.cols as usize && (0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v), "{side}"); + assert!(m.eval(r, c, u, v).distance(p) < 1e-3, "{rows}×{cols} {side}: {:?}", m.eval(r, c, u, v)); + let mut e = m.clone(); + assert!(e.add_lines_at(p, 0.0).is_some(), "{rows}×{cols} {side}: no line at {p:?}"); + assert_eq!(m.locate(p + out), None, "{rows}×{cols} {side}: just outside"); + assert_eq!(m.locate_within(p + out * 100.0, 0.5), None, "{rows}×{cols} {side}: past the tolerance"); + assert!(m.locate_within(p + out * 100.0, 1.5).is_some(), "{rows}×{cols} {side}: within the tolerance"); + } + for p in [Point::new(f64::NAN, 0.0), Point::new(30.0, f64::INFINITY)] { + assert_eq!(m.locate_within(p, f64::INFINITY), None, "{p:?}"); + } + } + } + /// Corners all in CMYK mix in CMYK (the inks halfway), not in RGB. #[test] fn a_cmyk_mesh_mixes_its_inks() { diff --git a/crates/doc/src/live/expand.rs b/crates/doc/src/live/expand.rs index f4a601c7b5..b8309f675b 100644 --- a/crates/doc/src/live/expand.rs +++ b/crates/doc/src/live/expand.rs @@ -206,12 +206,14 @@ pub fn mesh_warp_cost(cells: usize) -> usize { /// that takes the triangle where `f` takes its corners (with `masked`, the image masked by the /// triangle instead; with `pixelated`, drawn without smoothing). Each piece reaches a little past /// its edges (at most half a point) so neighbors overlap and no seams show. Each piece keeps the -/// color `n` colorizes a grayscale image with. The result is a group with `n`'s id, name, +/// color `n` colorizes a grayscale image with, and `n`'s color mask. The result is a group with `n`'s id, name, /// transparency, opacity mask and appearance. pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, cells: usize, pixelated: bool, masked: bool) -> Node { let k = cells.max(1); // A grayscale image's fill color colorizes each piece; the group of pieces takes none. let colorize = n.extras().colorize.clone(); + // Each piece shows what the image shows: its color mask's masked pixels. + let color_mask = n.extras().color_mask.clone(); let (pw, ph) = (im.width as f64, im.height as f64); let at = |i: usize, j: usize| Point::new(pw * i as f64 / k as f64, ph * j as f64 / k as f64); let mut pieces = Vec::with_capacity(2 * k * k); @@ -236,6 +238,7 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() }))); image.extras_mut().pixelated = pixelated; image.extras_mut().colorize = colorize.clone(); + image.extras_mut().color_mask = color_mask.clone(); if masked { // Preserve Shape Using Transparency: the triangle is the piece's alpha (a // white opacity mask) instead of its clipping path. diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index be865e2769..d912479464 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -530,6 +530,10 @@ pub(super) const MAX_BORDER_LINES: usize = 256; /// The most rounds of new lines a mesh made from a path takes to keep its border on the outline. const MAX_BORDER_ROUNDS: usize = 64; +/// A point this close (in points) to a mesh's outline is on it, for [`GradientMesh::locate_within`] +/// with any tolerance. +const ON_OUTLINE: f64 = 1e-6; + /// An anchor whose directions in and out differ by more than this (radians) is a corner: a border /// edge that can't follow the outline takes a mesh line through its sharpest corner first. const SHARP_TURN: f64 = 0.01; @@ -1436,17 +1440,23 @@ impl GradientMesh { } /// As [`Self::locate`], and for a point outside the mesh within `tol` of its outline, the - /// patch and local (u, v) of the nearest point of the mesh's edge. + /// patch and local (u, v) of the nearest point of the mesh's edge. A point on the outline + /// (within [`ON_OUTLINE`]) locates on its edge on every side, with any `tol`. pub fn locate_within(&self, p: Point, tol: f64) -> Option<(usize, usize, f64, f64)> { - if !self.is_valid() { + if !self.is_valid() || !p.is_finite() { return None; } - let bp = self.outline().to_bezpath(); - if bp.winding(p) == 0 { + // A point on the outline takes the nearest point of the edge on every side: the nonzero + // winding number counts a point on some edges as outside (a rectangle's bottom and right + // edges) and on the others as inside. + if let Some((_, r, c, u, v)) = self.nearest_edge(p, ON_OUTLINE).filter(|e| e.0 <= ON_OUTLINE * ON_OUTLINE) { + return Some((r, c, u, v)); + } + if self.outline().to_bezpath().winding(p) == 0 { if tol.is_nan() || tol <= 0.0 { return None; } - return self.nearest_edge(p).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v)); + return self.nearest_edge(p, tol).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v)); } const N: usize = 16; let mut best = (f64::INFINITY, 0, 0, 0.0, 0.0); @@ -1484,12 +1494,20 @@ impl GradientMesh { } /// The point of the mesh's outer edge nearest `p`: its squared distance from `p`, and its - /// boundary patch and local (u, v). - fn nearest_edge(&self, p: Point) -> Option<(f64, usize, usize, f64, f64)> { + /// boundary patch and local (u, v). Edges whose control points all lie farther than `within` + /// from `p` are skipped, so `None` means no edge is within `within`. + fn nearest_edge(&self, p: Point, within: f64) -> Option<(f64, usize, usize, f64, f64)> { use vectorcraft_geom::kurbo::ParamCurveNearest; let (rows, cols) = (self.rows as usize, self.cols as usize); let mut best: Option<(f64, usize, usize, f64, f64)> = None; let mut take = |e: CubicBez, at: (usize, usize, Option, Option)| { + // The edge lies inside its control points' box, so a box farther than `within` holds + // no point of the edge within it. + let b = Rect::from_points(e.p0, e.p1).union_pt(e.p2).union_pt(e.p3); + let (dx, dy) = ((b.x0 - p.x).max(p.x - b.x1).max(0.0), (b.y0 - p.y).max(p.y - b.y1).max(0.0)); + if dx * dx + dy * dy > within * within { + return; + } let n = e.nearest(p, 1e-9); if best.is_none_or(|b| n.distance_sq < b.0) { let (r, c, u, v) = at; diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 12d233ba37..7ff6cdeea2 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -261,6 +261,10 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> u b += ALLOC + size_of::(); b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective); b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize); + b += e + .color_mask + .as_deref() + .map_or(0, |m| ALLOC + size_of::() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3); b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::() + json_bytes(t)); b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::() + path_bytes(a)); if e.intertwine_tiers.capacity() > 0 { diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 6865ff7e6c..7b130bf395 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -72,6 +72,9 @@ pub struct NodeExtras { /// Transform panel › Align to Pixel Grid: the path's or compound path's horizontal and vertical /// segments stay on the pixel grid when it is transformed. pub pixel_aligned: bool, + /// Image Tools › Color Mask: the colors an image hides while its pixels stay as they are + /// ([`crate::color_mask`]). + pub color_mask: Option>, } /// No extras: what [`Node::extras`] gives for a node without any. @@ -99,6 +102,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { symbol_overrides: Vec::new(), envelope_edit_margin: None, pixel_aligned: false, + color_mask: None, }; /// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 2722e7bee0..34d8e99c53 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -55,6 +55,7 @@ impl Serialize for Node { e.symbol_overrides.is_empty(), e.envelope_edit_margin.is_none(), is_default(&e.pixel_aligned), + e.color_mask.is_none(), ]; let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; let mut skip = skips.into_iter(); @@ -98,6 +99,7 @@ impl Serialize for Node { field!("symbol_overrides", &e.symbol_overrides); field!("envelope_edit_margin", &e.envelope_edit_margin); field!("pixel_aligned", &e.pixel_aligned); + field!("color_mask", &e.color_mask); st.end() } } @@ -241,6 +243,8 @@ pub(super) struct NodeWire { envelope_edit_margin: Option<[f32; 4]>, #[serde(default)] pixel_aligned: bool, + #[serde(default)] + color_mask: Option>, } impl From for Node { @@ -269,6 +273,7 @@ impl From for Node { symbol_overrides: w.symbol_overrides, envelope_edit_margin: w.envelope_edit_margin, pixel_aligned: w.pixel_aligned, + color_mask: w.color_mask, }; Node { id: w.id, diff --git a/crates/doc/src/pixels.rs b/crates/doc/src/pixels.rs index 7edf64eb5e..0812095826 100644 --- a/crates/doc/src/pixels.rs +++ b/crates/doc/src/pixels.rs @@ -11,9 +11,9 @@ use crate::ImageBlob; /// address and aborts when an allocation fails, so it keeps the decoder's own 512 MB. pub const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 }; -/// A box of an image to sample, in 0 to 1 units of its width and height (`None`: all of it), and -/// the pixel centres to take from it ([`ImageBlob::sample_pixels`]). -pub type PixelPick<'a> = (Option<[f64; 4]>, &'a dyn Fn(f64, f64) -> bool); +/// A box of an image to sample, in 0 to 1 units of its width and height (`None`: all of it), the +/// pixels to sample from it at most, and the pixel centres to take ([`ImageBlob::sample_pixels`]). +pub type PixelPick<'a> = (Option<[f64; 4]>, usize, &'a dyn Fn(f64, f64) -> bool); /// The pixels of encoded image `bytes` as RGBA; `None` when they can't be decoded, would take /// more than `max` bytes as RGBA, or need more than `max` bytes to decode. The size is read from @@ -65,13 +65,13 @@ impl ImageBlob { Some(Self::png(png)) } - /// For each of `picks`, at most `budget` of the image's pixels (at least one), spread evenly + /// For each of `picks`, at most its budget of the image's pixels (at least one), spread evenly /// in rows and columns over the pick's box (`[u0, v0, u1, v1]`, where 0 to 1 spans the /// image's width and height from the top left; clipped to the image; `None`: the whole image), /// as straight RGBA. Only pixels whose centres the pick's function takes (in the same 0 to 1 - /// units) are given. The image is decoded once for all the picks. `None` when it can't be - /// decoded within [`MAX_RASTER_ALLOC`]. - pub fn sample_pixels(&self, picks: &[PixelPick<'_>], budget: usize) -> Option>> { + /// units) are given, and the function is called once for each pixel sampled. The image is + /// decoded once for all the picks. `None` when it can't be decoded within [`MAX_RASTER_ALLOC`]. + pub fn sample_pixels(&self, picks: &[PixelPick<'_>]) -> Option>> { let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?; let (w, h) = img.dimensions(); let (fw, fh) = (f64::from(w), f64::from(h)); @@ -79,7 +79,7 @@ impl ImageBlob { let (a, b) = (a.min(b), a.max(b)); ((a * n).floor().clamp(0.0, n) as u32, (b * n).ceil().clamp(0.0, n) as u32) }; - let sample = |area: Option<[f64; 4]>, keep: &dyn Fn(f64, f64) -> bool| { + let sample = |area: Option<[f64; 4]>, budget: usize, keep: &dyn Fn(f64, f64) -> bool| { let [u0, v0, u1, v1] = area.unwrap_or([0.0, 0.0, 1.0, 1.0]); let (x0, x1) = span(u0, u1, fw); let (y0, y1) = span(v0, v1, fh); @@ -105,7 +105,7 @@ impl ImageBlob { } out }; - Some(picks.iter().map(|(area, keep)| sample(*area, *keep)).collect()) + Some(picks.iter().map(|(area, budget, keep)| sample(*area, *budget, *keep)).collect()) } /// The image as a grayscale PNG: `f` gives each pixel's gray level from its (straight) RGB, and @@ -331,7 +331,7 @@ mod tests { let (r, b) = ([255, 0, 0, 255], [0, 0, 255, 255]); let img = blob(&[r, r, b, b, r, r, b, b], 4, 2); let any = |_: f64, _: f64| true; - let one = |b: &ImageBlob, area: Option<[f64; 4]>, budget: usize| b.sample_pixels(&[(area, &any)], budget).unwrap().remove(0); + let one = |b: &ImageBlob, area: Option<[f64; 4]>, budget: usize| b.sample_pixels(&[(area, budget, &any)]).unwrap().remove(0); assert_eq!(one(&img, None, 100).len(), 8, "the budget covers every pixel"); assert_eq!(one(&img, Some([0.5, 0.0, 1.0, 1.0]), 100), vec![b; 4], "the right half"); assert_eq!(one(&img, Some([1.0, 1.0, 0.5, 0.0]), 100), vec![b; 4], "a box given backwards"); @@ -339,13 +339,15 @@ mod tests { assert_eq!(one(&img, None, 2).len(), 2, "every second pixel of every second row"); assert_eq!(one(&img, None, 0), vec![r], "a budget of 0 counts as 1"); let left = |u: f64, _: f64| u < 0.5; - let both = img.sample_pixels(&[(None, &left), (Some([0.5, 0.0, 1.0, 1.0]), &any)], 100).unwrap(); + let both = img.sample_pixels(&[(None, 100, &left), (Some([0.5, 0.0, 1.0, 1.0]), 100, &any)]).unwrap(); assert_eq!(both, vec![vec![r; 4], vec![b; 4]], "several picks, each with the centres its function takes"); + let sizes: Vec = img.sample_pixels(&[(None, 2, &any), (None, 100, &any)]).unwrap().iter().map(Vec::len).collect(); + assert_eq!(sizes, [2, 8], "each pick keeps to its own budget"); // A narrow image keeps to the budget too. let tall = blob(&vec![r; 5000], 1, 5000); let n = one(&tall, None, 100).len(); assert!((50..=100).contains(&n), "{n} pixels"); - assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, &any)], 100).is_none()); + assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, 100, &any)]).is_none()); } /// A GIF whose `w` × `h` screen holds one opaque red pixel at the top left. The file holds no diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index 33eccb178a..86f7f6134c 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -517,7 +517,12 @@ fn rename(n: &mut Node, prefix: &str) { paint(&mut r.style.stroke); } } - NodeKind::Image(im) => im.key = format!("{prefix}{}", im.key), + NodeKind::Image(im) => { + im.key = format!("{prefix}{}", im.key); + if let Some(m) = n.extras.0.as_deref_mut().and_then(|e| e.color_mask.as_deref_mut()) { + (m.key, m.from) = (format!("{prefix}{}", m.key), format!("{prefix}{}", m.from)); + } + } NodeKind::PlacedDocument(p) => p.key = format!("{prefix}{}", p.key), NodeKind::SymbolInstance { symbol, .. } => *symbol = format!("{prefix}{symbol}"), _ => {} @@ -681,6 +686,30 @@ mod tests { Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0))) } + /// A color-masked image in a placed document's art keeps its masked pixels under the prefixed + /// names its resources get. + #[test] + fn a_color_mask_takes_the_prefixed_image_names() { + let im = + ImageObject { key: "own".into(), width: 2, height: 2, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let mut n = Node::new(NodeId(7), NodeKind::Image(Box::new(im))); + n.extras_mut().color_mask = Some(Box::new(crate::color_mask::ColorMask { + key: "masked".into(), + from: "own".into(), + background: Default::default(), + colors: vec![], + contiguous: true, + measure: Default::default(), + tolerance: 10.0, + softness: 10.0, + })); + rename(&mut n, "p:"); + let NodeKind::Image(im) = &n.kind else { panic!("an image") }; + let m = Document::color_mask_of(&n).unwrap(); + assert_eq!((im.key.as_str(), m.key.as_str(), m.from.as_str()), ("p:own", "p:masked", "p:own")); + assert!(m.made_for(im)); + } + #[test] fn round_trips_through_json() { let n = Node::new(NodeId(3), NodeKind::PlacedDocument(Box::new(placed("doc1-1")))); diff --git a/crates/effects/src/adjust.rs b/crates/effects/src/adjust.rs index c345136255..4193b085ef 100644 --- a/crates/effects/src/adjust.rs +++ b/crates/effects/src/adjust.rs @@ -435,11 +435,19 @@ impl ColorVisitor for Live<'_, '_> { /// adjustments of an object `n` is the art of) on everything it paints. The adjustment effects /// are gone from the result; embedded images take the keys `images` gives. `swatches` tells the /// document's global and spot swatches apart ([`crate::addons::duotone::swatch_kind`]). -pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images: &mut ImageHook<'_>) -> Option { +/// `has_image` tells whether the document holds an image: an image whose color mask's pixels are +/// missing is recoloured from its own pixels, as it is drawn without the adjustment. +pub fn adjust( + n: &Node, + outer: Option<&ColorMap>, + swatches: &SwatchKinds, + images: &mut ImageHook<'_>, + has_image: &dyn Fn(&str) -> bool, +) -> Option { let mut m: Option = None; if let Some(ch) = n.children() { for (i, c) in ch.iter().enumerate() { - if let Some(new) = adjust(c, None, swatches, images) + if let Some(new) = adjust(c, None, swatches, images, has_image) && let Some(slot) = m.get_or_insert_with(|| n.clone()).children_mut().and_then(|ch| ch.get_mut(i)) { *slot = Arc::new(new); @@ -462,11 +470,57 @@ pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images if let Some(map) = map { let mm = m.get_or_insert_with(|| n.clone()); mm.appearance.effects.retain(|e| !is_adjustment(&e.id)); + show_color_masks(mm, has_image); recolor_node(mm, Reach::ALL, &mut Live { map: &map, swatches, images }); } m } +/// Whether `n` is an image that [`recolor_node`] recolours (embedded, not colorized, without +/// pixels of its own) with a color mask made from its pixels. +fn recoloured_with_mask(n: &Node) -> bool { + match (&n.kind, Document::color_mask_of(n)) { + (NodeKind::Image(im), Some(m)) => im.link.is_none() && n.extras().colorize.is_none() && m.made_for(im), + _ => false, + } +} + +/// Whether `n` is or holds an image [`recoloured_with_mask`] counts. +fn holds_recoloured_with_mask(n: &Node) -> bool { + recoloured_with_mask(n) || n.children().is_some_and(|ch| ch.iter().any(|c| holds_recoloured_with_mask(c))) +} + +/// Give each image in `n` that [`recoloured_with_mask`] counts its masked pixels as its own, +/// without the mask, so [`recolor_node`] recolours the pixels it shows and the colors the mask +/// hides stay hidden. An image whose masked pixels the document does not hold (`has_image`) is +/// drawn from its own pixels ([`Document::shown_image`]): it keeps its key and loses the mask, so +/// the recoloured copy is drawn the same way. +fn show_color_masks(n: &mut Node, has_image: &dyn Fn(&str) -> bool) { + if recoloured_with_mask(n) + && let Some(masked) = Document::color_mask_of(n).map(|m| m.key.clone()) + { + if let NodeKind::Image(im) = &mut n.kind + && has_image(&masked) + { + im.key = masked; + } + n.extras_mut().color_mask = None; + } + for c in n.children_mut().into_iter().flatten() { + if holds_recoloured_with_mask(c) { + show_color_masks(Arc::make_mut(c), has_image); + } + } +} + +/// The keys of the masked pixels of the color masks in `n` and its members. +fn color_mask_keys<'a>(n: &'a Node, out: &mut Vec<&'a str>) { + out.extend(Document::color_mask_of(n).map(|m| m.key.as_str())); + for c in n.children().into_iter().flatten() { + color_mask_keys(c, out); + } +} + /// [`adjust`] for export and Expand Appearance: recoloured embedded images become new images in /// `d` (named by their content), and a symbol instance stands for its symbol's art: `symbol_art` /// when given, otherwise the symbol's art with the instance's own appearance changes. @@ -482,13 +536,16 @@ pub fn adjust_in_document(d: &mut Document, n: &Node, symbol_art: Option) _ => n, }; let kinds = crate::addons::duotone::swatch_kinds(d); + let mut masked = vec![]; + color_mask_keys(src, &mut masked); + masked.retain(|k| d.images.contains_key(*k)); let mut hook = |key: &str, map: &ColorMap| -> Option { let blob = d.images.get(key)?.map_rgb(|rgb| map.apply_rgb8(rgb))?; let k = blob.content_key(); d.images.entry(k.clone()).or_insert(blob); Some(k) }; - adjust(src, None, &|name| kinds.get(name).copied(), &mut hook) + adjust(src, None, &|name| kinds.get(name).copied(), &mut hook, &|key| masked.contains(&key)) } #[cfg(test)] @@ -551,17 +608,17 @@ mod tests { let mut g = Node::group(NodeId(1), vec![leaf(2), leaf(3)]); g.appearance.effects.push(Effect { id: "adjust.hueSaturation".into(), params: json!({"hue": 120}), visible: true }); assert!(has_adjustment(&g)); - let out = adjust(&g, None, &|_| None, &mut |_, _| None).unwrap(); + let out = adjust(&g, None, &|_| None, &mut |_, _| None, &|_| true).unwrap(); assert!(out.appearance.effects.is_empty()); for c in out.children().unwrap() { assert_eq!(c.appearance.fill_paint().color().unwrap().to_hex(), "#00ff00"); } // A hidden effect does nothing; a stroke's own effect recolours just that stroke. g.appearance.effects[0].visible = false; - assert!(!has_adjustment(&g) && adjust(&g, None, &|_| None, &mut |_, _| None).is_none()); + assert!(!has_adjustment(&g) && adjust(&g, None, &|_| None, &mut |_, _| None, &|_| true).is_none()); let mut p = Node::path(NodeId(5), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); p.appearance.items[1].effects_mut().push(Effect { id: "adjust.levels".into(), params: json!({"outputBlack": 255}), visible: true }); - let out = adjust(&p, None, &|_| None, &mut |_, _| None).unwrap(); + let out = adjust(&p, None, &|_| None, &mut |_, _| None, &|_| true).unwrap(); assert_eq!(out.appearance.items[1].paint().color().unwrap().to_hex(), "#ffffff"); assert_eq!(out.appearance.items[0].paint(), p.appearance.items[0].paint()); assert!(out.appearance.items[1].effects().is_empty()); @@ -576,7 +633,7 @@ mod tests { let fill = Appearance::basic(Paint::Gradient(Box::new(gp)), Paint::None, 0.0); let mut p = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), fill); p.appearance.effects.push(Effect { id: "adjust.hueSaturation".into(), params: json!({"hue": 120}), visible: true }); - let out = adjust(&p, None, &|_| None, &mut |_, _| None).unwrap(); + let out = adjust(&p, None, &|_| None, &mut |_, _| None, &|_| true).unwrap(); let Paint::Gradient(g) = out.appearance.fill_paint() else { panic!("a gradient fill") }; // The points are what a freeform gradient draws from, not its stops. let hexes: Vec = g.freeform.as_ref().unwrap().points.iter().map(|p| p.color.to_hex()).collect(); diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 55a904d02c..2b4953d151 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -104,6 +104,15 @@ fn path_kind(d: &mut Document, path: PathData, rule: FillRule) -> NodeKind { } } +thread_local! { + /// How many symbol instances deep [`bake_node`] is baking, through the art of instances whose + /// effects reshape it. + static INSTANCE_DEPTH: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The objects of symbol art that [`bake_document`] has baked for instances inside the art of + /// other instances, counted against [`crate::SYMBOL_ART_MAX_NODES`]. + static NESTED_NODES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// `n` with its geometry effects evaluated (`None` = unchanged). fn bake_node(d: &mut Document, n: &Node) -> Option { // A cancelled export leaves the rest of the document as it is: the caller drops the result. @@ -143,8 +152,27 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { } _ => None, }; + // Instances baked inside the art of others stop at the depth limit, or once their art + // passes the objects one export bakes that way: an instance of a symbol whose art holds + // instances of itself is kept as it is there. + let instance = matches!(n.kind, NodeKind::SymbolInstance { .. }); + if instance && INSTANCE_DEPTH.with(|c| c.get()) > 0 { + let count = symbol.as_ref().map_or(0, |a| a.count() as u64); + let spent = NESTED_NODES.with(|c| c.get()).saturating_add(count); + if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent > crate::SYMBOL_ART_MAX_NODES { + return None; + } + NESTED_NODES.with(|c| c.set(spent)); + } let m = reshape(Some(d), n, symbol.as_ref())?; - return Some(bake_node(d, &m).unwrap_or(m)); + if instance { + INSTANCE_DEPTH.with(|c| c.set(c.get() + 1)); + } + let baked = bake_node(d, &m); + if instance { + INSTANCE_DEPTH.with(|c| c.set(c.get() - 1)); + } + return Some(baked.unwrap_or(m)); } // A path whose Transform effect copies it with a gradient, or scales its strokes or moves its // patterns: each copy an object of its own, so its gradient fits it rather than spanning @@ -531,7 +559,9 @@ fn hoist_transparency(mut p: Node) -> Node { } /// [`expand_leaf`] every path and compound path in `n` (art made for Expand Appearance, such as a -/// group's own fills and strokes or outlined type), in place. +/// group's own fills and strokes or outlined type), in place. A group or layer in it with an +/// appearance of its own ([`crate::has_container_appearance`]) is first made into the art that +/// appearance paints ([`crate::evaluate_container`]). pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) { if matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) { if let Some(m) = expand_leaf(d, n, stroke_art) { @@ -539,6 +569,11 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) { } return; } + if crate::has_container_appearance(n) + && let Some(m) = crate::evaluate_container(Some(&*d), n) + { + *n = m; + } for c in n.children_mut().into_iter().flatten() { expand_art(d, Arc::make_mut(c), stroke_art); } @@ -661,6 +696,7 @@ pub fn bake_document(doc: &Document) -> Option { }; } let mut d = placed.into_owned(); + NESTED_NODES.with(|c| c.set(0)); let layers = d.layers.clone(); d.layers = layers.iter().map(|l| bake_node(&mut d, l).map(Arc::new).unwrap_or_else(|| l.clone())).collect(); Some(d) diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 16c271dca0..77977c24d1 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -130,19 +130,142 @@ pub fn has_painted_effects(n: &Node) -> bool { } /// Is `n` type without inline graphics that has a fill or stroke of its own that paints and has a -/// visible geometry effect, or an image with a fill or stroke of its own that paints a shape -/// ([`image_rows`])? On type, such an effect reshapes the whole outline that its fill or stroke -/// paints ([`outline_text`], which leaves inline graphics out). +/// visible geometry effect, an image with a fill or stroke of its own that paints a shape +/// ([`image_rows`]), or a symbol instance whose active fill or stroke has a visible geometry effect +/// ([`active_fill`], [`active_stroke`])? On type, such an effect reshapes the whole outline that its +/// fill or stroke paints ([`outline_text`], which leaves inline graphics out). On a symbol +/// instance, it reshapes the fills or strokes of the art it places ([`add_instance_row_effects`]). pub fn has_item_geometry(n: &Node) -> bool { match &n.kind { NodeKind::Text(t) => { t.runs.iter().all(|r| r.inline.is_none()) && n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) } NodeKind::Image(_) => n.appearance.items.iter().any(shapes_image), + NodeKind::SymbolInstance { .. } => { + active_fill(n).is_some_and(|f| crate::has_geometry(&f.effects)) || active_stroke(n).is_some_and(|s| crate::has_geometry(&s.effects)) + } _ => false, } } +/// The fill of symbol instance `n` whose effects its art takes: its topmost fill, the one that +/// stains the art, when it is visible and its opacity is above 0. A lower fill's effects do not +/// reach the art. +fn active_fill(n: &Node) -> Option<&vectorcraft_doc::FillLayer> { + n.appearance.fill().filter(|f| f.visible && f.opacity > 0.0) +} + +/// The stroke of symbol instance `n` whose effects its art takes: its topmost stroke, when it is +/// visible and its opacity is above 0. +fn active_stroke(n: &Node) -> Option<&vectorcraft_doc::StrokeLayer> { + n.appearance.stroke().filter(|s| s.visible && s.opacity > 0.0) +} + +/// The visible geometry effects in `fx`, in order. +fn geometry_of(fx: &[Effect]) -> Vec { + fx.iter().filter(|e| e.visible && is_geometry(&e.id)).cloned().collect() +} + +/// `art`, the art symbol instance `n` places, with the visible geometry effects of `n`'s active +/// fill added after the effects of every fill in it that paints, and those of its active stroke +/// after the effects of every stroke in it that paints ([`active_fill`], [`active_stroke`]). Each +/// fill or stroke keeps its paint, and the others keep their shapes. Live objects in it that are +/// reached are evaluated first (with the symbols of `doc`), so the effects reshape what they draw. +/// Clip groups' clipping paths, guides and the art of opacity masks keep their shapes. A symbol +/// instance in the art takes the effects on its own active fill or stroke, or on a new fill or +/// stroke without paint when it has none, and passes them on to its own art in turn; an instance +/// of a symbol whose art (in `doc`) holds an instance of `n`'s symbol, at any depth, keeps its +/// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no +/// instance in the art takes them. +fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { + let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; + let fill = active_fill(n).map_or(vec![], |f| geometry_of(&f.effects)); + let stroke = active_stroke(n).map_or(vec![], |s| geometry_of(&s.effects)); + if !fill.is_empty() || !stroke.is_empty() { + add_row_effects(doc, symbol, art, &fill, &stroke); + } +} + +/// Does the art of the symbol named `from` in `doc` hold an instance of the symbol named `to`, at +/// any depth of the symbols placed in it? `seen` holds the symbols already looked into. +fn places_symbol(doc: &Document, from: &str, to: &str, seen: &mut HashSet) -> bool { + if !seen.insert(from.to_string()) { + return false; + } + let Some(sym) = doc.symbols.iter().find(|s| s.name == from) else { return false }; + let mut names = vec![]; + sym.art.walk(&mut |c| { + if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { + names.push(symbol.clone()); + } + }); + names.iter().any(|name| name == to || places_symbol(doc, name, to, seen)) +} + +/// [`add_instance_row_effects`] of `fill` and `stroke` to `n` and the art in it, the art of an +/// instance of the symbol named `outer`. +fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect]) { + match &n.kind { + NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => return, + NodeKind::SymbolInstance { symbol, .. } => { + if let Some(d) = doc + && !places_symbol(d, symbol, outer, &mut HashSet::new()) + { + add_to_instance(n, fill, stroke); + } + return; + } + _ if vectorcraft_doc::live::is_live(n) => *n = evaluated(doc, n), + _ => {} + } + let takes = |i: &AppearanceItem| { + crate::paints(i) && !matches!(i, AppearanceItem::Fill(_) if fill.is_empty()) && !matches!(i, AppearanceItem::Stroke(_) if stroke.is_empty()) + }; + if n.appearance.items.iter().any(takes) { + for item in n.appearance.items.iter_mut().filter(|i| takes(i)) { + let fx = if matches!(item, AppearanceItem::Fill(_)) { fill } else { stroke }; + item.effects_mut().extend_from_slice(fx); + } + } + // A compound path paints its members with its own fills and strokes. + if matches!(n.kind, NodeKind::Compound { .. }) { + return; + } + // A clip group's first member is its clipping path, whatever its kind. + let clips = n.clips(); + for (i, c) in n.children_mut().into_iter().flatten().enumerate() { + if !(clips && i == 0) { + add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke); + } + } +} + +/// Add `fill` to the effects of symbol instance `n`'s active fill and `stroke` to those of its +/// active stroke ([`active_fill`], [`active_stroke`]); without one, to a new topmost fill or stroke +/// without paint, which neither stains nor strokes its art. +fn add_to_instance(n: &mut Node, fill: &[Effect], stroke: &[Effect]) { + if !fill.is_empty() { + match n.appearance.fill_mut().filter(|f| f.visible && f.opacity > 0.0) { + Some(f) => f.effects.extend_from_slice(fill), + None => { + let mut f = vectorcraft_doc::FillLayer::new(vectorcraft_doc::color::Paint::None); + f.effects = fill.to_vec(); + n.appearance.items.push(AppearanceItem::Fill(f)); + } + } + } + if !stroke.is_empty() { + match n.appearance.stroke_mut().filter(|s| s.visible && s.opacity > 0.0) { + Some(s) => s.effects.extend_from_slice(stroke), + None => { + let mut s = vectorcraft_doc::StrokeLayer::new(vectorcraft_doc::color::Paint::None, 0.0); + s.effects = stroke.to_vec(); + n.appearance.items.push(AppearanceItem::Stroke(s)); + } + } + } +} + /// Does effect `e` give an image's fill or stroke a shape to paint (a visible Convert to Shape or /// Outline Object)? fn gives_shape(e: &Effect) -> bool { @@ -302,7 +425,9 @@ fn with_id(art: &Node, id: NodeId) -> Node { /// `n` as plain art that geometry effects can reshape, without its transparency and object /// effects: type outlined ([`outline_text`]), live objects evaluated (type inside them outlined), /// a symbol instance as `symbol_art` (the symbol's art, stained as the caller draws it) placed by -/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them). +/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them), its +/// fills and strokes carrying the geometry effects of the instance's active fill and stroke +/// ([`add_instance_row_effects`]). /// `None` for other kinds (images, paths, containers), and for an instance whose art placed /// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of /// `doc`'s symbols that its instances show toward its instance budget. @@ -351,6 +476,9 @@ fn outline_art_with( _ => return None, }; outline_nested_text(paint_doc, &mut art, false); + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + add_instance_row_effects(symbols, n, &mut art); + } art.opacity = 1.0; art.blend = Default::default(); art.isolate = false; @@ -497,8 +625,10 @@ pub fn reshape(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> O /// `n` (see [`needs_outline`], or a path with [`has_transform_art`]) as plain art for Expand /// Appearance: [`reshape`]d when it has -/// geometry effects, else type with fills or strokes of its own outlined, or an image with fills -/// or strokes of its own that paint a shape, in the same form. `None` when it has none of these. +/// geometry effects, else type with fills or strokes of its own outlined, an image with fills or +/// strokes of its own that paint a shape, or a symbol instance's art reshaped by the geometry +/// effects of its active fill or stroke ([`has_item_geometry`]), in the same form. `None` when it +/// has none of these. pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { // A path whose Transform effect copies it, or scales its strokes or moves its patterns: each // copy an object of its own with the path's fills and strokes, the copies of each Transform @@ -552,12 +682,13 @@ fn as_art_opts( NodeKind::Image(im) => { let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf); let mut image = Node::new(n.id, n.kind.clone()); - // Its pixels draw as the image's do: colorized by a grayscale image's fill color, and - // smoothed or not. + // Its pixels draw as the image's do: colorized by a grayscale image's fill color, + // smoothed or not, and with its color mask's masked pixels. { let mut e = image.extras_mut(); e.colorize = n.extras().colorize.clone(); e.pixelated = n.extras().pixelated; + e.color_mask = n.extras().color_mask.clone(); } let clipped = || { let mut clip = Node::path(n.id, frame.clone(), Appearance::default()); diff --git a/crates/effects/src/solids/source.rs b/crates/effects/src/solids/source.rs index 585f23bd6b..d71b2993af 100644 --- a/crates/effects/src/solids/source.rs +++ b/crates/effects/src/solids/source.rs @@ -8,7 +8,7 @@ use std::borrow::Cow; use std::sync::Arc; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind}; -use vectorcraft_geom::{FillRule, PathData, Rect}; +use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath}; use vectorcraft_pathops as po; use super::{MAX_MEMBERS, Scope, geometry, is_container, members, profile, region, reshape_members, solid_paints}; @@ -24,6 +24,19 @@ const MAX_DEPTH: usize = 64; /// many steps. pub(super) const MAX_WORK: usize = 1 << 18; +/// The most times resolving one 3D effect's art may cut an image's frame to a clipping path to +/// learn whether the clip shows any of it ([`Resolver::hidden`]). +pub(super) const MAX_IMAGE_CUTS: usize = 1024; + +/// The area, in square points, under which what a clip shows of an image's frame counts as nothing: +/// the sliver left where the frame only touches the clipping path. +const SHOWN_AREA: f64 = 1e-9; + +/// The precision an image's frame is cut to a clipping path with: the cut drops pieces narrower +/// than this, so it is far below [`po::DEFAULT_PRECISION`], and a strip of the image much +/// narrower than a hundredth of a point still counts as shown. +const CUT_PRECISION: f64 = 1e-6; + /// The error for an image a 3D effect is asked to build from. pub(crate) fn image_refusal(label: &str) -> String { format!("{label} can't build a solid from an image: trace it first with Object › Image Trace › Make.") @@ -66,7 +79,7 @@ pub(crate) fn resolve_for<'a>(doc: Option<&Document>, n: &'a Node, label: &str, if !needs(n) { return Ok(Cow::Borrowed(n)); } - let mut r = Resolver { doc, label, every_fill, leaves: 0, work: 0, shown: None }; + let mut r = Resolver { doc, label, every_fill, leaves: 0, work: 0, cuts: 0, shown: None }; let children = r.content(n, 0); #[cfg(test)] WORK.with(|w| w.set(r.work)); @@ -90,8 +103,18 @@ struct Resolver<'a> { leaves: usize, /// The objects visited or made so far, counted against [`MAX_WORK`]. work: usize, - /// Inside clipping groups, the box of what their clipping paths show together. - shown: Option, + /// The image frames cut to clipping paths so far, counted against [`MAX_IMAGE_CUTS`]. + cuts: usize, + /// Inside clipping groups, what their clipping paths show together. + shown: Option, +} + +/// The clipping paths around the art being listed, outermost first, with the box of what they +/// show together. +#[derive(Clone)] +struct Shown { + bounds: Rect, + clips: Vec>, } impl Resolver<'_> { @@ -111,15 +134,52 @@ impl Resolver<'_> { /// `f` run on the art of `c`. The effects of an object or group can move its art into a clip, /// so inside one with effects no image is left out for lying outside the clip ([`Self::shown`]). fn inside(&mut self, c: &Node, f: impl FnOnce(&mut Self) -> Result) -> Result { - let outer = self.shown; - if has_effects(c) { - self.shown = None; + if !has_effects(c) { + return f(self); } + let outer = self.shown.take(); let out = f(self); self.shown = outer; out } + /// Does the plain image `c` lie wholly outside what the clips around it show together, each + /// clipping path with its own fill rule? Its frame, the pixel rectangle as its transform places + /// it, is cut to each clip in turn until nothing is left. An error when a cut fails or the cuts + /// pass [`MAX_IMAGE_CUTS`]: the image may show, so it can't be left out. + fn hidden(&mut self, c: &Node) -> Result { + let Some(shown) = &self.shown else { return Ok(false) }; + let NodeKind::Image(im) = &c.kind else { return Ok(false) }; + let Some(b) = c.visual_bounds() else { return Ok(true) }; + if b.intersect(shown.bounds).area() <= 0.0 { + return Ok(true); + } + let (w, h) = (f64::from(im.width), f64::from(im.height)); + let corners = [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)].map(|(x, y)| im.xf * Point::new(x, y)); + if corners.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) { + return Err(image_refusal(self.label)); + } + let clips = shown.clips.clone(); + let mut left = PathData::single(SubPath::polyline(&corners, true)); + for clip in clips { + let Some(here) = clip.0.bounds() else { return Ok(true) }; + if left.bounds().is_none_or(|l| l.intersect(here).area() <= 0.0) { + return Ok(true); + } + self.cuts += 1; + if self.cuts > MAX_IMAGE_CUTS { + return Err(self.too_much_work()); + } + self.spend(1)?; + left = + po::try_boolean(&left, FillRule::NonZero, &clip.0, clip.1, po::BoolOp::Intersect, CUT_PRECISION).map_err(|_| self.too_complex())?; + if left.subpaths.iter().all(|s| s.area().abs() <= SHOWN_AREA) { + return Ok(true); + } + } + Ok(false) + } + /// The art `n`, a symbol instance, a blend, a clipping group or layer, or a group holding one, /// shows, as the members of a plain group. fn content(&mut self, n: &Node, depth: usize) -> Result>, String> { @@ -162,11 +222,15 @@ impl Resolver<'_> { if clip_nested_past(first, MAX_DEPTH.saturating_sub(depth)) { return Err(self.too_deep()); } - let clip = clip_area(first); - // An image wholly outside every clip around it shows nothing and is left out. - let outer = self.shown; + let clip = Arc::new(clip_area(first)); + // An image wholly outside what the clips around it show together draws nothing and + // is left out. let here = clip.0.bounds().unwrap_or(Rect::ZERO); - self.shown = Some(outer.map_or(here, |o| o.intersect(here))); + let outer = self.shown.take(); + let mut inner_shown = outer.clone().unwrap_or(Shown { bounds: here, clips: vec![] }); + inner_shown.bounds = inner_shown.bounds.intersect(here); + inner_shown.clips.push(clip.clone()); + self.shown = Some(inner_shown); let listed = self.list(rest, depth + 1); self.shown = outer; let (inner, _) = listed?; @@ -198,8 +262,7 @@ impl Resolver<'_> { // Only an image with no effects or fills and strokes of its own is measured by its // frame; any other one may draw inside the clip. let plain = !has_effects(c) && c.appearance.items.iter().all(|i| !i.visible()); - let hidden = plain && self.shown.is_some_and(|k| c.visual_bounds().is_none_or(|b| b.intersect(k).area() <= 0.0)); - if hidden { + if plain && self.hidden(c)? { changed = true; continue; } diff --git a/crates/effects/src/solids/tests_sources.rs b/crates/effects/src/solids/tests_sources.rs index b2f6daf1c6..b7a9429fd9 100644 --- a/crates/effects/src/solids/tests_sources.rs +++ b/crates/effects/src/solids/tests_sources.rs @@ -317,6 +317,86 @@ fn images_are_refused_alone_and_in_a_group_with_image_trace_named() { } } +/// A clipping group: `art` inside a clipping path of `path` filled under `rule`. +fn shaped_clip_group(id: u64, path: PathData, rule: FillRule, art: Vec) -> Node { + let mut clipping = Node::path(NodeId(id + 1), path, Appearance::default()); + if let NodeKind::Path { clipping: c, rule: r, .. } = &mut clipping.kind { + *c = true; + *r = rule; + } + let children = std::iter::once(clipping).chain(art).map(Arc::new).collect(); + Node::new(NodeId(id), NodeKind::Group { children, clip: true }) +} + +/// An image `width` by `height` pixels placed by `xf`. +fn placed(id: u64, width: u32, height: u32, xf: Affine) -> Node { + let mut img = image(id); + if let NodeKind::Image(i) = &mut img.kind { + i.width = width; + i.height = height; + i.xf = xf; + } + img +} + +#[test] +fn an_image_inside_a_clips_box_but_outside_its_shape_is_left_out() { + let d = document(); + let circle = || shapes::ellipse(Rect::new(100.0, 100.0, 200.0, 200.0)); + let square = || shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 150.0)); + let at = |x: f64, y: f64| Affine::translate((x, y)); + // Two circles inside each other's clips: they show together only the lens between them. + let lens = |art: Vec| { + let inner = shaped_clip_group(70, shapes::ellipse(Rect::new(120.0, 100.0, 220.0, 200.0)), FillRule::NonZero, art); + shaped_clip_group(80, shapes::ellipse(Rect::new(80.0, 100.0, 180.0, 200.0)), FillRule::NonZero, vec![inner]) + }; + let mut ring = shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)); + ring.subpaths.extend(shapes::rectangle(Rect::new(130.0, 130.0, 170.0, 170.0)).subpaths); + // Turned 45° about its center at (156, 156): its box reaches into the square's corner, and its + // frame does not. + let turned = at(156.0, 156.0) * Affine::rotate(std::f64::consts::FRAC_PI_4) * at(-5.0, -5.0); + // A shown rectangle and an image `w` by `h` at `xf` inside the clipping path `path`. + let clipped = |path: PathData, rule: FillRule, shown: Rect, (w, h, xf): (u32, u32, Affine)| { + shaped_clip_group(60, path, rule, vec![rect(62, shown.x0, shown.y0, shown.x1, shown.y1, 0.0), placed(63, w, h, xf)]) + }; + let middle = Rect::new(140.0, 140.0, 160.0, 160.0); + let band = Rect::new(100.0, 100.0, 110.0, 200.0); + let left_out = [ + // In the corner of the circle's box, outside the circle. + ("a circle's corner", clipped(circle(), FillRule::NonZero, middle, (10, 10, at(100.0, 100.0)))), + ("a turned frame", clipped(square(), FillRule::NonZero, Rect::new(110.0, 110.0, 140.0, 140.0), (10, 10, turned))), + // Above the lens: inside each circle, outside both at once. + ("two clips' shared area", lens(vec![rect(62, 145.0, 140.0, 155.0, 160.0, 0.0), placed(63, 8, 3, at(146.0, 100.0))])), + ("an even-odd hole", clipped(ring.clone(), FillRule::EvenOdd, band, (10, 10, at(140.0, 140.0)))), + ]; + let shown = [ + ("part of the circle", clipped(circle(), FillRule::NonZero, middle, (10, 10, at(145.0, 145.0)))), + ("a non-zero hole", clipped(ring, FillRule::NonZero, band, (10, 10, at(140.0, 140.0)))), + // A strip 0.005 pt wide inside the square still shows. + ("a narrow strip", clipped(square(), FillRule::NonZero, Rect::new(110.0, 110.0, 140.0, 140.0), (10, 10, at(149.995, 120.0)))), + ("the lens", lens(vec![rect(62, 145.0, 140.0, 155.0, 160.0, 0.0), placed(63, 8, 3, at(146.0, 108.0))])), + ]; + for id in TYPES { + for (what, g) in &left_out { + let n = with(g.clone(), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id}: {what}"); + assert!(art(&d, &n, id).is_some(), "{id}: {what} draws"); + assert!(three_d_meshes_in(Some(&d), &n).is_ok_and(|m| !m.is_empty()), "{id}: {what} exports"); + } + for (what, g) in &shown { + let n = with(g.clone(), id, json!({})); + assert!(validate_three_d_in(Some(&d), &n, id, &json!({})).is_err_and(|e| e.contains("Image Trace")), "{id}: {what}"); + assert!(art(&d, &n, id).is_none(), "{id}: {what}"); + } + } + // Each frame cut to a clip counts: past the limit the art is refused, never left out unchecked. + let many: Vec = std::iter::once(rect(62, 140.0, 140.0, 160.0, 160.0, 0.0)) + .chain((0..=source::MAX_IMAGE_CUTS as u64).map(|i| placed(100 + i, 10, 10, at(100.0, 100.0)))) + .collect(); + let n = with(shaped_clip_group(60, circle(), FillRule::NonZero, many), ROTATE, front()); + assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("too many objects"))); +} + /// Symbols `L0` to `L{levels}`: `L0` holds `leaf`, each later one `fan` instances of the one /// before it. fn nested_symbols(levels: usize, fan: usize, leaf: Node) -> Document { diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index eab57e2a91..e02382b6b1 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -777,7 +777,7 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< /// The most presets one presets file imports: each is looked up among the saved ones. pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; -pub(crate) use addons::DecodedImages; +pub(crate) use addons::{DecodedImages, refresh_color_masks}; pub use docmenu::guide_indexes; pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 0815404835..66c67651a3 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -14,7 +14,7 @@ mod select; mod shapes; mod typetools; -pub(crate) use image::DecodedImages; +pub(crate) use image::{DecodedImages, refresh_color_masks}; use super::CommandSpec; diff --git a/crates/engine/src/cmd/addons/image.rs b/crates/engine/src/cmd/addons/image.rs index bfe3d2f4ef..898c28c707 100644 --- a/crates/engine/src/cmd/addons/image.rs +++ b/crates/engine/src/cmd/addons/image.rs @@ -2,12 +2,16 @@ //! selected images transparent in their own pixels, as one undo step. The background is the most //! common color along an image's edges, the average of its four corners, or colors the caller //! picks. It is cleared where it reaches in from an edge, or wherever it is. The work is done here, -//! on the pixels; nothing is sent anywhere. It is a VectorCraft addition. Its submenu (Object › -//! Plug-ins › Image Tools) and dialog are the UI's. +//! on the pixels; nothing is sent anywhere. Color Mask ([`mask`]) hides colors matched the same +//! way while the image keeps its pixels. They are VectorCraft additions. Its submenu (Object › +//! Plug-ins › Image Tools) and dialogs are the UI's. +mod mask; #[cfg(test)] mod tests; +pub(crate) use mask::refresh as refresh_color_masks; + use std::collections::{HashMap, HashSet}; use std::io::Cursor; use std::sync::{Arc, Weak}; @@ -15,12 +19,12 @@ use std::sync::{Arc, Weak}; use image::{DynamicImage, ImageBuffer, LumaA, Rgba}; use serde_json::{Value, json}; use vectorcraft_color::Color; -use vectorcraft_doc::{ImageBlob, NodeId, NodeKind}; +use vectorcraft_doc::{ImageBlob, ImageObject, NodeId, NodeKind}; use vectorcraft_geom::Affine; use super::super::fileio::{MAX_RASTER_ALLOC, ppi}; use super::super::menucmds::has_image; -use super::super::paint::{PROCESS_ON_TRANSPARENCY, gray_colorized_with_process}; +use super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process}; use super::super::{CommandSpec, Result, Session, bad, checked_ids_param, cmd, hex_with_alpha, number_or, switch_or, text_param}; /// Remove Background's command. @@ -35,7 +39,7 @@ const MAX_COLORS: usize = 16; const WORK_BYTES: u64 = 10; pub fn specs() -> Vec { - vec![cmd!( + let mut v = vec![cmd!( "addon.image.removeBackground", "Remove Background…", ["Object", "Plug-ins", "Image Tools"], @@ -43,7 +47,9 @@ pub fn specs() -> Vec { "{background?: \"edges\" (default: the most common color along the image's edges; nothing is cleared when the edges hold at least as many clear pixels as pixels of that color) | \"corners\" (the average of the image's four corner pixels that are not clear; nothing is cleared when all four are clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 colors, each a hex color \"#rrggbb\" or \"#rgb\" with or without the # or one of black, white, red, green and blue; needed with background: colors, and checked but not used with edges or corners), contiguous?: bool (true: only background pixels that reach in from an edge are cleared; false: they are cleared wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a background color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (with distance, % of the largest RGB distance; with channels, % of 255 steps on one channel; a pixel this near a background color is cleared; 10), softness?: 0..100 (% past the tolerance over which pixels fade from cleared to kept; 10), ids?: [id…] (default: the selected images)} make the background of each image transparent in its own pixels, as one undo step: the image stays an image, embedded as a PNG with an alpha channel at the depth of its pixels (16-bit images keep 16 bits and grayscale images stay gray) with the source's color profile and resolution, and a linked image is embedded; a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, a result with no pixel left, and a grayscale image colorized with a process color (which can't colorize gray pixels with transparency) are refused, and an image whose pixels do not change is left as it is (no undo step when none changes) → {changed: the images changed, ids, cleared: the pixels made fully clear in them}", has_image, remove_background - )] + )]; + v.extend(mask::specs()); + v } /// Where the background's colors come from. @@ -79,50 +85,50 @@ pub(crate) struct Settings { } impl Settings { - /// The settings `p` gives, each checked. - fn read(p: &Value) -> Result { + /// The settings `p` gives to command `cmd`, each checked. + fn read(p: &Value, cmd: &str) -> Result { let percent = |key: &str| -> Result { - let v = number_or(p, key, 10.0, C)?; - if v.is_finite() && (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) } + let v = number_or(p, key, 10.0, cmd)?; + if v.is_finite() && (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(cmd, format!("`{key}` must be from 0 to 100"))) } }; let (tolerance, softness) = (percent("tolerance")?, percent("softness")?); let colors = match p.get("colors") { None | Some(Value::Null) => None, - Some(v) => Some(colors(v)?), + Some(v) => Some(colors(v, cmd)?), }; - let background = match text_param(p, "background", C)? { + let background = match text_param(p, "background", cmd)? { None | Some("edges") => Background::Edges, Some("corners") => Background::Corners, - Some("colors") => Background::Colors(colors.ok_or_else(colors_error)?), - Some(_) => return Err(bad(C, "`background` must be edges, corners or colors")), + Some("colors") => Background::Colors(colors.ok_or_else(|| colors_error(cmd))?), + Some(_) => return Err(bad(cmd, "`background` must be edges, corners or colors")), }; - let measure = match text_param(p, "match", C)? { + let measure = match text_param(p, "match", cmd)? { None | Some("distance") => Match::Distance, Some("channels") => Match::Channels, - Some(_) => return Err(bad(C, "`match` must be distance or channels")), + Some(_) => return Err(bad(cmd, "`match` must be distance or channels")), }; - let contiguous = switch_or(p, "contiguous", true, C)?; + let contiguous = switch_or(p, "contiguous", true, cmd)?; Ok(Self { background, contiguous, measure, tolerance, softness }) } } -fn colors_error() -> crate::EngineError { - bad(C, "`colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue") +fn colors_error(cmd: &str) -> crate::EngineError { + bad(cmd, "`colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue") } -/// The colors `v` lists: an array of strings, or one string of them split by commas or spaces. -/// Each is read as [`Color::from_hex`] reads it; one with an alpha part is refused. -fn colors(v: &Value) -> Result> { +/// The colors `v` lists to command `cmd`: an array of strings, or one string of them split by +/// commas or spaces. Each is read as [`Color::from_hex`] reads it; one with an alpha part is refused. +fn colors(v: &Value, cmd: &str) -> Result> { // One past the most is enough to tell a list that is too long. let texts: Vec<&str> = match v { Value::String(s) => s.split([',', ' ', '\t', '\n']).filter(|t| !t.is_empty()).take(MAX_COLORS + 1).collect(), - Value::Array(a) => a.iter().take(MAX_COLORS + 1).map(Value::as_str).collect::>().ok_or_else(colors_error)?, - _ => return Err(colors_error()), + Value::Array(a) => a.iter().take(MAX_COLORS + 1).map(Value::as_str).collect::>().ok_or_else(|| colors_error(cmd))?, + _ => return Err(colors_error(cmd)), }; if texts.is_empty() || texts.len() > MAX_COLORS { - return Err(colors_error()); + return Err(colors_error(cmd)); } - texts.into_iter().map(|t| rgb8(t).ok_or_else(colors_error)).collect() + texts.into_iter().map(|t| rgb8(t).ok_or_else(|| colors_error(cmd))).collect() } /// The 8-bit RGB of the color `t` writes. @@ -135,7 +141,7 @@ fn rgb8(t: &str) -> Option<[u8; 3]> { } fn remove_background(s: &mut Session, p: &Value) -> Result { - let settings = Settings::read(p)?; + let settings = Settings::read(p, C)?; // A preview step keeps the pixels it decodes for the next step; other runs keep none. let mut kept = std::mem::take(&mut s.decoded_images); let previewing = s.previewing; @@ -165,40 +171,15 @@ fn remove_background(s: &mut Session, p: &Value) -> Result { /// cleared as `settings` say and the transform that keeps its place and size. Decoded pixels are /// taken from and kept in `kept` when it is given. fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result> { + let images = images(s, p, C)?; + // The result has an alpha channel, which a grayscale image colorized with a process color + // can't take. The pixels that are cleared are checked, the image's own, not the ones a color + // mask shows. let st = s.doc()?; - let ids: Vec = if p.get("ids").is_some_and(|v| !v.is_null()) { - // Each image once, however often `ids` names it. - let mut given = HashSet::new(); - let ids: Vec = checked_ids_param(s, p, "ids", C)?.into_iter().filter(|id| given.insert(*id)).collect(); - if let Some(id) = ids.iter().find(|id| !matches!(st.doc.node(**id).map(|n| &n.kind), Some(NodeKind::Image(_)))) { - return Err(bad(C, format!("object {} is not an image", id.0))); - } - ids - } else { - st.selection.objects.iter().copied().filter(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))).collect() - }; - if ids.is_empty() { - return Err(bad(C, "select an image")); - } - // Every image is checked before any is decoded. - let mut images = vec![]; - for id in ids { - let Some(n) = st.doc.node(id) else { continue }; - let NodeKind::Image(im) = &n.kind else { continue }; - let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image's pixels are missing"))?; - // The result has an alpha channel, which a grayscale image colorized with a process color - // can't take. - if gray_colorized_with_process(&st.doc, n).is_some() { + for (id, _, blob) in &images { + if blob.gray_source().is_some() && st.doc.node(*id).is_some_and(|n| colorized_with_process(&st.doc, n)) { return Err(bad(C, PROCESS_ON_TRANSPARENCY)); } - // The preview stands in for a file that hasn't been read, or that is kept at its preview. - if im.link.is_some() && blob.is_proxy() { - return Err(bad(C, "the linked image shows its preview: embed or relink it first")); - } - if blob.is_cmyk() { - return Err(bad(C, "a CMYK image has no transparency to set")); - } - images.push((id, im, blob)); } // Each image's pixels once, however many objects show them. let mut cleared: HashMap<&str, Option> = HashMap::new(); @@ -207,7 +188,7 @@ fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut De let out = match cleared.get(im.key.as_str()) { Some(out) => out.clone(), None => { - let out = clear(blob, settings, kept.as_deref_mut())?; + let out = clear(blob, settings, kept.as_deref_mut(), C)?; cleared.insert(&im.key, out.clone()); out } @@ -225,6 +206,58 @@ fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut De Ok(changes) } +/// The image objects command `cmd` acts on (`ids`, each once, or the selected images), each with +/// its pixels, all checked before any is decoded: an object that is not an image, missing pixels, +/// a linked image that shows its preview and a CMYK image are errors, as is no image at all. +fn images<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result> { + let st = s.doc()?; + let mut images = vec![]; + for id in targets(s, p, cmd)? { + let Some(NodeKind::Image(im)) = st.doc.node(id).map(|n| &n.kind) else { continue }; + let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(cmd, "the image's pixels are missing"))?; + // The preview stands in for a file that hasn't been read, or that is kept at its preview. + if im.link.is_some() && blob.is_proxy() { + return Err(bad(cmd, "the linked image shows its preview: embed or relink it first")); + } + if blob.is_cmyk() { + return Err(cmyk_refusal(cmd)); + } + images.push((id, &**im, blob)); + } + Ok(images) +} + +/// The image objects command `cmd` acts on: `ids`, each once, or the selected images. An object in +/// `ids` that is not an image is an error, as is no image at all. +fn targets(s: &Session, p: &Value, cmd: &str) -> Result> { + let st = s.doc()?; + let ids: Vec = if p.get("ids").is_some_and(|v| !v.is_null()) { + // Each image once, however often `ids` names it. + let mut given = HashSet::new(); + let ids: Vec = checked_ids_param(s, p, "ids", cmd)?.into_iter().filter(|id| given.insert(*id)).collect(); + if let Some(id) = ids.iter().find(|id| !matches!(st.doc.node(**id).map(|n| &n.kind), Some(NodeKind::Image(_)))) { + return Err(bad(cmd, format!("object {} is not an image", id.0))); + } + ids + } else { + st.selection.objects.iter().copied().filter(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))).collect() + }; + if ids.is_empty() { + return Err(bad(cmd, "select an image")); + } + Ok(ids) +} + +/// Whether `cmd` is one of Color Mask's commands, which hide pixels instead of clearing them. +fn masks(cmd: &str) -> bool { + matches!(cmd, mask::COLOR_MASK | mask::REMOVE_COLOR_MASK | mask::APPLY_COLOR_MASK) +} + +/// Command `cmd`'s refusal of a CMYK image. +fn cmyk_refusal(cmd: &str) -> crate::EngineError { + if masks(cmd) { bad(cmd, "a CMYK image can't take a color mask") } else { bad(cmd, "a CMYK image has no transparency to set") } +} + /// An image with its background cleared: its PNG, its size in pixels, and how many of its pixels /// were made fully clear. #[derive(Clone, Debug)] @@ -352,16 +385,16 @@ impl Pixels { /// `blob` with its background cleared as `settings` say, or `None` when no pixel changes. A CMYK /// image, one that can't be decoded or is too large to change, and a result with no pixel left are -/// errors. The PNG keeps the source's ICC profile and resolution. The decoded pixels are taken -/// from and kept in `kept` when it is given. -pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result> { +/// errors of command `cmd`. The PNG keeps the source's ICC profile and resolution. The decoded +/// pixels are taken from and kept in `kept` when it is given. +pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut DecodedImages>, cmd: &str) -> Result> { if blob.is_cmyk() { - return Err(bad(C, "a CMYK image has no transparency to set")); + return Err(cmyk_refusal(cmd)); } let found = kept.as_deref_mut().and_then(|k| k.get(&blob.bytes)); let (source, gray, icc) = match found { Some(found) => found, - None => decode(blob, kept)?, + None => decode(blob, kept, cmd)?, }; // The pixels kept for the next run stay as they are; ones not kept are worked on in place. let mut px = Arc::try_unwrap(source).unwrap_or_else(|kept| Pixels::clone(&kept)); @@ -373,7 +406,11 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut Pixels::Sixteen(img) => img.pixels().any(|p| p.0[3] > 0), }; if !left { - return Err(bad(C, "every pixel matches the background: no image would be left")); + return Err(if masks(cmd) { + bad(cmd, "the mask would hide every pixel") + } else { + bad(cmd, "every pixel matches the background: no image would be left") + }); } let out = match (px, gray) { (Pixels::Eight(img), false) => DynamicImage::ImageRgba8(img), @@ -389,9 +426,9 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut let mut encoder = image::codecs::png::PngEncoder::new(&mut png); if let Some(icc) = icc { use image::ImageEncoder as _; - encoder.set_icc_profile(icc).map_err(|e| bad(C, e.to_string()))?; + encoder.set_icc_profile(icc).map_err(|e| bad(cmd, e.to_string()))?; } - out.write_with_encoder(encoder).map_err(|e| bad(C, e.to_string()))?; + out.write_with_encoder(encoder).map_err(|e| bad(cmd, e.to_string()))?; // The resolution the file declares, which sizes the image at 100% when it is replaced or relinked. if let Some(r) = ppi::resolution(&blob.bytes) { png = ppi::with_png_resolution(&png, r); @@ -401,11 +438,12 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut /// `blob`'s pixels as straight RGBA, whether they were gray, and its ICC profile. An image that /// can't be decoded or is too large to change is an error. The pixels are kept in `kept`, when it -/// is given, if a copy of them fits the decode allowance beside the work. -fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>) -> Result<(Arc, bool, Option>)> { - let reader = - || image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(C, "the image's pixels can't be read")); - let mut decoder = reader()?.into_decoder().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?; +/// is given, if a copy of them fits the decode allowance beside the work. Errors are command `cmd`'s. +fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<(Arc, bool, Option>)> { + let reader = || { + image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(cmd, "the image's pixels can't be read")) + }; + let mut decoder = reader()?.into_decoder().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?; // The ICC profile the colors are in goes with them into the PNG. let (w, h, kind, icc) = { use image::ImageDecoder as _; @@ -418,13 +456,13 @@ fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>) -> Result<(Arc kind.channel_count(); let per_pixel = u64::from(kind.bytes_per_pixel()) + 2 * if deep { 8 } else { 4 } + WORK_BYTES; if u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC) { - return Err(bad(C, format!("an image of {w} × {h} pixels is too large to change"))); + return Err(bad(cmd, format!("an image of {w} × {h} pixels is too large to change"))); } let mut reader = reader()?; let mut limits = image::Limits::default(); limits.max_alloc = Some(MAX_RASTER_ALLOC); reader.limits(limits); - let img = reader.decode().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?; + let img = reader.decode().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?; #[cfg(test)] DECODES.with(|c| c.set(c.get() + 1)); let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16); diff --git a/crates/engine/src/cmd/addons/image/mask.rs b/crates/engine/src/cmd/addons/image/mask.rs new file mode 100644 index 0000000000..786effbd2e --- /dev/null +++ b/crates/engine/src/cmd/addons/image/mask.rs @@ -0,0 +1,443 @@ +//! Image Tools › Color Mask (`addon.image.colorMask`, `addon.image.removeColorMask`, +//! `addon.image.applyColorMask`): colors of the selected images are hidden while their pixels +//! stay as they are. The colors are matched as Remove Background matches them ([`super::clear`]); +//! the image keeps its own pixels, and the mask's settings and the masked pixels are kept with it +//! ([`vectorcraft_doc::color_mask`]), so the mask can be changed, removed, or applied to the +//! pixels later. When an image's own pixels are replaced (a link updated or relinked, the image +//! cropped or recolored), its mask is applied to the new pixels ([`refresh`]). + +#[cfg(test)] +mod tests; + +use std::collections::HashMap; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch}; +use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind}; +use vectorcraft_geom::Affine; + +use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process}; +use super::super::super::{CommandSpec, Result, Session, bad, cmd}; +use super::{Background, DecodedImages, MAX_COLORS, Match, Settings, clear, images, targets}; + +/// Color Mask's command. +pub const COLOR_MASK: &str = "addon.image.colorMask"; +/// Remove Color Mask's command. +pub const REMOVE_COLOR_MASK: &str = "addon.image.removeColorMask"; +/// Apply Color Mask's command. +pub const APPLY_COLOR_MASK: &str = "addon.image.applyColorMask"; + +/// The params that set a mask; with none of them, Color Mask only reports. +const SETTINGS: [&str; 6] = ["background", "colors", "contiguous", "match", "tolerance", "softness"]; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.image.colorMask", + "Color Mask…", + ["Object", "Plug-ins", "Image Tools"], + None, + "{background?: \"edges\" (default: the most common color along the image's edges) | \"corners\" (the average of the image's four corner pixels that are not clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 hex colors or black, white, red, green and blue, as addon.image.removeBackground takes them; needed with background: colors), contiguous?: bool (true: only matching pixels that reach in from an edge are hidden; false: wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a hidden color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (% as addon.image.removeBackground measures it; a pixel this near a hidden color is hidden; 10), softness?: 0..100 (% past the tolerance over which pixels fade from hidden to shown; 10), ids?: [id…] (default: the selected images)} hide colors of each image without changing its pixels, as one undo step: the image keeps its own pixels, and the mask (these settings, and the image's pixels with the hidden colors made clear, made as Remove Background makes them) is kept with the image and saved with the document; the canvas, printing and separations, PDF, SVG, EPS, raster formats, DXF, EMF, WMF, the legacy .ai and the .ai editing data, copy and paste, and placing a document show the masked pixels, and a click on any part of the image's frame selects it (the Eyedropper, Object Mosaic, Create Gradient Mesh, Crop Image's trim and Image Trace read the image's own pixels); setting the mask again replaces it, and an image whose mask does not change is left as it is (no undo step when none changes); when the image's own pixels are replaced later (Update Link, Relink, Crop Image, a recolor, a linked file read again on open), the mask is made again for the new pixels; an object in `ids` that is not an image, a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, a mask that would hide every pixel, and a mask that would hide pixels of a grayscale image colorized with a process color (masked gray pixels have transparency, which only a spot color, black or white colorizes; each image is checked on the pixels its new mask shows) are refused. With none of background, colors, contiguous, match, tolerance and softness given, nothing changes and the mask settings of the first image (or the defaults when it has no mask) are returned → {changed: the images changed, ids, hidden: the pixels made fully clear in them} or {background, colors, contiguous, match, tolerance, softness, masked}", + super::has_image, + color_mask + ), + cmd!( + "addon.image.removeColorMask", + "Remove Color Mask", + ["Object", "Plug-ins", "Image Tools"], + None, + "{ids?: [id…] (default: the selected images)} take the color mask off each image, as one undo step: the image shows its own pixels again; images without a mask are left as they are (no undo step when none has one), and an object in `ids` that is not an image is refused → {changed, ids}", + has_color_mask, + remove_color_mask + ), + cmd!( + "addon.image.applyColorMask", + "Apply Color Mask", + ["Object", "Plug-ins", "Image Tools"], + None, + "{ids?: [id…] (default: the selected images)} make each image's color mask part of its pixels, as one undo step: the masked pixels become the image's own, embedded as a PNG with an alpha channel (a linked image is embedded), and the mask is taken off; a mask that hides nothing is only taken off (the image keeps its pixels and its link); images without a mask are left as they are (no undo step when none has one), and an object in `ids` that is not an image, and a mask made again for new pixels that would give a grayscale image colorized with a process color an alpha channel, are refused → {changed, ids}", + has_color_mask, + apply_color_mask + ), + ] +} + +/// Enabled when a selected image has a color mask. +fn has_color_mask(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if st.selection.objects.iter().any(|id| st.doc.node(*id).and_then(Document::color_mask_of).is_some()) { + Ok(()) + } else { + Err("select an image with a color mask".into()) + } +} + +impl Settings { + /// The settings a mask was made with, `None` when a file gave ones out of range. + fn of(m: &ColorMask) -> Option { + let percent = |v: f64| v.is_finite() && (0.0..=100.0).contains(&v); + if !percent(m.tolerance) || !percent(m.softness) { + return None; + } + let background = match m.background { + MaskBackground::Edges => Background::Edges, + MaskBackground::Corners => Background::Corners, + MaskBackground::Colors if (1..=MAX_COLORS).contains(&m.colors.len()) => Background::Colors(m.colors.clone()), + MaskBackground::Colors => return None, + }; + let measure = match m.measure { + MaskMatch::Distance => Match::Distance, + MaskMatch::Channels => Match::Channels, + }; + Some(Self { background, contiguous: m.contiguous, measure, tolerance: m.tolerance, softness: m.softness }) + } + + /// A mask with these settings whose masked pixels are `key`, made from the pixels `from`. + fn mask(&self, key: String, from: String) -> ColorMask { + let (background, colors) = match &self.background { + Background::Edges => (MaskBackground::Edges, vec![]), + Background::Corners => (MaskBackground::Corners, vec![]), + Background::Colors(c) => (MaskBackground::Colors, c.clone()), + }; + let measure = match self.measure { + Match::Distance => MaskMatch::Distance, + Match::Channels => MaskMatch::Channels, + }; + ColorMask { key, from, background, colors, contiguous: self.contiguous, measure, tolerance: self.tolerance, softness: self.softness } + } +} + +/// The masked pixels of `blob` (`None`: no pixel is hidden, the image's own pixels show) as +/// `settings` say, with errors of command `cmd`. +fn masked(blob: &ImageBlob, settings: &Settings, kept: Option<&mut DecodedImages>, cmd: &str) -> Result> { + Ok(clear(blob, settings, kept, cmd)?.map(|out| (out.blob.content_key(), out.blob, out.cleared))) +} + +fn color_mask(s: &mut Session, p: &Value) -> Result { + if !SETTINGS.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + return report(s, p); + } + let settings = Settings::read(p, COLOR_MASK)?; + // A preview step keeps the pixels it decodes for the next step; other runs keep none. + let mut kept = std::mem::take(&mut s.decoded_images); + let previewing = s.previewing; + let found = mask_changes(s, p, &settings, previewing.then_some(&mut kept)); + s.decoded_images = kept; + let changes = found?; + let ids: Vec = changes.iter().map(|c| c.0.0).collect(); + let hidden: u64 = changes.iter().map(|c| c.3).sum(); + if !changes.is_empty() { + s.edit("Color Mask", |d, _| { + for (id, mask, blob, _) in changes { + if let Some(blob) = blob { + d.images.entry(mask.key.clone()).or_insert(blob); + } + if let Some(n) = d.node_mut(id) { + n.extras_mut().color_mask = Some(Box::new(mask)); + } + } + Ok(()) + })?; + } + Ok(json!({ "changed": ids.len(), "ids": ids, "hidden": hidden })) +} + +/// The images `p` names whose mask changes, each with its new mask, the masked pixels to add (when +/// the document doesn't have them) and how many pixels they hide. +type MaskChange = (NodeId, ColorMask, Option, u64); + +fn mask_changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result> { + let st = s.doc()?; + // Each image's pixels once, however many objects show them. + let mut made: HashMap<&str, (String, Option, u64)> = HashMap::new(); + let mut out = vec![]; + for (id, im, blob) in images(s, p, COLOR_MASK)? { + let (key, pixels, hidden) = match made.get(im.key.as_str()) { + Some(m) => m.clone(), + None => { + let m = match masked(blob, settings, kept.as_deref_mut(), COLOR_MASK)? { + Some((key, blob, hidden)) => (key, Some(blob), hidden), + None => (im.key.clone(), None, 0), + }; + made.insert(&im.key, m.clone()); + m + } + }; + let mask = settings.mask(key, im.key.clone()); + if st.doc.node(id).and_then(Document::color_mask_of) == Some(&mask) { + continue; + } + // Masked pixels that hide something have an alpha channel, which a grayscale image + // colorized with a process color can't take. The pixels the new mask shows are checked, + // made from the image's own pixels, not the ones an earlier mask shows. + let shown = pixels.as_ref().or_else(|| st.doc.images.get(&mask.key)); + if st.doc.node(id).is_some_and(|n| refused_colorize(&st.doc, n, shown)) { + return Err(bad(COLOR_MASK, PROCESS_ON_TRANSPARENCY)); + } + let pixels = pixels.filter(|_| !st.doc.images.contains_key(&mask.key)); + out.push((id, mask, pixels, hidden)); + } + Ok(out) +} + +/// Whether masked pixels `shown`, made for image node `n`, have transparency that `n`'s colorize +/// color can't take: gray pixels with an alpha channel and a process color +/// ([`colorized_with_process`]). +fn refused_colorize(doc: &Document, n: &Node, shown: Option<&ImageBlob>) -> bool { + shown.and_then(ImageBlob::gray_source).is_some_and(|g| g.alpha) && colorized_with_process(doc, n) +} + +/// Color Mask without settings: the first image's mask settings, or the defaults. It reads them +/// for images a change would refuse too (CMYK, a linked image at its preview), so the dialog opens. +fn report(s: &Session, p: &Value) -> Result { + let st = s.doc()?; + let first = targets(s, p, COLOR_MASK)?.first().and_then(|id| st.doc.node(*id)).and_then(Document::color_mask_of).cloned(); + let m = first.as_ref(); + let hex = |c: &[u8; 3]| format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]); + let colors = + m.filter(|m| !m.colors.is_empty()).map_or_else(|| "#ffffff".to_string(), |m| m.colors.iter().map(hex).collect::>().join(", ")); + let name = |v: Value| v.as_str().map(str::to_string).unwrap_or_default(); + Ok(json!({ + "background": name(serde_json::to_value(m.map_or(MaskBackground::Edges, |m| m.background)).unwrap_or_default()), + "colors": colors, + "contiguous": m.is_none_or(|m| m.contiguous), + "match": name(serde_json::to_value(m.map_or(MaskMatch::Distance, |m| m.measure)).unwrap_or_default()), + "tolerance": m.map_or(10.0, |m| m.tolerance), + "softness": m.map_or(10.0, |m| m.softness), + "masked": m.is_some(), + })) +} + +/// The image objects `p` names ([`targets`]: `ids`, or the selected images) that have a color mask. +fn masked_images(s: &Session, p: &Value, cmd: &str) -> Result> { + let st = s.doc()?; + Ok(targets(s, p, cmd)?.into_iter().filter(|id| st.doc.node(*id).and_then(Document::color_mask_of).is_some()).collect()) +} + +fn remove_color_mask(s: &mut Session, p: &Value) -> Result { + let ids = masked_images(s, p, REMOVE_COLOR_MASK)?; + if !ids.is_empty() { + s.edit("Remove Color Mask", |d, _| { + for id in &ids { + if let Some(n) = d.node_mut(*id) { + n.extras_mut().color_mask = None; + } + } + Ok(()) + })?; + } + Ok(json!({ "changed": ids.len(), "ids": ids.iter().map(|id| id.0).collect::>() })) +} + +fn apply_color_mask(s: &mut Session, p: &Value) -> Result { + let ids = masked_images(s, p, APPLY_COLOR_MASK)?; + // Each image's masked pixels, made again first when its own pixels changed since. A mask that + // hides nothing (its masked pixels are the image's own) is only taken off: the image keeps its + // pixels and its link. + let mut made = vec![]; + { + let st = s.doc()?; + for id in &ids { + let Some(n) = st.doc.node(*id) else { continue }; + let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { continue }; + let mask = match fresh(&st.doc, n, APPLY_COLOR_MASK) { + Some(Ok(fresh)) => fresh, + Some(Err(e)) => return Err(e), + None => (m.clone(), None), + }; + if mask.0.key == im.key { + made.push((*id, None)); + continue; + } + let shown = st.doc.images.get(&mask.0.key).or(mask.1.as_ref()); + if refused_colorize(&st.doc, n, shown) { + return Err(bad(APPLY_COLOR_MASK, PROCESS_ON_TRANSPARENCY)); + } + let size = mask_size(shown, im.width, im.height); + made.push((*id, Some((mask, size)))); + } + } + if !made.is_empty() { + s.edit("Apply Color Mask", |d, _| { + for (id, applied) in made { + let Some(n) = d.node_mut(id) else { continue }; + n.extras_mut().color_mask = None; + let Some(((mask, blob), (w, h))) = applied else { continue }; + if let Some(blob) = blob { + d.images.entry(mask.key.clone()).or_insert(blob); + } + let Some(n) = d.node_mut(id) else { continue }; + if let NodeKind::Image(im) = &mut n.kind { + // Masked pixels of another size than the object's keep its place and size. + if (w, h) != (im.width, im.height) { + im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(w), f64::from(im.height) / f64::from(h)); + (im.width, im.height) = (w, h); + } + im.key = mask.key; + im.link = None; + } + } + Ok(()) + })?; + } + Ok(json!({ "changed": ids.len(), "ids": ids.iter().map(|id| id.0).collect::>() })) +} + +/// The size in pixels of masked pixels `blob` (from its header), or the object's when it can't be +/// read. +fn mask_size(blob: Option<&ImageBlob>, width: u32, height: u32) -> (u32, u32) { + blob.and_then(|b| image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok()) + .filter(|(w, h)| *w > 0 && *h > 0) + .unwrap_or((width, height)) +} + +/// The mask of image node `n` made again for the image's own pixels, with the masked pixels when +/// `doc` doesn't have them: `None` when the mask is up to date (or `n` has none), an error when the +/// pixels can't be masked (missing, CMYK, a linked preview, too large, every pixel hidden, or +/// settings a file gave out of range). +fn fresh(doc: &Document, n: &Node, cmd: &str) -> Option)>> { + let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { return None }; + if !stale_mask(doc, n) { + return None; + } + let made = || -> Result<(ColorMask, Option)> { + let settings = Settings::of(m).ok_or_else(|| bad(cmd, "the color mask's settings are out of range"))?; + let blob = doc.images.get(&im.key).ok_or_else(|| bad(cmd, "the image's pixels are missing"))?; + if im.link.is_some() && blob.is_proxy() { + return Err(bad(cmd, "the linked image shows its preview: embed or relink it first")); + } + Ok(match masked(blob, &settings, None, cmd)? { + Some((key, blob, _)) => { + let blob = (!doc.images.contains_key(&key)).then_some(blob); + (settings.mask(key, im.key.clone()), blob) + } + None => (settings.mask(im.key.clone(), im.key.clone()), None), + }) + }; + Some(made()) +} + +/// After an edit from `before` (`None`: everything is new, as after a document's links are read): +/// the color masks of images in `doc`'s art ([`Document::art_roots`]: layers, symbols, graph +/// designs, patterns and the original of the pattern being edited, opacity mask art included) +/// whose own pixels were replaced are made again for the new pixels ([`Refresh::made`]). Only the +/// art that changed since `before` is looked at. +pub(crate) fn refresh(before: Option<&Document>, doc: &mut Document) { + let old: Vec<&Arc> = before.map(|b| b.art_roots().collect()).unwrap_or_default(); + let mut pass = Refresh { doc: &*doc, made: HashMap::new(), blobs: vec![] }; + let mut fixed = vec![]; + for (i, root) in doc.art_roots().enumerate() { + let counterpart = old.get(i).copied().filter(|o| o.id == root.id); + if stale_in(doc, root, counterpart) { + let mut root = root.clone(); + pass.fix(Arc::make_mut(&mut root)); + fixed.push((i, root)); + } + } + let blobs = pass.blobs; + if fixed.is_empty() { + return; + } + for (key, blob) in blobs { + doc.images.entry(key).or_insert(blob); + } + let mut fixed = fixed.into_iter().peekable(); + for (i, root) in doc.art_roots_mut().enumerate() { + if fixed.peek().is_some_and(|(at, _)| *at == i) + && let Some((_, new)) = fixed.next() + { + *root = new; + } + } +} + +/// Whether `n`, or anything in it (opacity-mask art included), is an image whose mask is out of +/// date ([`stale_mask`]). What is the same as in `old`, `n`'s counterpart before an edit, is not +/// looked at. +fn stale_in(doc: &Document, n: &Arc, old: Option<&Arc>) -> bool { + if old.is_some_and(|o| Arc::ptr_eq(o, n)) { + return false; + } + if stale_mask(doc, n) { + return true; + } + let old_mask = old.and_then(|o| o.extras().mask.as_ref()).map(|m| &m.art); + if n.extras().mask.as_ref().is_some_and(|m| stale_in(doc, &m.art, old_mask)) { + return true; + } + let Some(children) = n.children() else { return false }; + let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice); + let mut by_id: Option>> = None; + children.iter().enumerate().any(|(i, c)| { + let b = match before.get(i) { + Some(b) if b.id == c.id => Some(b), + _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), + }; + stale_in(doc, c, b) + }) +} + +/// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked +/// pixels `doc` doesn't have). A mask that hides nothing (its masked pixels are the image's own) +/// is up to date while the image's key stays the same, even when its pixels are missing. +fn stale_mask(doc: &Document, n: &Node) -> bool { + matches!((&n.kind, Document::color_mask_of(n)), (NodeKind::Image(im), Some(m)) + if im.pixels.is_none() && !(m.made_for(im) && (m.key == im.key || doc.images.contains_key(&m.key)))) +} + +/// One [`refresh`] pass: the masks made so far, by the image's pixels, the mask's settings and +/// whether a process color colorizes the image (an image shown by many objects is decoded once), +/// and the masked pixels to add to the document. +struct Refresh<'a> { + doc: &'a Document, + made: HashMap<(String, String, bool), ColorMask>, + blobs: Vec<(String, ImageBlob)>, +} + +impl Refresh<'_> { + /// Make the masks out of date in `n` (a copy of the document's art) again. + fn fix(&mut self, n: &mut Node) { + if let Some(mask) = self.made(n) { + n.extras_mut().color_mask = Some(Box::new(mask)); + } + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && stale_in(self.doc, &m.art, None) + { + self.fix(Arc::make_mut(&mut m.art)); + } + for c in n.children_mut().into_iter().flatten() { + if stale_in(self.doc, c, None) { + self.fix(Arc::make_mut(c)); + } + } + } + + /// The mask of image node `n` made again for the image's own pixels ([`fresh`]), `None` when + /// it is up to date. A mask that can't be made for them (every pixel hidden, CMYK pixels, a + /// linked preview, too large, gray pixels with transparency under a process color) keeps its + /// settings and hides nothing: the image shows its own pixels, and setting the mask again + /// reports why. + fn made(&mut self, n: &Node) -> Option { + let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { return None }; + if !stale_mask(self.doc, n) { + return None; + } + let settings = ColorMask { key: String::new(), from: String::new(), ..m.clone() }; + let at = (im.key.clone(), format!("{settings:?}"), colorized_with_process(self.doc, n)); + if let Some(made) = self.made.get(&at) { + return Some(made.clone()); + } + let hides_nothing = || ColorMask { key: im.key.clone(), from: im.key.clone(), ..m.clone() }; + let mask = match fresh(self.doc, n, COLOR_MASK)? { + Ok((mask, blob)) if refused_colorize(self.doc, n, blob.as_ref().or_else(|| self.doc.images.get(&mask.key))) => hides_nothing(), + Ok((mask, blob)) => { + self.blobs.extend(blob.map(|b| (mask.key.clone(), b))); + mask + } + Err(_) => hides_nothing(), + }; + self.made.insert(at, mask.clone()); + Some(mask) + } +} diff --git a/crates/engine/src/cmd/addons/image/mask/tests.rs b/crates/engine/src/cmd/addons/image/mask/tests.rs new file mode 100644 index 0000000000..b9b56a5e4a --- /dev/null +++ b/crates/engine/src/cmd/addons/image/mask/tests.rs @@ -0,0 +1,1007 @@ +use std::io::Cursor; + +use image::DynamicImage; +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::color_mask::{ColorMask, MaskBackground}; +use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeId, NodeKind}; +use vectorcraft_geom::Rect; + +use super::{APPLY_COLOR_MASK, COLOR_MASK, REMOVE_COLOR_MASK}; +use crate::Session; + +const WHITE: [u8; 4] = [255, 255, 255, 255]; +const RED: [u8; 4] = [200, 0, 0, 255]; + +fn png(img: DynamicImage) -> Vec { + let mut out = Vec::new(); + img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// 12 × 10 pixels: white, with a red block from (3, 3) to (9, 7) that holds one white pixel at +/// (6, 5). +fn framed() -> Vec { + png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(12, 10, |x, y| { + let block = (3..9).contains(&x) && (3..7).contains(&y); + image::Rgba(if block && (x, y) != (6, 5) { RED } else { WHITE }) + }))) +} + +/// Hide white wherever it is, exactly. +fn hide_white() -> Value { + json!({"background": "colors", "colors": "#ffffff", "contiguous": false, "tolerance": 0, "softness": 0}) +} + +/// A session with `bytes` opened as a document, its image selected. +fn open(bytes: &[u8]) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let id = s.doc().unwrap().selection.objects[0]; + (s, id) +} + +fn doc(s: &Session) -> &Document { + &s.doc().unwrap().doc +} + +fn image_of(d: &Document, id: NodeId) -> ImageObject { + let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!("an image") }; + (**im).clone() +} + +fn mask_of(d: &Document, id: NodeId) -> Option { + Document::color_mask_of(d.node(id).unwrap()).cloned() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// The straight RGBA of pixel (`x`, `y`) of image `id` as `d` draws it, on nothing. +fn drawn(d: &Document, id: NodeId, x: u32, y: u32) -> [u8; 4] { + drawn_at(d, pixel_at(d, id, x, y)) +} + +/// Where the center of pixel (`x`, `y`) of image `id` is in `d`. +fn pixel_at(d: &Document, id: NodeId, x: u32, y: u32) -> vectorcraft_geom::Point { + image_of(d, id).xf * vectorcraft_geom::Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5) +} + +/// The straight RGBA that `d` draws at `at`, on nothing. +fn drawn_at(d: &Document, at: vectorcraft_geom::Point) -> [u8; 4] { + let r = vectorcraft_render::Renderer::new().render_region(d, Rect::new(at.x - 0.5, at.y - 0.5, at.x + 0.5, at.y + 0.5), 1.0, false); + let px = r.to_straight(); + [px[0], px[1], px[2], px[3]] +} + +#[test] +fn the_mask_hides_the_chosen_colors_while_the_pixels_stay() { + let (mut s, id) = open(&framed()); + let before = (image_of(doc(&s), id), doc(&s).images[&image_of(doc(&s), id).key].bytes.clone(), undo_len(&s)); + assert_eq!(drawn(doc(&s), id, 0, 0), WHITE); + let r = s.execute(COLOR_MASK, &hide_white()).unwrap(); + assert_eq!(r, json!({"changed": 1, "ids": [id.0], "hidden": 12 * 10 - 6 * 4 + 1})); + let d = doc(&s); + assert_eq!(image_of(d, id), before.0, "the image object is as it was"); + assert_eq!(d.images[&before.0.key].bytes, before.1, "its pixels are as they were"); + let m = mask_of(d, id).unwrap(); + assert_eq!((m.from.as_str(), m.background, m.contiguous), (before.0.key.as_str(), MaskBackground::Colors, false)); + assert_eq!(drawn(d, id, 0, 0)[3], 0, "white is hidden"); + assert_eq!(drawn(d, id, 6, 5)[3], 0, "inside the block too"); + assert_eq!(drawn(d, id, 4, 4), RED, "the red shows"); + assert_eq!(undo_len(&s), before.2 + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(mask_of(doc(&s), id), None); + assert_eq!(drawn(doc(&s), id, 0, 0), WHITE); +} + +#[test] +fn the_mask_is_edited_reported_and_removed() { + let (mut s, id) = open(&framed()); + let r = s.execute(COLOR_MASK, &json!({})).unwrap(); + assert_eq!( + r, + json!({"background": "edges", "colors": "#ffffff", "contiguous": true, "match": "distance", "tolerance": 10.0, "softness": 10.0, "masked": false}) + ); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let steps = undo_len(&s); + // The same settings again: nothing changes. + assert_eq!(s.execute(COLOR_MASK, &hide_white()).unwrap()["changed"], 0); + assert_eq!(undo_len(&s), steps, "no undo step"); + // Contiguous: the white inside the block shows again. + let r = s.execute(COLOR_MASK, &json!({"background": "colors", "colors": "#ffffff", "tolerance": 0, "softness": 0})).unwrap(); + assert_eq!(r["changed"], 1); + assert_eq!((drawn(doc(&s), id, 0, 0)[3], drawn(doc(&s), id, 6, 5)), (0, WHITE)); + let r = s.execute(COLOR_MASK, &json!({})).unwrap(); + assert_eq!( + r, + json!({"background": "colors", "colors": "#ffffff", "contiguous": true, "match": "distance", "tolerance": 0.0, "softness": 0.0, "masked": true}) + ); + let steps = undo_len(&s); + assert_eq!(s.execute(REMOVE_COLOR_MASK, &json!({})).unwrap(), json!({"changed": 1, "ids": [id.0]})); + assert_eq!(undo_len(&s), steps + 1); + assert_eq!((mask_of(doc(&s), id), drawn(doc(&s), id, 0, 0)), (None, WHITE)); + // Nothing left to remove: the command is not enabled, and adds no undo step. + let e = s.execute(REMOVE_COLOR_MASK, &json!({})).unwrap_err(); + assert!(e.to_string().contains("select an image with a color mask"), "{e}"); + assert_eq!(undo_len(&s), steps + 1); +} + +#[test] +fn applying_the_mask_makes_it_part_of_the_pixels() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let m = mask_of(doc(&s), id).unwrap(); + let steps = undo_len(&s); + assert_eq!(s.execute(APPLY_COLOR_MASK, &json!({})).unwrap(), json!({"changed": 1, "ids": [id.0]})); + let d = doc(&s); + assert_eq!((image_of(d, id).key, mask_of(d, id)), (m.key.clone(), None)); + let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8(); + assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, RED)); + assert_eq!(drawn(d, id, 0, 0)[3], 0); + assert_eq!(undo_len(&s), steps + 1); + assert!(s.execute(APPLY_COLOR_MASK, &json!({})).is_err(), "no mask left"); +} + +/// The bytes of the first `data:image/png;base64,` image in `svg`. +fn svg_image(svg: &str) -> DynamicImage { + let at = svg.find("data:image/png;base64,").expect("an embedded PNG") + "data:image/png;base64,".len(); + let end = at + svg[at..].find('"').unwrap(); + image::load_from_memory(&vectorcraft_format::base64_decode(&svg[at..end]).unwrap()).unwrap() +} + +#[test] +fn outputs_write_the_masked_pixels() { + let (mut s, _) = open(&framed()); + let export = + |s: &Session, format: &str| crate::cmd::fileio::encode_all(doc(s), format, &json!({"useArtboards": true})).unwrap().files.remove(0).1; + let (png0, svg0, pdf0, eps0) = (export(&s, "png"), export(&s, "svg"), export(&s, "pdf"), export(&s, "eps")); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let alpha = |bytes: &[u8]| image::load_from_memory(bytes).unwrap().to_rgba8().get_pixel(0, 0).0[3]; + assert_eq!((alpha(&png0), alpha(&export(&s, "png"))), (255, 0), "PNG"); + let svg_alpha = |bytes: &[u8]| svg_image(std::str::from_utf8(bytes).unwrap()).to_rgba8().get_pixel(0, 0).0[3]; + assert_eq!((svg_alpha(&svg0), svg_alpha(&export(&s, "svg"))), (255, 0), "SVG"); + let has = |bytes: &[u8], what: &[u8]| bytes.windows(what.len()).any(|w| w == what); + assert!(!has(&pdf0, b"/SMask") && has(&export(&s, "pdf"), b"/SMask"), "PDF: the image with an alpha channel"); + assert!(!has(&eps0, b"/MaskColor") && has(&export(&s, "eps"), b"/MaskColor"), "EPS: the hidden pixels masked out"); +} + +#[test] +fn the_mask_saves_and_opens_again() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let saved = vectorcraft_format::save_file(doc(&s)); + let back = vectorcraft_format::load(&saved).unwrap(); + assert_eq!(mask_of(&back, id), mask_of(doc(&s), id)); + let m = mask_of(&back, id).unwrap(); + assert_eq!(back.images[&m.key].bytes, doc(&s).images[&m.key].bytes, "the masked pixels are saved with it"); + assert_eq!(back.images[&m.from].bytes, doc(&s).images[&m.from].bytes, "and the image's own"); + assert_eq!(drawn(&back, id, 0, 0)[3], 0); +} + +#[test] +fn copy_and_paste_carry_the_mask() { + let (mut s, _) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + super::super::DECODES.with(|c| c.set(0)); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(super::super::DECODES.with(|c| c.get()), 0, "the masked pixels come along, so nothing is decoded to make them again"); + let id = s.doc().unwrap().selection.objects[0]; + let d = doc(&s); + let m = mask_of(d, id).expect("the pasted image keeps its mask"); + assert!(m.made_for(&image_of(d, id)) && d.images.contains_key(&m.key), "with its masked pixels"); + assert_eq!(drawn(d, id, 0, 0)[3], 0); + assert_eq!(drawn(d, id, 4, 4), RED); +} + +#[test] +fn new_pixels_take_the_mask_again() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + // Crop Image replaces the image's own pixels: the mask is made for the cropped ones. + let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 6, 5]})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap_or(id.0)); + let d = doc(&s); + let (im, m) = (image_of(d, id), mask_of(d, id).unwrap()); + assert_eq!(m.from, im.key, "made for the cropped pixels"); + assert_eq!((drawn(d, id, 0, 0)[3], drawn(d, id, 4, 4)), (0, RED)); + // Pixels put in place by any edit (a link read again) take it too. + let blue = png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(6, 5, |x, _| image::Rgba(if x < 3 { WHITE } else { [0, 0, 200, 255] })))); + s.edit("Swap", |d, _| { + let blob = ImageBlob::png(blue); + let key = blob.content_key(); + d.images.insert(key.clone(), blob); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = key; + } + Ok(()) + }) + .unwrap(); + let d = doc(&s); + assert_eq!(mask_of(d, id).unwrap().from, image_of(d, id).key); + assert_eq!((drawn(d, id, 0, 0)[3], drawn(d, id, 4, 0)), (0, [0, 0, 200, 255])); +} + +#[test] +fn a_document_read_with_new_pixels_takes_the_mask_again() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let mut d = doc(&s).clone(); + let blob = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(4, 4, image::Rgba(WHITE))))); + let red = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(4, 4, |x, _| image::Rgba(if x == 0 { WHITE } else { RED }))))); + let key = red.content_key(); + d.images.insert(key.clone(), red); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = key.clone(); + } + assert_eq!(drawn(&d, id, 0, 0), WHITE, "until the mask is made again, the image's own pixels"); + super::refresh(None, &mut d); + assert_eq!(mask_of(&d, id).unwrap().from, key); + assert_eq!(drawn(&d, id, 0, 0)[3], 0); + // Pixels the mask would hide entirely: the mask stays, hiding nothing. + let all = blob.content_key(); + d.images.insert(all.clone(), blob); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = all.clone(); + } + super::refresh(None, &mut d); + let m = mask_of(&d, id).unwrap(); + assert_eq!((m.key.as_str(), m.from.as_str(), m.colors.as_slice()), (all.as_str(), all.as_str(), &[[255, 255, 255]][..])); + assert_eq!(drawn(&d, id, 0, 0), WHITE); +} + +/// A new document with a selected 12 × 10 image of `blob` under `key`, linked to `/nowhere/art.png`. +fn linked(key: &str, blob: ImageBlob) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let key = key.to_string(); + let id = s + .edit("Place", |d, sel| { + d.images.insert(key.clone(), blob); + let id = d.alloc_id(); + let im = ImageObject { + key, + width: 12, + height: 10, + xf: Default::default(), + link: Some(vectorcraft_doc::LinkInfo::new("/nowhere/art.png")), + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + (s, id) +} + +/// A linked image keeps its link; outputs that refer to linked files write its masked pixels, and +/// applying the mask embeds it. +#[test] +fn a_linked_image_stays_linked_and_outputs_its_masked_pixels() { + let (mut s, id) = linked("linked", ImageBlob::png(framed())); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let d = doc(&s); + assert_eq!((image_of(d, id).key.as_str(), image_of(d, id).link.map(|l| l.path)), ("linked", Some("/nowhere/art.png".to_string()))); + assert_eq!(drawn(d, id, 0, 0)[3], 0); + // Images written as files beside the SVG: the masked pixels are written, not a link to the + // linked file. + let r = s.execute("document.serialize", &json!({"format": "svg", "images": "link"})).unwrap(); + let text = r["text"].as_str().unwrap(); + assert!(!text.contains("/nowhere/art.png"), "{text}"); + assert_eq!(r["linked"].as_array().map(Vec::len), Some(1), "{r}"); + let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + assert_eq!(svg_image(r["text"].as_str().unwrap()).to_rgba8().get_pixel(0, 0).0[3], 0); + let m = mask_of(doc(&s), id).unwrap(); + s.execute(APPLY_COLOR_MASK, &json!({})).unwrap(); + let im = image_of(doc(&s), id); + assert_eq!((im.key, im.link), (m.key, None), "applied: the masked pixels, embedded"); +} + +/// A mask that hides nothing (no pixel matches) leaves a linked image linked in outputs, and +/// applying it only takes it off: the image keeps its pixels and its link. +#[test] +fn a_mask_that_hides_nothing_keeps_the_link() { + let (mut s, id) = linked("linked", ImageBlob::png(framed())); + let r = s.execute(COLOR_MASK, &json!({"background": "colors", "colors": "#0000ff", "contiguous": false, "tolerance": 0, "softness": 0})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["hidden"].as_u64()), (Some(1), Some(0))); + assert_eq!(mask_of(doc(&s), id).unwrap().key, "linked", "the masked pixels are the image's own"); + let r = s.execute("document.serialize", &json!({"format": "svg", "images": "link"})).unwrap(); + assert!(r["text"].as_str().unwrap().contains("/nowhere/art.png"), "{r}"); + assert_eq!(s.execute(APPLY_COLOR_MASK, &json!({})).unwrap()["changed"], 1); + let im = image_of(doc(&s), id); + assert_eq!((im.key.as_str(), im.link.map(|l| l.path), mask_of(doc(&s), id)), ("linked", Some("/nowhere/art.png".to_string()), None)); +} + +/// Color Mask refuses a linked image that shows its preview and an image too large to change, +/// with its own command's errors. +#[test] +fn color_mask_refuses_previews_and_images_too_large() { + let preview = std::sync::Arc::new(framed()); + let (mut s, id) = linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }); + let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string(); + assert!(e.contains(COLOR_MASK) && e.contains("the linked image shows its preview: embed or relink it first"), "{e}"); + assert_eq!(mask_of(doc(&s), id), None); + // Without settings, the dialog's query reads the settings and opens on the defaults. + assert_eq!(s.execute(COLOR_MASK, &json!({})).unwrap()["masked"], json!(false)); + let (mut s, _) = open(&crate::tests_linkspanel::png_header(10_632, 10_631)); + let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string(); + assert!(e.contains(COLOR_MASK) && e.contains("an image of 10632 × 10631 pixels is too large to change"), "{e}"); +} + +/// Crop Image off the pixel grid cuts the image's own pixels, so the hidden colors stay in them +/// and show again once the mask is removed. +#[test] +fn cropping_off_the_pixel_grid_keeps_the_hidden_colors_in_the_pixels() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + s.execute("object.cropImage", &json!({"rect": [0.5, 0.5, 6, 5]})).unwrap(); + let d = doc(&s); + let (im, m) = (image_of(d, id), mask_of(d, id).unwrap()); + assert_eq!(m.from, im.key, "the mask is made for the cut pixels"); + let own = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + assert!(own.pixels().all(|p| p.0[3] == 255), "the cut pixels are the image's own, white included"); + assert_eq!(drawn(d, id, 0, 0)[3], 0, "white is hidden"); + s.execute(REMOVE_COLOR_MASK, &json!({"ids": [id.0]})).unwrap(); + assert_eq!(drawn(doc(&s), id, 0, 0)[3], 255); +} + +/// Apply Color Mask on a mask made for older pixels makes it again for the image's own pixels, +/// and masked pixels of another size than the object records keep its place and size. +#[test] +fn applying_a_mask_made_for_older_pixels_makes_it_again_and_keeps_the_size() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let before = doc(&s).node(id).unwrap().geometric_bounds().unwrap(); + // Pixels twice the size, put in place without an edit, so no refresh has run. + let big = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(24, 20, |x, y| { + let block = (6..18).contains(&x) && (6..14).contains(&y); + image::Rgba(if block { RED } else { WHITE }) + })))); + let key = big.content_key(); + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + d.images.insert(key.clone(), big); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = key.clone(); + } + assert_eq!(s.execute(APPLY_COLOR_MASK, &json!({})).unwrap()["changed"], 1); + let d = doc(&s); + let im = image_of(d, id); + assert_ne!(im.key, key, "the masked pixels of the new pixels"); + assert_eq!((im.width, im.height, mask_of(d, id)), (24, 20, None)); + let after = d.node(id).unwrap().geometric_bounds().unwrap(); + assert!((after.width() - before.width()).abs() < 1e-9 && (after.height() - before.height()).abs() < 1e-9, "{before:?} {after:?}"); + let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(10, 10).0), (0, RED)); +} + +/// A 12 × 10 grayscale image without alpha: white, with a black block from (3, 3) to (9, 7). +fn gray_framed() -> Vec { + png(DynamicImage::ImageLuma8(image::GrayImage::from_fn(12, 10, |x, y| { + image::Luma([if (3..9).contains(&x) && (3..7).contains(&y) { 0 } else { 255 }]) + }))) +} + +/// Masked pixels have an alpha channel: a grayscale image colorized with a process color can't +/// take a mask, and a masked one can't take a process color. +#[test] +fn a_process_color_does_not_colorize_masked_gray_pixels() { + const REFUSED: &str = "a process color can't colorize a grayscale image with transparency"; + let (mut s, id) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + assert!(doc(&s).node(id).unwrap().extras().colorize.is_some(), "a gray image without alpha takes a process color"); + let (before, steps) = (doc(&s).clone(), undo_len(&s)); + let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string(); + assert!(e.contains(REFUSED), "{e}"); + assert_eq!((doc(&s), undo_len(&s)), (&before, steps)); + // Black colorizes gray pixels with alpha: the mask is set, then a process color is refused. + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + assert_eq!(s.execute(COLOR_MASK, &hide_white()).unwrap()["changed"], 1); + let e = s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap_err().to_string(); + assert!(e.contains(REFUSED), "{e}"); +} + +/// Another image that already has an alpha channel and a process colorize color, as an opened file +/// can hold, neither lets a grayscale image colorized with a process color take a mask nor stops a +/// mask on an image that can take one. +#[test] +fn another_image_colorized_with_transparency_does_not_change_the_refusal() { + const REFUSED: &str = "a process color can't colorize a grayscale image with transparency"; + let (mut s, id) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let held = ImageBlob::png(png(DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_pixel(2, 2, image::LumaA([128, 100]))))); + s.edit("Place", |d, _| { + let key = held.content_key(); + d.images.insert(key.clone(), held.clone()); + let other = d.alloc_id(); + let im = ImageObject { key, width: 2, height: 2, xf: Default::default(), link: None, placement: Default::default(), pixels: None }; + let mut n = Node::new(other, NodeKind::Image(Box::new(im))); + n.extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + d.insert(d.default_layer(), 0, n)?; + Ok(()) + }) + .unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, vec![id], "only the gray image is selected"); + let (before, steps) = (doc(&s).clone(), undo_len(&s)); + let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string(); + assert!(e.contains(COLOR_MASK) && e.contains(REFUSED), "{e}"); + assert_eq!((doc(&s), undo_len(&s)), (&before, steps), "with another image refused already, nothing changes"); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + assert_eq!(s.execute(COLOR_MASK, &hide_white()).unwrap()["changed"], 1, "an image colorized with black takes the mask beside the other"); + let m = mask_of(doc(&s), id).unwrap(); + let masked = image::load_from_memory(&doc(&s).images[&m.key].bytes).unwrap().to_luma_alpha8(); + assert_eq!((masked.get_pixel(0, 0).0[1], masked.get_pixel(4, 4).0[1]), (0, 255), "white is hidden and black shows"); +} + +/// The mask is made from the image's own pixels: a grayscale image colorized with a process color +/// is refused even when an earlier mask, as an opened file can hold, shows color pixels. +#[test] +fn a_gray_image_whose_earlier_mask_shows_color_pixels_is_refused() { + let (mut s, id) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let rgb = ImageBlob::png(framed()); + s.edit("Mask", |d, _| { + let key = rgb.content_key(); + d.images.insert(key.clone(), rgb.clone()); + let from = image_of(d, id).key; + let mask = ColorMask { key, from, ..mask_of_settings() }; + d.node_mut(id).unwrap().extras_mut().color_mask = Some(Box::new(mask)); + Ok(()) + }) + .unwrap(); + let (before, steps) = (doc(&s).clone(), undo_len(&s)); + let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string(); + assert!(e.contains("a process color can't colorize a grayscale image with transparency"), "{e}"); + assert_eq!((doc(&s), undo_len(&s)), (&before, steps)); +} + +/// Remove Background clears the image's own pixels: a grayscale image colorized with a process +/// color is refused even when an earlier mask, as an opened file can hold, shows color pixels. +#[test] +fn remove_background_refuses_a_gray_image_whose_earlier_mask_shows_color_pixels() { + let (mut s, id) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let rgb = ImageBlob::png(framed()); + let key = rgb.content_key(); + s.edit("Mask", |d, _| { + d.images.insert(key.clone(), rgb.clone()); + let from = image_of(d, id).key; + let mask = ColorMask { key: key.clone(), from, ..mask_of_settings() }; + d.node_mut(id).unwrap().extras_mut().color_mask = Some(Box::new(mask)); + Ok(()) + }) + .unwrap(); + let d = doc(&s); + let n = d.node(id).unwrap(); + let NodeKind::Image(im) = &n.kind else { panic!("an image") }; + assert_eq!(d.shown_image(n, im).key, key, "the image shows the color pixels"); + let (before, steps) = (doc(&s).clone(), undo_len(&s)); + let e = s.execute(super::super::REMOVE_BACKGROUND, &hide_white()).unwrap_err().to_string(); + assert!(e.contains("a process color can't colorize a grayscale image with transparency"), "{e}"); + assert_eq!((doc(&s), undo_len(&s)), (&before, steps)); +} + +/// A mask that hides nothing leaves the image's own pixels without transparency, so a grayscale +/// image colorized with a process color takes it. +#[test] +fn a_mask_that_hides_nothing_on_a_gray_image_colorized_with_a_process_color_is_set() { + let (mut s, id) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let none = json!({"background": "colors", "colors": "#808080", "contiguous": false, "tolerance": 0, "softness": 0}); + let r = s.execute(COLOR_MASK, &none).unwrap(); + assert_eq!((r["changed"].as_u64(), r["hidden"].as_u64()), (Some(1), Some(0))); + let (m, im) = (mask_of(doc(&s), id).unwrap(), image_of(doc(&s), id)); + assert_eq!(m.key, im.key, "the masked pixels are the image's own"); + assert!(doc(&s).node(id).unwrap().extras().colorize.is_some(), "the image stays colorized"); +} + +/// New gray pixels whose colors a mask hides would take transparency, which a process color can't +/// colorize: the mask made again for them hides nothing, and Apply Color Mask refuses them. +#[test] +fn new_gray_pixels_under_a_process_color_are_not_masked() { + const REFUSED: &str = "a process color can't colorize a grayscale image with transparency"; + let gray = json!({"background": "colors", "colors": "#808080", "contiguous": false, "tolerance": 0, "softness": 0}); + let swapped = + || ImageBlob::png(png(DynamicImage::ImageLuma8(image::GrayImage::from_fn(12, 10, |x, _| image::Luma([if x < 6 { 128 } else { 0 }]))))); + let setup = || { + let (mut s, id) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + assert_eq!(s.execute(COLOR_MASK, &gray).unwrap()["hidden"], 0, "no pixel is gray yet"); + (s, id) + }; + // Pixels put in place by an edit: the mask is made again for them and hides nothing. + let (mut s, id) = setup(); + s.edit("Swap", |d, _| { + let blob = swapped(); + let key = blob.content_key(); + d.images.insert(key.clone(), blob); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = key; + } + Ok(()) + }) + .unwrap(); + let d = doc(&s); + let (im, m) = (image_of(d, id), mask_of(d, id).unwrap()); + assert_eq!((m.from.as_str(), m.key.as_str()), (im.key.as_str(), im.key.as_str()), "the mask hides nothing"); + assert_eq!(crate::cmd::paint::check_colorized(d), Ok(())); + // Pixels put in place without an edit: Apply Color Mask makes the mask again and refuses it. + let (mut s, id) = setup(); + let blob = swapped(); + let key = blob.content_key(); + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + d.images.insert(key.clone(), blob); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = key; + } + let (before, steps) = (doc(&s).clone(), undo_len(&s)); + let e = s.execute(APPLY_COLOR_MASK, &json!({})).unwrap_err().to_string(); + assert!(e.contains(APPLY_COLOR_MASK) && e.contains(REFUSED), "{e}"); + assert_eq!((doc(&s), undo_len(&s)), (&before, steps)); +} + +/// A mask that hides white, made for another document's image (only its settings are of use). +fn mask_of_settings() -> ColorMask { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + mask_of(doc(&s), id).unwrap() +} + +/// Images outside the layers (a symbol's art, opacity-mask art) take their masks again too when +/// their own pixels are replaced, as Update Link replaces them there. +#[test] +fn masks_outside_the_layers_are_made_again() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let mut d = doc(&s).clone(); + let masked = d.node(id).unwrap().clone(); + let red = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(4, 4, |x, _| image::Rgba(if x == 0 { WHITE } else { RED }))))); + let key = red.content_key(); + d.images.insert(key.clone(), red); + let mut moved = masked.clone(); + if let NodeKind::Image(im) = &mut moved.kind { + im.key = key.clone(); + } + d.symbols.push(vectorcraft_doc::Symbol { name: "Logo".into(), art: std::sync::Arc::new(moved.clone()), dynamic: false }); + let holder_id = d.alloc_id(); + let mut holder = vectorcraft_doc::Node::new(holder_id, NodeKind::Group { children: vec![], clip: false }); + holder.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(moved, false))); + d.insert(d.default_layer(), 0, holder).unwrap(); + super::refresh(None, &mut d); + let from = |n: &vectorcraft_doc::Node| Document::color_mask_of(n).unwrap().from.clone(); + assert_eq!(from(&d.symbols.last().unwrap().art), key, "in the symbol's art"); + let art = &d.node(holder_id).unwrap().extras().mask.as_ref().unwrap().art; + assert_eq!(from(art), key, "in the opacity mask's art"); + let m = Document::color_mask_of(art).unwrap(); + let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8(); + assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(1, 0).0), (0, RED)); +} + +/// `ids` stand in for the selection: an image that is not selected is changed by its id. +#[test] +fn images_given_by_id_need_not_be_selected() { + let (mut s, id) = open(&framed()); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!( + s.execute(COLOR_MASK, &json!({"ids": [id.0], "background": "colors", "colors": "#fff", "tolerance": 0, "softness": 0})).unwrap()["changed"], + 1 + ); + assert_eq!(s.execute(REMOVE_COLOR_MASK, &json!({"ids": [id.0]})).unwrap()["changed"], 1); + s.execute(COLOR_MASK, &json!({"ids": [id.0], "background": "colors", "colors": "#fff", "tolerance": 0, "softness": 0})).unwrap(); + assert_eq!(s.execute(APPLY_COLOR_MASK, &json!({"ids": [id.0]})).unwrap()["changed"], 1); + assert_eq!(mask_of(doc(&s), id), None); +} + +#[test] +fn what_cannot_be_masked_is_refused_and_nothing_changes() { + let (mut s, id) = open(&framed()); + let steps = undo_len(&s); + let e = s.execute(COLOR_MASK, &json!({"tolerance": 101})).unwrap_err(); + assert!(e.to_string().contains("`tolerance` must be from 0 to 100"), "{e}"); + let e = s + .execute(COLOR_MASK, &json!({"background": "colors", "colors": "#fff, #c80000", "contiguous": false, "tolerance": 0, "softness": 0})) + .unwrap_err(); + assert!(e.to_string().contains("the mask would hide every pixel"), "{e}"); + assert_eq!((mask_of(doc(&s), id), undo_len(&s)), (None, steps)); + let inks = vectorcraft_doc::cmyk::Inks::new(4, 2, [0, 0, 0, 0].repeat(8)).unwrap(); + let (mut s, _) = open(&ImageBlob::cmyk_tiff(&inks).unwrap().bytes); + let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err(); + assert!(e.to_string().contains("a CMYK image can't take a color mask"), "{e}"); + // Without settings, the dialog's query reads the settings and opens on the defaults. + assert_eq!(s.execute(COLOR_MASK, &json!({})).unwrap()["masked"], json!(false)); +} + +/// Remove Color Mask and Apply Color Mask refuse an object in `ids` that is not an image, as +/// Color Mask does. +#[test] +fn an_object_that_is_not_an_image_is_refused() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap()["id"].as_u64().unwrap(); + let steps = undo_len(&s); + for cmd in [COLOR_MASK, REMOVE_COLOR_MASK, APPLY_COLOR_MASK] { + let mut p = if cmd == COLOR_MASK { hide_white() } else { json!({}) }; + p["ids"] = json!([id.0, rect]); + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains(&format!("object {rect} is not an image")), "{cmd}: {e}"); + } + assert!(mask_of(doc(&s), id).is_some()); + assert_eq!(undo_len(&s), steps); +} + +/// A mask that can't be made for the image's pixels (they are missing) is not made again on every +/// later edit: the art holding it is left as it is. +#[test] +fn a_mask_that_cannot_be_made_is_not_made_again_on_every_edit() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let mut d = doc(&s).clone(); + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.key = "gone".into(); + } + super::refresh(None, &mut d); + assert_eq!(mask_of(&d, id).unwrap().key, "gone", "it hides nothing"); + let layer = d.layers[0].clone(); + super::refresh(None, &mut d); + assert!(std::sync::Arc::ptr_eq(&layer, &d.layers[0]), "the second pass changes nothing"); +} + +/// The original of a pattern being edited takes its masks again too. +#[test] +fn the_pattern_being_edited_takes_its_masks_again() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let mut d = doc(&s).clone(); + let mut art = d.node(id).unwrap().clone(); + let red = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(4, 4, |x, _| image::Rgba(if x == 0 { WHITE } else { RED }))))); + let key = red.content_key(); + d.images.insert(key.clone(), red); + if let NodeKind::Image(im) = &mut art.kind { + im.key = key.clone(); + } + let original = vectorcraft_doc::PatternDef::new("Tile", vec![std::sync::Arc::new(art)]); + d.pattern_edit = Some(vectorcraft_doc::PatternEdit { pattern: "Tile".into(), layer: NodeId(999_999), original: Some(original) }); + super::refresh(None, &mut d); + let original = d.pattern_edit.as_ref().and_then(|e| e.original.as_ref()).unwrap(); + assert_eq!(Document::color_mask_of(&original.art[0]).unwrap().from, key); +} + +/// A linked file read again as the document opens (Update Links: Automatically) takes the mask +/// for its new pixels. +#[test] +fn a_linked_file_read_again_on_open_takes_the_mask_again() { + let dir = crate::tests_links::Folder::new("color-mask"); + let pic = dir.file("art.png"); + crate::tests_links::write(&pic, &framed()); + let mut s = crate::tests_links::session(); + let id = crate::tests_links::place(&mut s, &pic); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let saved = dir.file("art.vectorcraft"); + crate::tests_links::save(&mut s, &saved); + // New pixels in the file: blue where the block was red. + let blue = png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(12, 10, |x, y| { + image::Rgba(if (3..9).contains(&x) && (3..7).contains(&y) { [0, 0, 200, 255] } else { WHITE }) + }))); + crate::tests_links::write(&pic, &blue); + s.execute("prefs.set", &json!({"key": "updateLinks", "value": "automatically"})).unwrap(); + let r = crate::tests_links::open(&mut s, &saved); + assert_eq!(r["updatedLinks"][0]["ids"], json!([id.0]), "{r}"); + let d = doc(&s); + let (im, m) = (image_of(d, id), mask_of(d, id).unwrap()); + assert_eq!(m.from, im.key, "made for the file's new pixels"); + let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8(); + assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, [0, 0, 200, 255])); +} + +/// The bytes of every file `format` writes for `d` with `p`. +fn written(d: &Document, format: &str, p: Value) -> Vec> { + crate::cmd::fileio::encode_all(d, format, &p).unwrap().files.into_iter().map(|f| f.1).collect() +} + +/// `out` for the opened image without a mask, with one hiding its red block, and with the mask +/// removed again: the mask changes what is written, and removing it gives the same output as +/// before. (Outputs that flatten see-through pixels over the white page show the hidden block as +/// white.) +fn written_with_the_mask(out: impl Fn(&Document) -> T) { + let (mut s, _) = open(&framed()); + let plain = out(doc(&s)); + s.execute(COLOR_MASK, &json!({"background": "colors", "colors": "#c80000", "contiguous": false, "tolerance": 0, "softness": 0})).unwrap(); + let masked = out(doc(&s)); + s.execute(REMOVE_COLOR_MASK, &json!({})).unwrap(); + assert_ne!(plain, masked, "the masked pixels are written"); + assert_eq!(out(doc(&s)), plain, "without the mask, the image's own"); +} + +#[test] +fn dxf_writes_the_masked_pixels() { + written_with_the_mask(|d| written(d, "dxf", json!({}))); +} + +#[test] +fn emf_and_wmf_write_the_masked_pixels() { + written_with_the_mask(|d| written(d, "emf", json!({}))); + written_with_the_mask(|d| written(d, "wmf", json!({}))); +} + +#[test] +fn legacy_ai_writes_the_masked_pixels() { + written_with_the_mask(|d| written(d, "ai", json!({"aiVersion": 7}))); +} + +#[test] +fn ai_editing_data_writes_the_masked_pixels() { + let o = vectorcraft_eps::AiEditingOptions { title: "art".into(), created: Some(0) }; + written_with_the_mask(|d| vectorcraft_eps::export_ai_editing(d, &o).unwrap().program); +} + +/// PDF/X-1a and PDF/X-3 flatten a masked image, whose hidden pixels are transparency, and write no +/// soft mask. +#[test] +fn pdf_x1a_and_x3_flatten_the_hidden_pixels() { + for standard in ["pdfX1a", "pdfX3"] { + let (mut s, _) = open(&framed()); + let export = |s: &mut Session| { + let v = s.execute("document.exportPdf", &json!({"standard": standard, "compression": {"compressText": false}})).unwrap(); + let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + (String::from_utf8_lossy(&bytes).into_owned(), v["warnings"].to_string()) + }; + let (_, warnings) = export(&mut s); + assert!(!warnings.contains("flattened"), "{standard}, an opaque image: {warnings}"); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let (text, warnings) = export(&mut s); + assert!(warnings.contains("flattened"), "{standard}: {warnings}"); + assert!(!text.contains("/SMask"), "{standard}"); + } +} + +/// The legacy .ai flattens a masked image, whose hidden pixels are transparency, as it flattens an +/// image whose background was removed, and `transparentImages: "omit"` leaves both out. +#[test] +fn legacy_ai_flattens_a_masked_image_as_a_see_through_one() { + let warnings = |s: &Session, p: &Value| crate::cmd::fileio::encode_all(doc(s), "ai", p).unwrap().notes(); + let (mut masked, _) = open(&framed()); + masked.execute(COLOR_MASK, &hide_white()).unwrap(); + let (mut cleared, _) = open(&framed()); + cleared.execute(super::super::REMOVE_BACKGROUND, &hide_white()).unwrap(); + for (p, said) in [(json!({"aiVersion": 7}), "are flattened"), (json!({"aiVersion": 7, "transparentImages": "omit"}), "are left out")] { + let w = warnings(&masked, &p); + assert!(w.iter().any(|w| w.contains("transparent images") && w.contains(said)), "{p}: {w:?}"); + assert_eq!(w, warnings(&cleared, &p), "{p}"); + } +} + +/// A live color adjustment recolors the masked pixels too: the hidden colors stay hidden on the +/// canvas and in outputs that apply the adjustment. +#[test] +fn a_live_color_adjustment_keeps_the_hidden_colors_hidden() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + s.execute("effect.apply", &json!({"effect": "adjust.hueSaturation", "params": {"hue": 120}})).unwrap(); + let d = doc(&s); + assert_eq!(drawn(d, id, 1, 1)[3], 0, "the hidden white"); + let block = drawn(d, id, 4, 4); + assert!(block[3] == 255 && block != RED, "the red block, recolored: {block:?}"); + let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let px = svg_image(r["text"].as_str().unwrap()).to_rgba8(); + assert_eq!(px.get_pixel(1, 1).0[3], 0, "SVG: the hidden white"); + assert!(px.get_pixel(4, 4).0[3] == 255 && px.get_pixel(4, 4).0 != RED, "SVG: the red block, recolored"); +} + +/// An image whose masked pixels are missing from the document is drawn and expanded from its own +/// pixels with a live color adjustment, as it is drawn without one. +#[test] +fn a_live_color_adjustment_recolors_the_image_when_its_masked_pixels_are_missing() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + s.execute("effect.apply", &json!({"effect": "adjust.hueSaturation", "params": {"hue": 120}})).unwrap(); + let mut d = doc(&s).clone(); + let masked = mask_of(&d, id).unwrap().key; + assert!(d.images.remove(&masked).is_some(), "the masked pixels were in the document"); + assert_eq!(drawn(&d, id, 1, 1), WHITE, "the white shows"); + let block = drawn(&d, id, 4, 4); + assert!(block[3] == 255 && block != RED, "the red block, recolored: {block:?}"); + let node = d.node(id).unwrap().clone(); + let out = vectorcraft_render::effects::adjust_in_document(&mut d, &node, None).unwrap(); + let NodeKind::Image(im) = &out.kind else { panic!("an image") }; + assert_ne!(im.key, image_of(&d, id).key, "the expanded image is recolored"); + assert_eq!(Document::color_mask_of(&out), None, "the expanded image has no mask to make again from the recolored pixels"); + let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + assert_eq!(px.get_pixel(1, 1).0, WHITE, "the expanded image shows the white"); +} + +/// An envelope warp draws the image's masked pixels in its pieces. +#[test] +fn an_envelope_warp_draws_the_masked_pixels() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let (white, red) = (pixel_at(doc(&s), id, 1, 1), pixel_at(doc(&s), id, 4, 4)); + s.execute("object.envelope.makeWithWarp", &json!({"style": "arch", "bend": 0})).unwrap(); + assert_eq!(drawn_at(doc(&s), white)[3], 0, "the hidden white"); + assert!(drawn_at(doc(&s), red)[3] > 0, "the red block"); +} + +/// A geometry effect draws the image's masked pixels, and Expand Appearance keeps the mask on the +/// image it makes. +#[test] +fn a_transform_effect_keeps_the_mask() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let moved = |p: vectorcraft_geom::Point| vectorcraft_geom::Point::new(p.x + 30.0, p.y); + let (white, red) = (moved(pixel_at(doc(&s), id, 1, 1)), moved(pixel_at(doc(&s), id, 4, 4))); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap(); + assert_eq!(drawn_at(doc(&s), white)[3], 0, "the hidden white"); + assert_eq!(drawn_at(doc(&s), red), RED, "the red block"); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let mut masks = vec![]; + doc(&s).walk(|n| masks.extend(Document::color_mask_of(n).cloned())); + assert_eq!(masks.len(), 1, "the expanded image keeps its mask"); +} + +/// A pattern whose tile holds a masked image counts as one with a see-through image, so outputs +/// without transparency expand it before they flatten. +#[test] +fn a_pattern_tile_with_a_masked_image_counts_as_see_through() { + let href = format!("data:image/png;base64,{}", vectorcraft_format::base64_encode(&framed())); + let svg = format!( + r##""## + ); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "p.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap(); + let mut d = doc(&s).clone(); + let see_through = + |d: &Document| crate::cmd::expand::has_transparent_image_patterns(d, &crate::cmd::flatten::see_through_images(d), &|_, _| false); + assert!(!see_through(&d), "an opaque tile"); + let hidden = png(DynamicImage::ImageRgba8(image::RgbaImage::from_fn(12, 10, |x, _| image::Rgba(if x == 0 { [0; 4] } else { RED })))); + d.images.insert("masked".into(), ImageBlob::png(hidden)); + fn image_in(n: &mut vectorcraft_doc::Node) -> Option<&mut vectorcraft_doc::Node> { + if matches!(n.kind, NodeKind::Image(_)) { + return Some(n); + } + n.children_mut()?.iter_mut().find_map(|c| image_in(std::sync::Arc::make_mut(c))) + } + let node = d.patterns.iter_mut().flat_map(|p| p.art.iter_mut()).find_map(|a| image_in(std::sync::Arc::make_mut(a))).unwrap(); + let NodeKind::Image(im) = &node.kind else { panic!("the tile's image") }; + let from = im.key.clone(); + node.extras_mut().color_mask = Some(Box::new(ColorMask { + key: "masked".into(), + from, + background: MaskBackground::Colors, + colors: vec![[255, 255, 255]], + contiguous: false, + measure: vectorcraft_doc::color_mask::MaskMatch::Distance, + tolerance: 0.0, + softness: 0.0, + })); + assert!(see_through(&d), "the tile shows its masked pixels"); +} + +/// SVG writes a colorized gray image with a mask as the coverage of its masked pixels, shared by +/// the objects that show it. +#[test] +fn svg_writes_a_colorized_masked_image_as_it_shows() { + let (mut s, _) = open(&gray_framed()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute(COLOR_MASK, &json!({"background": "colors", "colors": "#000000", "contiguous": false, "tolerance": 0, "softness": 0})).unwrap(); + s.execute("edit.duplicate", &json!({})).unwrap(); + let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let text = r["text"].as_str().unwrap(); + assert_eq!(text.matches("data:image/png;base64,").count(), 1, "one shared image: {text}"); + assert_eq!(svg_image(text).to_rgba8().get_pixel(4, 4).0[3], 0, "the hidden black block covers nothing"); +} + +/// The opened masked image moved into what `wrap` makes of it (given the document, to take ids +/// from, and the image node). +fn wrapped(wrap: impl FnOnce(&mut Document, vectorcraft_doc::Node) -> vectorcraft_doc::Node) -> (Session, NodeId) { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + s.edit("Wrap", |d, _| { + let (parent, index, _) = d.position(id).unwrap(); + let image = (*d.remove(id)?).clone(); + let holder = wrap(d, image); + d.insert(parent, index, holder)?; + Ok(()) + }) + .unwrap(); + (s, id) +} + +/// The rectangle of the opened image's frame (12 × 10 at the origin) filled with `fill`. +fn frame(d: &mut Document, fill: vectorcraft_color::Paint) -> vectorcraft_doc::Node { + let rect = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 12.0, 10.0)); + vectorcraft_doc::Node::path(d.alloc_id(), rect, vectorcraft_doc::Appearance::basic(fill, vectorcraft_color::Paint::None, 0.0)) +} + +/// An image in a clip group of its own frame, which the canvas draws straight into the clipping +/// path, shows its masked pixels. +#[test] +fn a_clipped_image_draws_its_masked_pixels() { + let (s, id) = wrapped(|d, image| { + let clip = frame(d, vectorcraft_color::Paint::None); + vectorcraft_doc::Node::new( + d.alloc_id(), + NodeKind::Group { children: vec![std::sync::Arc::new(clip), std::sync::Arc::new(image)], clip: true }, + ) + }); + assert_eq!((drawn(doc(&s), id, 0, 0)[3], drawn(doc(&s), id, 4, 4)), (0, RED)); +} + +/// An image whose opacity mask is one white shape, which the canvas draws straight into the +/// shape, shows its masked pixels. +#[test] +fn an_image_masked_by_a_white_shape_draws_its_masked_pixels() { + let (s, id) = wrapped(|d, image| { + let white = frame(d, vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE)); + image.with_mask(Some(Box::new(vectorcraft_doc::OpacityMask::new(white, true)))) + }); + assert_eq!((drawn(doc(&s), id, 0, 0)[3], drawn(doc(&s), id, 4, 4)), (0, RED)); +} + +/// Pasting into a document that has other pixels under the image's names renames them, and the +/// mask follows: the masked pixels come along under their new name, nothing is decoded again. +#[test] +fn paste_renames_the_masked_pixels_with_the_image() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let m = mask_of(doc(&s), id).unwrap(); + let masked = doc(&s).images[&m.key].bytes.clone(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let other = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(2, 2, image::Rgba(RED))))); + s.edit("Taken names", |d, _| { + d.images.insert(m.key.clone(), other.clone()); + d.images.insert(m.from.clone(), other.clone()); + Ok(()) + }) + .unwrap(); + super::super::DECODES.with(|c| c.set(0)); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(super::super::DECODES.with(|c| c.get()), 0, "nothing is decoded to make the mask again"); + let id = s.doc().unwrap().selection.objects[0]; + let d = doc(&s); + let (im, pasted) = (image_of(d, id), mask_of(d, id).unwrap()); + assert!(pasted.key != m.key && pasted.from != m.from, "renamed: {pasted:?}"); + assert!(pasted.made_for(&im)); + assert_eq!(d.images[&pasted.key].bytes, masked); + assert_eq!((drawn(d, id, 0, 0)[3], drawn(d, id, 4, 4)), (0, RED)); +} + +/// Placing a document (as an editable copy) whose image has a mask brings the masked pixels, and +/// the mask follows names the placing document already uses for other pixels. +#[test] +fn placing_a_document_brings_the_masked_pixels() { + let (mut s, id) = open(&framed()); + s.execute(COLOR_MASK, &hide_white()).unwrap(); + let m = mask_of(doc(&s), id).unwrap(); + let file = vectorcraft_format::save_file(doc(&s)); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let other = ImageBlob::png(png(DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(2, 2, image::Rgba(RED))))); + s.edit("Taken names", |d, _| { + d.images.insert(m.from.clone(), other.clone()); + Ok(()) + }) + .unwrap(); + super::super::DECODES.with(|c| c.set(0)); + let r = + s.execute("file.place", &json!({"name": "art.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&file), "link": false})).unwrap(); + assert_eq!(super::super::DECODES.with(|c| c.get()), 0, "nothing is decoded to make the mask again: {r}"); + let d = doc(&s); + let mut found = vec![]; + for root in d.art_roots() { + root.walk(&mut |n| { + if let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) { + found.push(((**im).clone(), m.clone())); + } + }); + } + let [(im, placed)] = found.as_slice() else { panic!("one masked image: {found:?}") }; + assert!(placed.made_for(im) && placed.from != m.from, "the image was renamed and the mask follows: {placed:?}"); + let px = image::load_from_memory(&d.images[&placed.key].bytes).unwrap().to_rgba8(); + assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, RED)); +} diff --git a/crates/engine/src/cmd/addons/image/tests.rs b/crates/engine/src/cmd/addons/image/tests.rs index d57f58046f..ae59efad87 100644 --- a/crates/engine/src/cmd/addons/image/tests.rs +++ b/crates/engine/src/cmd/addons/image/tests.rs @@ -392,7 +392,7 @@ fn the_color_profile_is_kept() { encoder.set_icc_profile(icc.clone()).unwrap(); DynamicImage::ImageRgba8(framed()).write_with_encoder(encoder).unwrap(); let blob = ImageBlob::png(bytes); - let out = super::clear(&blob, &settings(Background::Edges), None).unwrap().unwrap(); + let out = super::clear(&blob, &settings(Background::Edges), None, super::C).unwrap().unwrap(); let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(out.blob.bytes.as_slice())).unwrap(); assert_eq!(decoder.icc_profile().unwrap(), Some(icc)); } diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 291c221756..bdb238ce83 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -123,6 +123,10 @@ fn node_refs(n: &Node, f: Visit) { if let Some(mask) = &m.extras().mask { node_refs(&mask.art, f); } + // A color-masked image's masked pixels go with it. + if let Some(cm) = Document::color_mask_of(m) { + f(Ref::Name(Res::Image, &cm.key)); + } match &m.kind { NodeKind::Text(t) => { for r in &t.runs { @@ -663,6 +667,10 @@ impl Relink { if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { self.node(Arc::make_mut(&mut m.art)); } + if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) { + self.name(Res::Image, &mut cm.key); + self.name(Res::Image, &mut cm.from); + } match &mut n.kind { NodeKind::Text(t) => { for r in &mut t.runs { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 985d54fa50..256578f9b2 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -23,7 +23,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, 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: 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), 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/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 8040b0016c..72a72e6411 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -94,7 +94,7 @@ fn effect_specs() -> Vec { "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", can_expand, expand_appearance ), @@ -848,8 +848,9 @@ fn load_texture(params: &mut Value, cmd: &str) -> Result<()> { /// Has `n` an appearance Expand Appearance turns into objects: a path that isn't basic (several /// fills or strokes, effects, transparency of a fill or stroke, a brush), a group or layer with -/// fills, strokes or effects of its own or such members, other objects with effects, or type with -/// fills or strokes of its own? +/// fills, strokes or effects of its own or such members, other objects with effects, type with +/// fills or strokes of its own, or a symbol instance whose active fill or stroke has a geometry +/// effect ([`effects::has_item_geometry`])? pub(crate) fn expandable(n: &Node) -> bool { expandable_except(n, &[]) } @@ -866,7 +867,7 @@ pub(crate) fn expandable_except(n: &Node, skip: &[NodeId]) -> bool { !n.appearance.items.is_empty() || !n.appearance.effects.is_empty() || children.iter().any(|c| expandable_except(c, skip)) } NodeKind::Text(_) => !n.appearance.items.is_empty() || !n.appearance.effects.is_empty(), - NodeKind::Image(_) => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(), + NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(), _ => !n.appearance.effects.is_empty(), } } @@ -939,6 +940,38 @@ fn expand_pieces( expanded } +/// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose +/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as +/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so +/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more +/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art +/// would take the objects placed so far past `budget`. +fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) { + for c in m.children_mut().into_iter().flatten() { + if !matches!(c.kind, NodeKind::SymbolInstance { .. }) { + if c.children().is_some() { + expand_nested_instances(d, Arc::make_mut(c), depth, budget); + } + continue; + } + let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue }; + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) { + continue; + } + let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue }; + let count = sym.art.count() as u64; + if count > *budget { + continue; + } + *budget -= count; + let art = vectorcraft_render::instance_art(&sym.art, c); + if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) { + expand_nested_instances(d, &mut a, depth + 1, budget); + *c = Arc::new(a); + } + } +} + /// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids? fn repeats_an_id(n: &Node, seen: &std::collections::HashSet) -> bool { let mut ids = std::collections::HashSet::new(); @@ -1094,6 +1127,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br _ => None, }; effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| { + let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES; + expand_nested_instances(d, &mut m, 1, &mut budget); expand_pieces(d, &mut m, true, brushes, &mut stroke_art); m }) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 40b8e26060..0f55386830 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -884,8 +884,8 @@ fn blended(n: &Node) -> bool { n.opacity < 1.0 || n.blend != BlendMode::Normal } -/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`), a -/// colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in +/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`, a +/// color-masked image's masked pixels counted as its own), a colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in /// `n`, or anywhere when `on`, also in the tile art of the pattern fills of the paths in `n`, down /// to `levels` patterns. Hidden art doesn't count. fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool, levels: u32) -> bool { @@ -894,7 +894,9 @@ fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet, colorize: } let on = on || blended(n); match &n.kind { - NodeKind::Image(im) => on || keys.contains(&im.key) || (n.extras().colorize.is_some() && colorize(d, n)), + NodeKind::Image(im) => { + on || keys.contains(&im.key) || keys.contains(&d.shown_image(n, im).key) || (n.extras().colorize.is_some() && colorize(d, n)) + } NodeKind::Path { .. } | NodeKind::Compound { .. } => { n.appearance.items.iter().any(|i| pattern_fill_holds_transparent_image(d, i, keys, colorize, on, levels)) } diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index 6ee826d5ea..05b6e03551 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -185,7 +185,8 @@ fn expand_image_patterns(d: &mut Document) -> Result<()> { } /// The images of `d` a legacy `.ai` can't hold, in paint order with their places in it (as -/// [`Document::walk`] counts). These have see-through pixels or a colorize paint (except the +/// [`Document::walk`] counts). These have see-through pixels (a color-masked image's masked pixels +/// counted as its own) or a colorize paint (except the /// colorized images the writer writes as image masks, clear pixels included, /// [`vectorcraft_eps::writes_image_mask`]), or /// have opacity or a blending mode of their own or, with `flatten`, of a group they are in. @@ -197,7 +198,8 @@ fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> { let mut at = 0; d.walk(|n| { if let NodeKind::Image(im) = &n.kind - && (((keys.contains(&im.key) || n.extras().colorize.is_some()) && !vectorcraft_eps::writes_image_mask(d, n)) + && (((keys.contains(&im.key) || keys.contains(&d.shown_image(n, im).key) || n.extras().colorize.is_some()) + && !vectorcraft_eps::writes_image_mask(d, n)) || n.opacity < 1.0 || n.blend != BlendMode::Normal || (mode == SeeThrough::Flatten && transparent(d, n.id))) diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index cf7bdb7baa..4ad89c773b 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -76,12 +76,13 @@ pub(crate) fn see_through_images(doc: &Document) -> BTreeSet { doc.images.iter().filter(|(_, b)| see_through(b)).map(|(k, _)| k.clone()).collect() } -/// `n` shows an image of `keys` (itself or inside). +/// `n` shows an image of `keys` (itself or inside), a color-masked image's masked pixels counted as +/// what it shows. pub(super) fn draws_image(n: &Node, keys: &BTreeSet) -> bool { !keys.is_empty() && n.visible && match &n.kind { - NodeKind::Image(im) => keys.contains(&im.key), + NodeKind::Image(im) => keys.contains(&im.key) || Document::color_mask_of(n).is_some_and(|m| m.made_for(im) && keys.contains(&m.key)), _ => n.children().is_some_and(|ch| ch.iter().any(|c| draws_image(c, keys))), } } diff --git a/crates/engine/src/cmd/flatten/options.rs b/crates/engine/src/cmd/flatten/options.rs index a5881c76ef..16cf8e5de7 100644 --- a/crates/engine/src/cmd/flatten/options.rs +++ b/crates/engine/src/cmd/flatten/options.rs @@ -155,7 +155,8 @@ impl FlattenOptions { /// the paint ([`vectorcraft_doc::ImageBlob::takes_colorize`]) never counts: it draws uncolorized. pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool { let NodeKind::Image(im) = &n.kind else { return true }; - let blob = d.image_blob(im); + let shown = d.shown_image(n, im); + let blob = d.image_blob(&shown); if blob.is_some_and(|b| !b.takes_colorize()) { return false; } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index ab6dd3e56a..d79320c304 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1060,6 +1060,8 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps }; Nested { pick: &pick, make: &mut make, next: 0 }.run(d); } + // Color masks of images whose files were read again are made for the new pixels. + super::refresh_color_masks(None, d); out } diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 8e325c69be..0c835c7b5d 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -290,7 +290,7 @@ pub fn specs() -> Vec { "Add Mesh Line", [], None, - "{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}", + "{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y), inside or on the edge, to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge; at a point that is already a mesh point it adds no line, and records no undo step unless `color` changes a gradient mesh's point (a mesh envelope's points have no color) → {index}", has_doc, mesh_add_line ), diff --git a/crates/engine/src/cmd/live/mesh.rs b/crates/engine/src/cmd/live/mesh.rs index 187d2149f2..2290b56af4 100644 --- a/crates/engine/src/cmd/live/mesh.rs +++ b/crates/engine/src/cmd/live/mesh.rs @@ -122,9 +122,14 @@ fn with_mesh(s: &mut Session, p: &Value, cmd: &str, label: &str, envelopes: b /// Run `f` on the gradient mesh `id` of `d`; with `envelopes`, a mesh envelope's grid too (its /// points and handles are written back: editing fills in the handles). fn edit_grid(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result) -> Result { - match d.node_mut(id).map(|n| &mut n.kind) { - Some(NodeKind::Mesh(m)) => f(m), - Some(NodeKind::Envelope { kind, .. }) if envelopes && matches!(**kind, EnvelopeKind::Mesh { .. }) => { + edit_kind(&mut d.node_mut(id).ok_or(EngineError::NoNode(id))?.kind, cmd, envelopes, f) +} + +/// [`edit_grid`] on a node's kind. +fn edit_kind(k: &mut NodeKind, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result) -> Result { + match k { + NodeKind::Mesh(m) => f(m), + NodeKind::Envelope { kind, .. } if envelopes && matches!(**kind, EnvelopeKind::Mesh { .. }) => { let EnvelopeKind::Mesh { rows, cols, points, handles } = &mut **kind else { return Err(bad(cmd, "not a gradient mesh or mesh envelope")); }; @@ -135,8 +140,7 @@ fn edit_grid(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: imp *handles = m.points.iter().map(|q| q.handles).collect(); Ok(r) } - Some(_) => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })), - None => Err(EngineError::NoNode(id)), + _ => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })), } } @@ -281,12 +285,41 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["tolerance"], C)?; let tol = f64_or(p, "tolerance", 0.0).max(0.0); let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c)); - let index = with_mesh(s, p, C, "Add Mesh Line", true, |m| { + let add = move |m: &mut GradientMesh| { let i = m.add_lines_at(q, tol).ok_or_else(|| bad(C, "point is outside the mesh"))?; if let Some(c) = color { m.points[i].color = c; } Ok(i) + }; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; + if s.script_running() { + return Err(EngineError::Busy); + } + // The lines are added to a copy of the object. A point that is already a mesh point adds none: + // when its color stays too, nothing changes and no undo step is recorded. The grid is compared, + // not the node: a mesh envelope stored without handles takes them in any edit, and keeps no + // colors, so only its points and handles count. + let orig = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind.clone(); + let colored = matches!(orig, NodeKind::Mesh(_)); + let mut kind = orig.clone(); + let (i, same) = edit_kind(&mut kind, C, true, |m| { + let before = m.clone(); + let i = add(m)?; + let shape = |g: &GradientMesh| (g.rows, g.cols, g.points.iter().map(|q| (q.p, q.handles)).collect::>()); + Ok((i, if colored { *m == before } else { shape(m) == shape(&before) })) + })?; + if same { + return Ok(json!({ "index": i })); + } + let index = s.edit("Add Mesh Line", move |d, _| { + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + // Settling typed values before the edit may have changed the object: add the lines again. + if n.kind != orig { + return edit_kind(&mut n.kind, C, true, add); + } + n.kind = kind; + Ok(i) })?; Ok(json!({ "index": index })) } diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 1dd1548363..1ab0e0b670 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -115,7 +115,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -729,7 +729,9 @@ fn cmyk_raster( /// The image Object › Rasterize makes of some art, before it goes in a document /// ([`rasterize_art`]). pub(crate) struct Rasterized { - /// A PNG, or a CMYK image of the art's inks ([`cmyk_raster`]). + /// A PNG (greyscale for the Grayscale colour model), a 1-bit TIFF or greyscale PNG for Bitmap + /// ([`vectorcraft_render::Rendered::to_bilevel`]), or a CMYK image of the art's inks + /// ([`cmyk_raster`]). blob: vectorcraft_doc::ImageBlob, /// A CMYK image's transparency, a greyscale PNG: it becomes the image's opacity mask. alpha: Option>, @@ -769,7 +771,8 @@ impl Rasterized { /// Object › Rasterize's image of `nodes` (drawn also where hidden) with the params `p` of command /// `cmd`, each defaulting to `doc`'s raster effects settings: over the bounds of what the art draws /// ([`vectorcraft_render::drawn_bounds`]) and the room around them, in whole pixels. With `inks`, -/// a CMYK document's colour model makes a CMYK image ([`cmyk_raster`]); otherwise images are PNGs. +/// a CMYK document's colour model makes a CMYK image ([`cmyk_raster`]); otherwise images are PNGs, +/// greyscale for the Grayscale and Bitmap colour models (an opaque Bitmap image is a 1-bit TIFF). pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p: &Value, cmd: &str, inks: bool) -> Result { check_numbers(p, &["ppi"], cmd)?; let ppi = f64_or(p, "ppi", doc.raster_effects_ppi); @@ -836,10 +839,17 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p let tmp = isolated_doc(doc, nodes); let opts = raster.render_options(RasterFormat::Png); let (img, warning) = render_pixels(&tmp, region, scale, &opts, look.color_model)?; - let (blob, alpha) = if inks && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk && look.color_model == RasterColorModel::Document { - cmyk_raster(&tmp, region, scale, &opts, &img)? - } else { - (vectorcraft_doc::ImageBlob::new("image/png", img.to_png().map_err(EngineError::Other)?), None) + let png = + |bytes: std::result::Result, String>| bytes.map(|b| vectorcraft_doc::ImageBlob::new("image/png", b)).map_err(EngineError::Other); + let (blob, alpha) = match look.color_model { + RasterColorModel::Document if inks && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk => cmyk_raster(&tmp, region, scale, &opts, &img)?, + RasterColorModel::Document => (png(img.to_png())?, None), + // Grayscale images, as the colour models say (#6969). + RasterColorModel::Grayscale => (png(img.to_gray_png())?, None), + RasterColorModel::Bitmap => { + let (mime, bytes) = img.to_bilevel(ppi).map_err(EngineError::Other)?; + (vectorcraft_doc::ImageBlob::new(mime, bytes), None) + } }; let xf = Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale); Ok(Rasterized { blob, alpha, width: img.width, height: img.height, xf, clip, warning }) @@ -1043,6 +1053,11 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { bare.blend = Default::default(); bare.appearance = Appearance::default().into(); bare.visible = true; + // The image's own pixels are cut, not the masked ones a color mask shows: the mask is made + // again for the cut pixels after the edit. + if let Some(e) = bare.extras_if_any() { + e.color_mask = None; + } let tmp = isolated_doc(&st.doc, vec![bare]); let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale); let (png, w, h, warning) = diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index f4aaa841ca..c7c82c7625 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -798,9 +798,9 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { None => (None, None), }; let applied = profile.is_some(); - let mut d = match profile { - Some(p) => settings.document_from_profile(p), - None => settings.document(), + let (mut d, links_from, warnings) = match profile { + Some(p) => (settings.document_from_profile(p.doc), Some(p.file), p.warnings), + None => (settings.document(), None, vec![]), }; d.grid = s.prefs.grid(); d.title = match str_param(p, "name").or(str_param(p, "title")).map(str::trim).filter(|t| !t.is_empty()) { @@ -811,6 +811,9 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { }; d.metadata.created = clock_date(s, "created", date_param(p, "created", C)?); let i = s.add_document(d, None); + // The profile's links keep their relative paths, which name places from the profile's file, as + // a new document from a history state keeps its source's. + s.doc_mut()?.links_from = links_from; // Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both // are views of the whole app, so Default leaves them as they are. if settings.preview_mode == PreviewMode::Overprint { @@ -821,6 +824,9 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { if applied { out["profile"] = json!(settings.profile); } + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } if let Some(e) = profile_error { out["profileError"] = json!({ "profile": settings.profile, "reason": e }); } @@ -883,6 +889,19 @@ fn delete(s: &mut Session, p: &Value) -> Result { /// larger one is reported and the document starts with the defaults. pub const MAX_PROFILE_BYTES: u64 = 64 << 20; +/// `file.new`'s reason for a profile when the request being served may not read the profiles +/// folder: the folder's path is left out. +const PROFILE_DENIED: &str = "the request may not read the New Document profiles folder"; + +/// A profile's file as [`Session::read_profile`] read it. +struct ReadProfile { + doc: Document, + /// The file's path, which its links' relative paths name places from. + file: String, + /// A warning for each color profile the file carries that can't be used. + warnings: Vec, +} + /// The New Document profiles' names: the built-in categories, in tab order. pub fn profile_names() -> impl Iterator { CATEGORIES.iter().map(|c| c.0) @@ -919,24 +938,29 @@ impl Session { self.profile_path(name).is_some_and(|p| p.is_file()) } - /// Profile `name`'s document: `None` when it has no file (the shipped profile, the defaults), + /// 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. - fn read_profile(&self, name: &str) -> std::result::Result, String> { + 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(); // Checked before the file is looked for, so a request that may not read the folder learns - // nothing of its files. - crate::file_access::check_read(&path.to_string_lossy())?; + // nothing of its files, nor where the folder is. + 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(&path.to_string_lossy())?; + crate::file_access::check_read(&file).map_err(denied)?; let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?; - let mut doc = vectorcraft_format::load(&bytes).map_err(|e| e.to_string())?; + // 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())?; // Linked images in its symbols, patterns and brushes are read from their files, as placing // a document reads them. - super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&path.to_string_lossy())), false, false); - Ok(Some(doc)) + super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false); + Ok(Some(ReadProfile { doc, file, warnings })) } } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 1aeba3ad30..df388b81ab 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -701,7 +701,9 @@ fn colorized_images(d: &Document, ids: &[NodeId], paint: &Paint) -> std::result: out.push(*id); continue; } - let Some(gray) = d.image_blob(im).and_then(|b| b.gray_source()) else { continue }; + // A color-masked image is colorized as it shows: its masked pixels, which have an alpha + // channel. + let Some(gray) = d.image_blob(&d.shown_image(n, im)).and_then(|b| b.gray_source()) else { continue }; match paint { // Without a color, `none` goes to the image's fill item. Paint::None => continue, @@ -758,11 +760,17 @@ pub(super) fn check_colorized_kept(was_ok: bool, d: &Document) -> std::result::R if was_ok { check_colorized(d) } else { Ok(()) } } -/// How the pixels of `n` are gray, when `n` is a grayscale or 1-bit image colorized with a color -/// that [`colorizes_transparency`] refuses. Such an image can't have an alpha channel. +/// Is `n` an image colorized with a color that [`colorizes_transparency`] refuses? When its pixels +/// are grayscale or 1-bit, they can't have an alpha channel. +pub(super) fn colorized_with_process(d: &Document, n: &Node) -> bool { + matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.as_deref().is_some_and(|paint| !colorizes_transparency(d, paint)) +} + +/// How the pixels `n` shows are gray, when `n` is a grayscale or 1-bit image colorized with a +/// color that [`colorizes_transparency`] refuses ([`colorized_with_process`]). pub(super) fn gray_colorized_with_process(d: &Document, n: &Node) -> Option { - let (NodeKind::Image(im), Some(paint)) = (&n.kind, n.extras().colorize.as_deref()) else { return None }; - if colorizes_transparency(d, paint) { None } else { d.image_blob(im).and_then(|b| b.gray_source()) } + let NodeKind::Image(im) = &n.kind else { return None }; + if colorized_with_process(d, n) { d.image_blob(&d.shown_image(n, im)).and_then(|b| b.gray_source()) } else { None } } /// Is `e` the refusal of [`check_colorized`]? diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index fb0622632e..15a39f06e5 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -78,6 +78,12 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) { NodeKind::SymbolInstance { symbol, .. } => f(Ref::Symbol(symbol)), _ => {} } + // A color-masked image's masked pixels come along, and the key they were made from + // follows the image's. + if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) { + f(Ref::Image(&mut cm.key)); + f(Ref::Image(&mut cm.from)); + } }); } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 11c9c0dca7..c4b21b1cb4 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -34,7 +34,10 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.contour.set", "addon.cutting.bridges", "addon.cutting.weed", + "addon.image.applyColorMask", + "addon.image.colorMask", "addon.image.removeBackground", + "addon.image.removeColorMask", "addon.pathtools.addPoints", "addon.pathtools.close", "addon.pathtools.corner", @@ -480,6 +483,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.allOnArtboard", "select.anchors", "select.anchorsMany", + "select.byNote", "select.color", "select.font", "select.globalEdit", diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 34091017e3..931bcce681 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -59,7 +59,7 @@ pub fn specs() -> Vec { "Color Theme Picker", [], None, - "{picks: [{at: [x, y]} (a click: the object a Selection tool click there takes, with everything inside it) | {rect: [x0, y0, x1, y1]} (a marquee: every painted object it touches, and the part of each image inside it)] (1 to 256, in document points), colors?: 5 (1 to 64)} → {colors: [colour keys, the most used first], objects: the number of objects read} the colour palette of the art picked, for Recolor Artwork's Color Theme Picker: visible fills and strokes, gradient stops, text, mesh points, pattern tiles (with the patterns they use), the art of symbol instances (placed through their 9-slice guides), the colorize colour of an image it applies to and other images' pixels (at most 65,536 pixels of each pick of an image, spread evenly, and 1,048,576 pixels of at most 64 images in all; pixels less than half opaque and images that can't be decoded are left out). In a clip group, or under an opacity mask that clips, only what shows inside the clipping path or the mask art is read; a blend, envelope or repeat a marquee touches is read whole. Hidden or fully transparent objects and fill or stroke items are left out; locked objects are read. Each object read weighs the same, shared among its colours (an image's among its pixels; the vector art a symbol instance places counts as one object, each image it places on its own); similar colours merge (k-means in Lab) into at most `colors`, each shown by its most used colour in its own model. Picks that touch no art give no colours. Changes nothing", + "{picks: [{at: [x, y]} (a click: the object a Selection tool click there takes, with everything inside it) | {rect: [x0, y0, x1, y1]} (a marquee: every painted object it touches, and the part of each image inside it)] (1 to 256, in document points), colors?: 5 (1 to 64)} → {colors: [colour keys, the most used first], objects: the number of objects read} the colour palette of the art picked, for Recolor Artwork's Color Theme Picker: visible fills and strokes, gradient stops, text, mesh points, pattern tiles (with the patterns they use), the art of symbol instances (placed through their 9-slice guides), the colorize colour of an image it applies to and other images' pixels (at most 65,536 pixels of each pick of an image, spread evenly, and 1,048,576 pixels of at most 64 images in all; pixels less than half opaque and images that can't be decoded are left out). In a clip group, or under an opacity mask that clips, only what shows inside the clipping path or the mask art is read; a blend, envelope or repeat a marquee touches is read whole. The symbol instances read place at most 16,000,000 objects in all (an instance whose art would pass that is left out), and the pixels read inside clip groups are tested against at most 4,000,000 clipping-path elements in all (the picks of an image inside clip groups that would pass that are left out). Hidden or fully transparent objects and fill or stroke items are left out; locked objects are read. Each object read weighs the same, shared among its colours (an image's among its pixels; the vector art a symbol instance places counts as one object, each image it places on its own); similar colours merge (k-means in Lab) into at most `colors`, each shown by its most used colour in its own model. Picks that touch no art give no colours. Changes nothing", has_doc, pick_theme ), @@ -75,8 +75,8 @@ const MAX_THEME_IMAGES: usize = 64; const MAX_THEME_READS: usize = 4096; /// The stroke segments the opacity masks one pick reads are outlined along, at most. const MASK_OUTLINE_SEGMENTS: usize = 20_000; -/// The point-in-region tests one pick makes to find whether outlines show through clip groups, -/// and the clipping-path elements the pixels of one image are tested against, at most. +/// The point-in-region tests the picks make to find whether outlines show through clip groups, +/// and the clipping-path elements the pixels of their images are tested against, at most. const THEME_WORK: usize = 4_000_000; /// The picks one `recolor.pickTheme` takes, and the colours it gives, at most. const MAX_PICKS: usize = 256; @@ -126,6 +126,10 @@ struct ImageRead<'a> { colorize: Option>, } +/// A pattern's colours, the image reads of its tiles, and the depth its tiles were read at when +/// [`MAX_THEME_DEPTH`] cut them short. +type PatternRead<'a> = (Vec, Vec>, Option); + /// The colours the Color Theme Picker has read: each object weighs 1, shared among its colours. struct Theme<'a> { d: &'a Document, @@ -138,11 +142,17 @@ struct Theme<'a> { /// What the clip groups being read show, in document space: the union of these regions /// (none: nothing shows); `None` outside clip groups. clip: Option>, - /// The colours of the patterns read so far, and the patterns whose tiles are being read. - pattern_colors: HashMap, Vec>)>, + /// The colours of the patterns read so far (with the depth their tiles were read at when + /// [`MAX_THEME_DEPTH`] cut them short), and the patterns whose tiles are being read. + pattern_colors: HashMap>, pattern_stack: Vec, + /// Whether art was left out for passing [`MAX_THEME_DEPTH`]. + cut: bool, /// The region tests [`Self::shows`] has made. work: std::cell::Cell, + /// The objects the symbol instances read have placed, of [`vectorcraft_doc::MAX_SYMBOL_NODES`] + /// ([`vectorcraft_doc::charge_symbol_art`]). + symbol_nodes: u64, /// The object isolated in isolation mode. scope: Option, /// The stroke segments opacity masks may still be outlined along ([`mask_regions`]). @@ -170,8 +180,10 @@ impl<'a> Theme<'a> { blobs: std::collections::HashSet::new(), clip: None, pattern_colors: HashMap::new(), + cut: false, pattern_stack: vec![], work: std::cell::Cell::new(0), + symbol_nodes: 0, scope: None, mask_budget: MASK_OUTLINE_SEGMENTS, objects: 0, @@ -192,8 +204,10 @@ impl<'a> Theme<'a> { /// many there are, and the cells of all the reads add up, so the images give at most 16³ /// colours. Images that can't be decoded give none. The first [`MAX_THEME_IMAGES`] images /// are read, and all the reads share [`THEME_TOTAL_PIXELS`] pixels (each read at least one, at - /// most [`THEME_PIXELS`]). - fn read_images(&mut self) { + /// most [`THEME_PIXELS`]). The pixels read inside clip groups are tested against + /// [`THEME_WORK`] clipping-path elements in all; the reads of an image inside clip groups + /// that would pass it are left out. Gives the clipping-path elements tested. + fn read_images(&mut self) -> usize { let reads = std::mem::take(&mut self.images); // The reads of each image, in the order its first read came. let mut by_image: Vec<(*const vectorcraft_doc::ImageBlob, Vec<&ImageRead>)> = vec![]; @@ -208,15 +222,42 @@ impl<'a> Theme<'a> { let count: usize = by_image.iter().map(|(_, g)| g.len()).sum(); let budget = (THEME_TOTAL_PIXELS / count.max(1)).clamp(1, THEME_PIXELS); let mut pixels: HashMap<[u8; 3], ([f64; 3], f64)> = HashMap::new(); - for (_, group) in by_image { + // The clipping-path elements the pixels read have been tested against. + let tested = std::cell::Cell::new(0usize); + let elements = + |r: &ImageRead| r.clip.as_ref().map_or(0, |rs| rs.iter().map(|(bp, _)| bp.elements().len().max(1)).fold(0, usize::saturating_add)); + for (_, mut group) in by_image { + // Each pixel sampled for a read inside clip groups is tested against its clipping + // regions: the clipped reads of one image take at most `clipped` pixels each, so all + // of them keep within the work left, and the other reads take `budget`. When the work + // left can't test one pixel of each, the clipped reads are kept in order while their + // pixel fits, and the rest are left out. + let left = THEME_WORK.saturating_sub(tested.get()); + if group.iter().map(|r| elements(r)).fold(0, usize::saturating_add) > left { + let mut room = left; + group.retain(|r| { + let c = elements(r); + let fits = c <= room; + room = room.saturating_sub(if fits { c } else { 0 }); + fits + }); + } + let cost = group.iter().map(|r| elements(r)).fold(0, usize::saturating_add); + let clipped = left.checked_div(cost).map_or(budget, |w| budget.min(w)); + if group.is_empty() { + continue; + } let keeps: Vec bool + '_>> = group .iter() .map(|r| { - let (xf, (w, h), area, clip) = (r.xf, r.size, r.area, &r.clip); + let (xf, (w, h), area, clip, cost, tested) = (r.xf, r.size, r.area, &r.clip, elements(r), &tested); Box::new(move |u: f64, v: f64| { let p = xf * Point::new(u * w, v * h); area.is_none_or(|a| a.contains(p)) - && clip.as_ref().is_none_or(|rs| rs.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p))) + && clip.as_ref().is_none_or(|rs| { + tested.set(tested.get().saturating_add(cost)); + rs.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p)) + }) }) as Box bool + '_> }) .collect(); @@ -241,15 +282,10 @@ impl<'a> Theme<'a> { let high = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::NEG_INFINITY, f64::max); [low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h] }); - (box_uv, keep.as_ref()) + (box_uv, if r.clip.is_some() { clipped } else { budget }, keep.as_ref()) }) .collect(); - // Each sampled pixel inside a clip group is tested against the clipping regions: the - // pixels one image gives keep that work within THEME_WORK path elements. - let elements = - group.iter().map(|r| r.clip.as_ref().map_or(0, |rs| rs.iter().map(|(bp, _)| bp.elements().len()).sum::())).max().unwrap_or(0); - let budget = THEME_WORK.checked_div(elements).map_or(budget, |w| budget.min(w.max(1))); - let Some(each) = group[0].blob.sample_pixels(&picks, budget) else { continue }; + let Some(each) = group[0].blob.sample_pixels(&picks) else { continue }; for (px, read) in each.into_iter().zip(&group) { if let Some(colors) = &read.colorize { // Ink: an opaque pixel darker than white takes the colorize paint. @@ -289,6 +325,7 @@ impl<'a> Theme<'a> { let [r, g, b] = sum.map(|s| (s / w).round().clamp(0.0, 255.0) as u8); self.samples.push((Color::rgb8(r, g, b), w as f32)); } + tested.get() } /// Read `n` and everything visible inside it: each image (its part inside `area` when given, @@ -316,8 +353,12 @@ impl<'a> Theme<'a> { /// [`Self::read`] without `n`'s opacity mask. fn read_unmasked(&mut self, n: &Node, area: Option, depth: usize) { + if depth > MAX_THEME_DEPTH { + self.cut = true; + return; + } // Hidden and fully transparent objects show nothing. - if depth > MAX_THEME_DEPTH || !n.visible || n.opacity <= 0.0 || matches!(n.kind, NodeKind::Path { guide: true, .. }) { + if !n.visible || n.opacity <= 0.0 || matches!(n.kind, NodeKind::Path { guide: true, .. }) { return; } let touches = area.is_none_or(|r| self.touches(n, r)); @@ -332,13 +373,13 @@ impl<'a> Theme<'a> { // other paints its appearance has (with effects that draw them) count as well. let colorized = n.extras().colorize.is_some() && blob.takes_colorize(); let own = if colorized || n.extras().colorize.is_none() { - self.own(n, true) + self.own(n, true, depth) } else { // A colorize paint the image does not take (a linked image's preview) // shows nothing. let mut plain = n.clone(); plain.extras_mut().colorize = None; - self.own(&plain, true) + self.own(&plain, true, depth) }; let colorize = if colorized { Some(own) @@ -357,31 +398,43 @@ impl<'a> Theme<'a> { && self.shows(n, area) && let Some(s) = self.d.symbols.iter().find(|s| s.name == *symbol) { - // The instance's own paints; its overrides show in its art. - let own = self.own(n, false); - self.add(own); // The art as the instance places it: through the symbol's 9-slice guides when - // it has them, else by the instance's transform. Art that would place too many - // objects is left out, as the renderer leaves it out. + // it has them, else by the instance's transform. All the instances read share + // one limit on the objects they place, counted as the renderer counts them: an + // instance whose art would pass it shows nothing and is left out. let dynamic = (!n.extras().symbol_overrides.is_empty()).then(|| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n)); - if let Some(placed) = self.d.place_symbol_art(symbol, dynamic.as_ref().unwrap_or(&s.art), *xf) { - // The vector art counts as one object, each of its colours once, so an - // object the 9-slice guides cut into several copies does not count more. - // Each image placed is read on its own, as images are elsewhere. - let (samples, objects) = (self.samples.len(), self.objects); - self.read(&placed, None, depth + 1); - let added = self.samples.split_off(samples); - self.objects = objects; - let mut seen = std::collections::HashSet::new(); - let colors: Vec = added.into_iter().map(|(c, _)| c).filter(|c| seen.insert(ColorKey::of(c))).collect(); - self.add(colors); - } + let (d, art) = (self.d, dynamic.as_ref().unwrap_or(&s.art)); + let placed = match d.symbol_slice_map(symbol, *xf) { + Some(m) => vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, m.most_placed(art, d), || { + let placed = d.place_symbol_art(symbol, art, *xf); + let n = placed.as_ref().map_or(0, |a| a.count_with_masks() as u64); + (placed, n) + }), + None => { + let count = art.count() as u64; + vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, count, || (d.place_symbol_art(symbol, art, *xf), count)) + } + }; + let Some(Some(placed)) = placed else { return }; + // The instance's own paints; its overrides show in its art. + let own = self.own(n, false, depth); + self.add(own); + // The vector art counts as one object, each of its colours once, so an + // object the 9-slice guides cut into several copies does not count more. + // Each image placed is read on its own, as images are elsewhere. + let (samples, objects) = (self.samples.len(), self.objects); + self.read(&placed, None, depth + 1); + let added = self.samples.split_off(samples); + self.objects = objects; + let mut seen = std::collections::HashSet::new(); + let colors: Vec = added.into_iter().map(|(c, _)| c).filter(|c| seen.insert(ColorKey::of(c))).collect(); + self.add(colors); } return; } NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) => { if touches && self.shows(n, area) { - let own = self.own(n, true); + let own = self.own(n, true, depth); self.add(own); // The copies are drawn elsewhere than the objects lie: the clipping paths // around the live object, tested above, do not apply to the objects. @@ -396,7 +449,7 @@ impl<'a> Theme<'a> { _ => {} } if touches && self.shows(n, area) { - let own = self.own(n, true); + let own = self.own(n, true, depth); self.add(own); } // A compound path's members are its geometry: the compound paints them. @@ -767,13 +820,16 @@ impl<'a> Theme<'a> { /// document art is read (clip groups and symbols included; the tiles' images join this pick's /// image reads). Each pattern's colours /// are read once; a pattern whose tile uses itself, directly or through other patterns, adds - /// nothing more the second time. - fn own(&mut self, m: &Node, overrides: bool) -> Vec { + /// nothing more the second time. `depth` is `m`'s ([`Self::read`]): the tiles' art is read one + /// deeper, and a pattern whose tiles [`MAX_THEME_DEPTH`] cut short is read again when it is + /// used less deep. + fn own(&mut self, m: &Node, overrides: bool, depth: usize) -> Vec { let mut out = vec![]; let mut patterns: Vec = vec![]; paint_colors_of(m, overrides, &mut out, &mut patterns); for name in patterns { - if let Some((colors, reads)) = self.pattern_colors.get(&name) { + if let Some((colors, reads, cut)) = self.pattern_colors.get(&name).filter(|e| e.2.is_none_or(|at| depth >= at)) { + self.cut |= cut.is_some(); out.extend(colors); // The tiles' images count again for each use, within the pick's limits. let reads = reads.clone(); @@ -795,10 +851,11 @@ impl<'a> Theme<'a> { sub.blobs = std::mem::take(&mut self.blobs); // The tiles share this pick's limits on work too. sub.work.set(self.work.get()); + sub.symbol_nodes = self.symbol_nodes; sub.mask_budget = self.mask_budget; let before = sub.images.len(); for a in &def.art { - sub.read(a, None, 0); + sub.read(a, None, depth + 1); } sub.pattern_stack.pop(); self.pattern_stack = std::mem::take(&mut sub.pattern_stack); @@ -807,10 +864,12 @@ impl<'a> Theme<'a> { self.images = std::mem::take(&mut sub.images); self.blobs = std::mem::take(&mut sub.blobs); self.work.set(sub.work.get()); + self.symbol_nodes = sub.symbol_nodes; self.mask_budget = sub.mask_budget; + self.cut |= sub.cut; let colors: Vec = sub.samples.iter().map(|(c, _)| *c).collect(); out.extend(&colors); - self.pattern_colors.insert(name, (colors, reads)); + self.pattern_colors.insert(name, (colors, reads, sub.cut.then_some(depth))); } out } @@ -1529,3 +1588,243 @@ fn randomize(_: &mut Session, p: &Value) -> Result { .collect(); Ok(json!({ "map": map })) } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use vectorcraft_doc::{Appearance, ImageBlob, MAX_SYMBOL_NODES, PatternDef, Symbol}; + use vectorcraft_geom::{Affine, BezPath, FillRule, shapes}; + + use super::*; + + const RED: Color = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }; + const BLUE: Color = Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }; + + /// A 10 pt square from (`x`, 0) painted `fill`. + fn square(d: &mut Document, x: f64, fill: Paint) -> Arc { + let p = shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)); + Arc::new(Node::path(d.alloc_id(), p, Appearance::basic(fill, Paint::None, 0.0))) + } + + /// Symbol `name` whose art is a group of `art`, and an instance of it. + fn symbol(d: &mut Document, name: &str, art: Vec>) -> Arc { + let group = Node::group(d.alloc_id(), art); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(group) }); + Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })) + } + + fn has(t: &Theme, c: Color) -> bool { + t.samples.iter().any(|(s, _)| ColorKey::of(s) == ColorKey::of(&c)) + } + + /// The symbol instances read share one limit on the objects they place: with room for one + /// instance's art (a group and a square, 2 objects), the first instance is read and the + /// second, of another symbol, is left out. + #[test] + fn symbol_instances_share_one_limit_on_placed_objects() { + let mut d = Document::new(100.0, 100.0); + let red = square(&mut d, 0.0, Paint::solid(RED)); + let a = symbol(&mut d, "Red", vec![red]); + let blue = square(&mut d, 20.0, Paint::solid(BLUE)); + let b = symbol(&mut d, "Blue", vec![blue]); + let mut t = Theme::new(&d); + t.symbol_nodes = MAX_SYMBOL_NODES - 3; + t.read(&a, None, 0); + t.read(&b, None, 0); + assert!(has(&t, RED), "the first instance fits"); + assert!(!has(&t, BLUE), "the second does not"); + assert_eq!(t.symbol_nodes, MAX_SYMBOL_NODES - 1); + } + + /// An instance left out at the limit shows nothing, so its own paints are left out too. + #[test] + fn an_instance_past_the_limit_gives_none_of_its_own_paints() { + let mut d = Document::new(100.0, 100.0); + let red = square(&mut d, 0.0, Paint::solid(RED)); + let mut inst = (*symbol(&mut d, "Red", vec![red])).clone(); + inst.appearance = Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0).into(); + let mut t = Theme::new(&d); + t.read(&inst, None, 0); + assert!(has(&t, BLUE), "the instance's own fill, with room for its art"); + let mut t = Theme::new(&d); + t.symbol_nodes = MAX_SYMBOL_NODES - 1; + t.read(&inst, None, 0); + assert!(t.samples.is_empty() && t.objects == 0, "nothing past the limit: {:?}", t.samples); + } + + /// An instance without 9-slice guides is counted as the renderer counts it, without the art of + /// its opacity masks: a square with a mask of 6 objects places 2. + #[test] + fn an_instance_is_counted_without_its_mask_art() { + let mut d = Document::new(100.0, 100.0); + let leaf = square(&mut d, 0.0, Paint::solid(BLUE)); + let mut mask = vectorcraft_doc::OpacityMask::new(Node::group(d.alloc_id(), vec![leaf; 5]), true); + mask.disabled = true; + let mut red = (*square(&mut d, 0.0, Paint::solid(RED))).clone(); + red.extras_mut().mask = Some(Box::new(mask)); + let inst = symbol(&mut d, "Masked", vec![Arc::new(red)]); + let mut t = Theme::new(&d); + t.symbol_nodes = MAX_SYMBOL_NODES - 3; + t.read(&inst, None, 0); + assert!(has(&t, RED)); + assert_eq!(t.symbol_nodes, MAX_SYMBOL_NODES - 1); + } + + /// Nested instances charge the limit at every level: a tree of four leaf instances (5 + /// objects) whose leaves place 2 objects each places 13 objects in all, and with 9 objects of + /// room it places the tree and two of its leaves. + #[test] + fn nested_symbol_instances_charge_every_level() { + let mut d = Document::new(100.0, 100.0); + let red = square(&mut d, 0.0, Paint::solid(RED)); + let leaf = symbol(&mut d, "Leaf", vec![red]); + let tree = symbol(&mut d, "Tree", vec![leaf; 4]); + let mut t = Theme::new(&d); + t.read(&tree, None, 0); + assert_eq!(t.symbol_nodes, 13); + let mut t = Theme::new(&d); + t.symbol_nodes = MAX_SYMBOL_NODES - 9; + t.read(&tree, None, 0); + assert_eq!(t.symbol_nodes, MAX_SYMBOL_NODES, "the tree and two leaves"); + assert!(has(&t, RED)); + } + + /// Patterns `P0` to `P{n}`: each tile a group holding a square filled with the next pattern, + /// the last a red square. Gives a square filled with `P0`. + fn pattern_chain(d: &mut Document, n: usize) -> Arc { + let fill = |i: usize| Paint::Pattern { pattern: format!("P{i}"), xf: Affine::IDENTITY }; + for i in 0..=n { + let inner = if i == n { square(d, 0.0, Paint::solid(RED)) } else { square(d, 0.0, fill(i + 1)) }; + let tile = Arc::new(Node::group(d.alloc_id(), vec![inner])); + d.patterns.push(PatternDef::new(&format!("P{i}"), vec![tile])); + } + square(d, 0.0, fill(0)) + } + + /// Pattern tiles are read one level deeper than the object their pattern fills, so a chain of + /// patterns shares one limit on depth with the art around it: the end of a chain of 50 is + /// read, the end of a chain of 200 (two levels for each tile) is not. + #[test] + fn pattern_tiles_share_one_depth_limit() { + let mut d = Document::new(100.0, 100.0); + let short = pattern_chain(&mut d, 50); + let mut t = Theme::new(&d); + t.read(&short, None, 0); + assert!(has(&t, RED), "a chain of 50"); + let mut d = Document::new(100.0, 100.0); + let long = pattern_chain(&mut d, 200); + let p100 = square(&mut d, 0.0, Paint::Pattern { pattern: "P100".into(), xf: Affine::IDENTITY }); + let mut t = Theme::new(&d); + t.read(&long, None, 0); + assert!(!has(&t, RED), "a chain of 200 passes {MAX_THEME_DEPTH} levels"); + // The patterns cut short there are read again when used less deep: from P100 the end is + // 100 patterns away. + t.read(&p100, None, 0); + assert!(has(&t, RED), "P100 read again at the top"); + } + + /// A pattern tile's symbol instances charge the same limit as the art around it. + #[test] + fn pattern_tiles_charge_the_symbol_limit() { + let mut d = Document::new(100.0, 100.0); + let red = square(&mut d, 0.0, Paint::solid(RED)); + let inst = symbol(&mut d, "Red", vec![red]); + d.patterns.push(PatternDef::new("Dots", vec![inst])); + let art = square(&mut d, 0.0, Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }); + let mut t = Theme::new(&d); + t.read(&art, None, 0); + assert!(has(&t, RED)); + assert_eq!(t.symbol_nodes, 2, "the tile's instance placed a group and a square"); + let mut t = Theme::new(&d); + t.symbol_nodes = MAX_SYMBOL_NODES - 1; + t.read(&art, None, 0); + assert!(!has(&t, RED), "no room for the tile's instance"); + } + + /// A `size` px image of one color `rgba`. + fn blob(rgba: [u8; 4], size: u32) -> ImageBlob { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(size, size, image::Rgba(rgba)).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + ImageBlob::png(png) + } + + /// A read of all of `blob`, placed at the origin 1 pt a pixel, inside a clipping path over + /// it of `elements` path elements. + fn clipped(blob: &ImageBlob, size: f64, elements: usize) -> ImageRead<'_> { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + let steps = elements.saturating_sub(4).max(1); + for i in 1..=steps { + bp.line_to((size * i as f64 / steps as f64, 0.0)); + } + bp.line_to((size, size)); + bp.line_to((0.0, size)); + bp.close_path(); + ImageRead { blob, xf: Affine::IDENTITY, size: (size, size), area: None, clip: Some(vec![(bp, FillRule::NonZero)]), colorize: None } + } + + /// The reads of one image inside clip groups share the work limit: three reads of a 64 px + /// image, each inside a clipping path of 3,000 elements, test at most [`THEME_WORK`] elements + /// in all and still read the image. + #[test] + fn reads_of_one_image_share_the_clip_work_limit() { + let d = Document::new(100.0, 100.0); + let red = blob([255, 0, 0, 255], 64); + let mut t = Theme::new(&d); + t.images = (0..3).map(|_| clipped(&red, 64.0, 3000)).collect(); + let tested = t.read_images(); + assert!(tested > 0 && tested <= THEME_WORK, "{tested} elements tested"); + assert!(has(&t, RED)); + } + + /// A read of an image outside clip groups keeps its own pixel budget when another read of the + /// same image inside a clip group gets only two pixels: the blue 8 px block in the corner of a + /// red 64 px image is still read. + #[test] + fn unclipped_reads_keep_their_budget_beside_clipped_reads() { + let d = Document::new(100.0, 100.0); + let red = blob([255, 0, 0, 255], 64); + let mut png = Vec::new(); + image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba(if x >= 56 && y >= 56 { [0, 0, 255, 255] } else { [255, 0, 0, 255] })) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let corner = ImageBlob::png(png); + let mut t = Theme::new(&d); + let whole = ImageRead { clip: None, ..clipped(&corner, 64.0, 4) }; + // The red read leaves 6,400 elements of work; 3,200 elements a pixel leave two pixels. + t.images = vec![clipped(&red, 64.0, 3900), whole, clipped(&corner, 64.0, 3200)]; + let tested = t.read_images(); + assert!(tested <= THEME_WORK, "{tested} elements tested"); + assert!(has(&t, BLUE), "the read outside clip groups samples the whole image"); + } + + /// When the work left can't test a pixel of every clipped read of an image, the reads that fit + /// are still read: with 6,400 elements left, a read of a blue image inside a clipping path + /// of 5,000 elements is read beside one of 2,000 elements, which is left out. + #[test] + fn clipped_reads_that_fit_the_work_left_are_read() { + let d = Document::new(100.0, 100.0); + let (red, blue) = (blob([255, 0, 0, 255], 64), blob([0, 0, 255, 255], 64)); + let mut t = Theme::new(&d); + t.images = vec![clipped(&red, 64.0, 3900), clipped(&blue, 64.0, 5000), clipped(&blue, 64.0, 2000)]; + let tested = t.read_images(); + assert!(tested <= THEME_WORK, "{tested} elements tested"); + assert!(has(&t, BLUE), "the read that fits is read"); + } + + /// Past the work limit, the reads of an image inside clip groups are left out: a red image + /// inside a clipping path of 3,900 elements takes nearly all of it, and a blue image after it, + /// inside one of 100,000 elements, is not read. + #[test] + fn clipped_image_reads_past_the_work_limit_are_left_out() { + let d = Document::new(100.0, 100.0); + let (red, blue) = (blob([255, 0, 0, 255], 64), blob([0, 0, 255, 255], 64)); + let mut t = Theme::new(&d); + t.images = vec![clipped(&red, 64.0, 3900), clipped(&blue, 64.0, 100_000)]; + let tested = t.read_images(); + assert!(tested <= THEME_WORK, "{tested} elements tested"); + assert!(has(&t, RED)); + assert!(!has(&t, BLUE), "the blue image is past the limit"); + } +} diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index a2c7b3a8d4..ea307c7575 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -11,6 +11,7 @@ use super::object::can_align; use super::wand::{fill_of, stroke_of}; use super::{ CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index, ok, str_param, + switch_or, text_param, }; use crate::DocState; @@ -103,6 +104,15 @@ pub fn specs() -> Vec { has_doc, select_color ), + cmd!( + "select.byNote", + "Select by Note", + [], + None, + "{note, caseSensitive?: bool, wholeWord?: bool} select the objects whose Attributes note (attributes.set) holds `note`, without its leading and trailing spaces (1 to 1,024 bytes): anywhere in the note and in any letter case by default; caseSensitive (default false) asks for the same letter case, and wholeWord (default false) for no letter, digit or _ right before or after it. It looks at the objects Select All takes and the objects inside them, leaving out hidden and locked objects and art on a locked artboard; an object whose note matches is selected without the objects inside it. The objects found replace the selection, in paint order. No object found is an error that leaves the selection as it was. Not an undo step; Select > Reselect repeats it. The Actions panel's Select Object step (ui.action.insertSelectObject) runs this → {count, ids} (resulting selection)", + has_doc, + by_note + ), cmd!( "select.same.fillColor", "Fill Color", @@ -730,6 +740,124 @@ fn select_color(s: &mut Session, p: &Value) -> Result { select_where(s, C, p, |d, n| paint_reported(d, n) && reads_as(fill_of(n), fill.as_deref()) && reads_as(stroke_of(n).0, stroke.as_deref())) } +/// The longest note, in bytes, that Select by Note searches for. +const MAX_NOTE_QUERY: usize = 1024; + +/// Select by Note: the objects whose Attributes note holds `note` ([`note_matches`]). An object +/// whose note matches is selected without the objects inside it. With none found, the selection +/// stays as it was. +fn by_note(s: &mut Session, p: &Value) -> Result { + const C: &str = "select.byNote"; + let query = text_param(p, "note", C)?.map(str::trim).unwrap_or_default(); + if query.is_empty() { + return Err(bad(C, "the note is empty")); + } + if query.len() > MAX_NOTE_QUERY { + return Err(bad(C, "the note is longer than 1,024 bytes")); + } + let case_sensitive = switch_or(p, "caseSensitive", false, C)?; + let whole_word = switch_or(p, "wholeWord", false, C)?; + let not_found = || bad(C, format!("no object that can be selected has a note matching “{query}”")); + let st = s.doc()?; + let locks = st.doc.locked_artboards(); + let mut ids = vec![]; + walk_selectable(&st.doc, st.isolation, |n| { + let note = n.extras().attrs.as_deref().map_or("", |a| a.note.as_str()); + if note_matches(note, query, case_sensitive, whole_word) && is_selectable(&st.doc, st.isolation, &locks, n.id) { + ids.push(n.id); + return false; + } + true + }); + // The selection leaves out guides under Lock Guides and hidden slices, whatever selects them. + let mut found = st.selection.clone(); + found.set(ids.iter().copied()); + crate::deselect_hidden(&s.menu, &st.doc, &mut found); + if found.objects.is_empty() { + return Err(not_found()); + } + let before = st.selection.objects.clone(); + s.select(|_, sel| sel.set(ids.iter().copied()))?; + let st = s.doc_mut()?; + st.last_selection_cmd = Some((C.to_string(), p.clone(), before)); + selection_result(s) +} + +/// Whether `note` holds `query`: anywhere, and in any letter case unless `case_sensitive`. With +/// `whole_word`, the match starts and ends on whole characters of `note`, and the characters of +/// `note` right before and right after it are not a letter, a digit or `_`. +/// +/// Letter case is compared one character at a time ([`fold_case`]), so a final Σ still matches σ, +/// and each folded character keeps the byte offset of the character of `note` it comes from. +fn note_matches(note: &str, query: &str, case_sensitive: bool, whole_word: bool) -> bool { + if note.is_empty() || query.is_empty() { + return false; + } + let fold = |text: &str| -> Vec<(char, usize)> { + let mut out = Vec::with_capacity(text.len()); + for (at, c) in text.char_indices() { + if case_sensitive { + out.push((c, at)); + } else { + out.extend(fold_case(c).map(|f| (f, at))); + } + } + out + }; + let folded = fold(note); + let query: Vec = fold(query).into_iter().map(|(c, _)| c).collect(); + let word = |c: char| c.is_alphanumeric() || c == '_'; + // Whether the match of `query` that starts at `folded[i]` counts. + let accept = |i: usize| { + if !whole_word { + return true; + } + let (start, last) = (folded[i].1, folded[i + query.len() - 1].1); + let starts_whole = i == 0 || folded[i - 1].1 != start; + let ends_whole = folded.get(i + query.len()).is_none_or(|(_, at)| *at != last); + if !starts_whole || !ends_whole { + return false; + } + let end = last + note[last..].chars().next().map_or(0, char::len_utf8); + !note[..start].chars().next_back().is_some_and(word) && !note[end..].chars().next().is_some_and(word) + }; + // Knuth-Morris-Pratt, so a long note takes time in proportion to its length, and every place + // the query occurs is tried, also places that overlap. `fail[k]` is the length of the longest + // proper prefix of `query[..=k]` that is also its suffix. + let mut fail = vec![0; query.len()]; + let mut k = 0; + for i in 1..query.len() { + while k > 0 && query[i] != query[k] { + k = fail[k - 1]; + } + if query[i] == query[k] { + k += 1; + } + fail[i] = k; + } + let mut k = 0; + for (j, (c, _)) in folded.iter().enumerate() { + while k > 0 && *c != query[k] { + k = fail[k - 1]; + } + if *c == query[k] { + k += 1; + } + if k == query.len() { + if accept(j + 1 - k) { + return true; + } + k = fail[k - 1]; + } + } + false +} + +/// `c` in lowercase for a comparison that ignores letter case, with the final sigma ς read as σ. +fn fold_case(c: char) -> impl Iterator { + c.to_lowercase().map(|l| if l == 'ς' { 'σ' } else { l }) +} + /// Does `document.inspect` report a fill and stroke for `n`? A compound path's are its own, though /// it holds its members, and its members report none. fn paint_reported(d: &Document, n: &Node) -> bool { diff --git a/crates/engine/src/schemas.rs b/crates/engine/src/schemas.rs index fb08bb649c..08bc0f719d 100644 --- a/crates/engine/src/schemas.rs +++ b/crates/engine/src/schemas.rs @@ -69,7 +69,7 @@ fn param_error(id: &str, e: &ParamError) -> EngineError { Problem::Unknown { keys } => bad(id, format!("unknown parameter `{path}`; it takes: {keys}", keys = keys.join(", "))), Problem::Missing => bad(id, format!("missing `{path}`")), Problem::WrongType { expected, got } => bad(id, format!("`{path}` must be {expected}, not {got}")), - Problem::TooDeep => EngineError::Internal { cmd: id.into(), msg: e.to_string() }, + Problem::TooDeep => bad(id, format!("`{path}` is nested too deeply")), } } @@ -246,6 +246,30 @@ mod tests { assert!(s.doc().unwrap().history.undo.is_empty()); } + /// A value nested past the limit of a sound schema is a parameter error that names it, not an + /// internal error: a color list at the nesting limit, where a color string still passes. + #[test] + fn a_value_nested_too_deeply_is_a_parameter_error() { + let levels = vectorcraft_apischema::MAX_DEPTH; + let ty = (0..levels).fold(Type::Color, |inner, _| Type::Array(Box::leak(Box::new(inner)))); + let params: &'static [Param] = Box::leak(Box::new([Param::new("fills", ty)])); + let schema = ParamSchema::new(params, ""); + assert_eq!(schema.definition_problem(), None); + let wrapped = |v: Value| (0..levels).fold(v, |inner, _| Value::Array(vec![inner])); + assert!(schema.validate(&json!({"fills": wrapped(json!("#ff0000"))})).is_ok()); + let e = schema.validate(&json!({"fills": wrapped(json!([1, 0, 0]))})).unwrap_err(); + let path = format!("fills{}", "[0]".repeat(levels)); + match param_error("view.synthetic", &e) { + EngineError::BadParams { cmd, msg } => { + assert_eq!(cmd, "view.synthetic"); + assert_eq!(msg, format!("`{path}` is nested too deeply")); + } + other => panic!("not a parameter error: {other}"), + } + let shown = param_error("view.synthetic", &e).to_string(); + assert!(shown.starts_with("invalid parameters for `view.synthetic`") && !shown.contains("report this bug"), "{shown}"); + } + /// Each command's JSON schema follows the 2020-12 rules, and a validator of those rules, which /// shares no code with the writer, gives the same answer as the schema check. None of these /// schemas has a lenient parameter. diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 61a4cc8a01..a1468f4612 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -31,6 +31,8 @@ impl Session { } // Pixel-aligned objects the edit changed go back on the pixel grid. cmd::refresh_pixel_aligned(&before, doc); + // Color masks of images whose own pixels the edit replaced are made for the new ones. + cmd::refresh_color_masks(Some(&*before), doc); let placed = cmd::objects_on_path::refresh(&before, doc); // Pixel-aligned members that placing moved go back on the pixel grid. cmd::keep_aligned_in(doc, &placed); diff --git a/crates/engine/src/tests/attributes.rs b/crates/engine/src/tests/attributes.rs index 4dea459409..d3edf2615b 100644 --- a/crates/engine/src/tests/attributes.rs +++ b/crates/engine/src/tests/attributes.rs @@ -1,4 +1,5 @@ -//! Window → Attributes (`attributes.set`, `attributes.info`, `path.setFillRule`, `path.reverse`), +//! Window → Attributes (`attributes.set`, `attributes.info`, `path.setFillRule`, `path.reverse`, +//! and `select.byNote`, which selects objects by their note), //! the links SVG export writes for objects with a URL, and what objects keep for other software //! (their `data-*` attributes and their attributes in other applications' namespaces). @@ -216,6 +217,140 @@ fn object_data_is_set_saved_and_written_to_svg() { assert_eq!(back.node(a).unwrap().extras().attrs, s.doc().unwrap().doc.node(a).unwrap().extras().attrs); } +/// The selected objects after `select.byNote` with `p`, or its error. +fn by_note(s: &mut Session, p: Value) -> std::result::Result, String> { + s.execute("select.byNote", &p).map_err(|e| e.to_string())?; + Ok(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect()) +} + +fn note(s: &mut Session, id: NodeId, note: &str) { + run(s, "attributes.set", json!({"ids": [id.0], "note": note})); +} + +/// Select by Note finds a note anywhere and in any letter case by default, replaces the selection +/// with every object it finds, in paint order, and is not an undo step. Case Sensitive and Whole +/// Word narrow it; Reselect repeats it. +#[test] +fn select_by_note_matches_part_of_a_note_in_any_case_unless_asked() { + let mut s = session(); + let [a, b, c, d] = [0.0, 20.0, 40.0, 60.0].map(|x| rect(&mut s, x)); + note(&mut s, a, "Logo front"); + note(&mut s, b, "logo"); + note(&mut s, c, "Logotype"); + note(&mut s, d, "back"); + run(&mut s, "select.set", json!({"ids": [d.0]})); + let undo = s.doc().unwrap().history.undo.len(); + assert_eq!(by_note(&mut s, json!({"note": " LOGO "})), Ok(vec![a.0, b.0, c.0]), "outer spaces are left out"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + assert_eq!(by_note(&mut s, json!({"note": "logo", "caseSensitive": true})), Ok(vec![b.0])); + assert_eq!(by_note(&mut s, json!({"note": "logo", "wholeWord": true})), Ok(vec![a.0, b.0])); + assert_eq!(by_note(&mut s, json!({"note": "Logo", "caseSensitive": true, "wholeWord": true})), Ok(vec![a.0])); + assert_eq!(by_note(&mut s, json!({"note": "o f"})), Ok(vec![a.0]), "spaces inside the note count"); + run(&mut s, "select.none", json!({})); + run(&mut s, "select.reselect", json!({})); + assert_eq!(s.doc().unwrap().selection.objects, [a]); +} + +/// Whole Word looks at every place the text occurs, also places that overlap. +#[test] +fn select_by_note_whole_word_matches_overlapping_places_and_other_scripts() { + let mut s = session(); + let a = rect(&mut s, 0.0); + let matches = |s: &mut Session, text: &str, p: Value| { + note(s, a, text); + by_note(s, p).is_ok() + }; + assert!(matches(&mut s, "a aa a a", json!({"note": "a a", "wholeWord": true}))); + assert!(!matches(&mut s, "aa_a", json!({"note": "a", "wholeWord": true}))); + assert!(matches(&mut s, "x-ray, x", json!({"note": "x", "wholeWord": true}))); + assert!(matches(&mut s, "ÉTIQUETTE", json!({"note": "étiquette"}))); + assert!(!matches(&mut s, "ÉTIQUETTE", json!({"note": "étiquette", "caseSensitive": true}))); + assert!(matches(&mut s, "标签 一", json!({"note": "一", "wholeWord": true}))); + assert!(!matches(&mut s, "", json!({"note": "a"}))); +} + +/// Letter case is compared one character at a time: a final Σ, whose lowercase is ς, matches Σ +/// and σ. Whole Word looks at the characters of the note itself, so a letter whose lowercase +/// takes two characters (İ) neither ends a word early nor matches half of itself. +#[test] +fn select_by_note_compares_letter_case_per_character() { + let mut s = session(); + let a = rect(&mut s, 0.0); + let matches = |s: &mut Session, text: &str, p: Value| { + note(s, a, text); + by_note(s, p).is_ok() + }; + assert!(matches(&mut s, "ΟΣ", json!({"note": "Σ"}))); + assert!(matches(&mut s, "ΟΣ", json!({"note": "σ"}))); + assert!(matches(&mut s, "ΟΣ", json!({"note": "ος", "wholeWord": true}))); + assert!(!matches(&mut s, "ΟΣ", json!({"note": "σ", "caseSensitive": true}))); + assert!(!matches(&mut s, "İx", json!({"note": "i", "wholeWord": true}))); + assert!(matches(&mut s, "İ x", json!({"note": "İ", "wholeWord": true}))); + assert!(!matches(&mut s, "İ x", json!({"note": "i", "wholeWord": true}))); +} + +/// Select by Note leaves out hidden and locked objects, selects a group whose note matches without +/// its members and a member whose note matches on its own, keeps to the isolated group, and leaves +/// the selection as it was when it finds nothing. Bad params are errors that change nothing. +#[test] +fn select_by_note_takes_only_objects_that_can_be_selected() { + let mut s = session(); + let [a, b, c, d, e] = [0.0, 10.0, 20.0, 30.0, 40.0].map(|x| rect(&mut s, x)); + for id in [a, b, c, d, e] { + note(&mut s, id, "tag"); + } + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "object.hide", json!({})); + run(&mut s, "select.set", json!({"ids": [b.0]})); + run(&mut s, "object.lock", json!({})); + run(&mut s, "select.set", json!({"ids": [c.0, d.0]})); + let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + note(&mut s, g, "tag group"); + assert_eq!(by_note(&mut s, json!({"note": "tag"})), Ok(vec![g.0, e.0]), "the group, not its members"); + note(&mut s, g, "box"); + assert_eq!(by_note(&mut s, json!({"note": "tag"})), Ok(vec![c.0, d.0, e.0])); + run(&mut s, "object.isolate", json!({"id": g.0})); + assert_eq!(by_note(&mut s, json!({"note": "tag"})), Ok(vec![c.0, d.0]), "inside the isolated group only"); + run(&mut s, "select.set", json!({"ids": [c.0]})); + let missing = by_note(&mut s, json!({"note": "nothing"})).unwrap_err(); + assert!(missing.contains("no object that can be selected has a note matching “nothing”"), "{missing}"); + assert_eq!(s.doc().unwrap().selection.objects, [c], "the selection stays"); + for bad in [ + json!({}), + json!({"note": " "}), + json!({"note": 5}), + json!({"note": "x".repeat(1025)}), + json!({"note": "tag", "caseSensitive": "yes"}), + json!({"note": "tag", "wholeWord": 1}), + ] { + assert!(s.execute("select.byNote", &bad).is_err(), "{bad}"); + assert_eq!(s.doc().unwrap().selection.objects, [c], "{bad}"); + } + assert!(by_note(&mut s, json!({"note": "x".repeat(1024)})).is_err_and(|e| e.contains("no object")), "1,024 bytes is allowed"); +} + +/// Under Lock Guides a guide whose note matches is not a match, and a search that finds only such +/// guides leaves the selection and the Puppet Warp pins on it as they were. +#[test] +fn select_by_note_leaves_locked_guides_out_before_changing_the_selection() { + let mut s = session(); + let a = rect(&mut s, 10.0); + let g = rect(&mut s, 50.0); + note(&mut s, g, "edge"); + run(&mut s, "select.set", json!({"ids": [g.0]})); + run(&mut s, "view.guides.make", json!({})); + run(&mut s, "view.guides.lock", json!({"locked": true})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "object.puppetWarp", json!({"id": a.0, "rest": true, "pins": [[25, 25]], "moved": [[25, 25]]})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + assert!(s.doc().unwrap().doc.puppet.is_some(), "a pin on the rectangle"); + let missing = by_note(&mut s, json!({"note": "edge"})).unwrap_err(); + assert!(missing.contains("no object that can be selected"), "{missing}"); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, [a], "the selection stays"); + assert!(st.doc.puppet.is_some(), "the pins stay"); +} + /// An object's attributes in other applications' XML namespaces are its own, as its `data-*` /// attributes are: a pasted copy and a duplicate keep them, deleting the object takes them with /// it, and the native file and SVG export keep them. diff --git a/crates/engine/src/tests/envelope.rs b/crates/engine/src/tests/envelope.rs index 4ffd7a361a..9d8999e388 100644 --- a/crates/engine/src/tests/envelope.rs +++ b/crates/engine/src/tests/envelope.rs @@ -123,6 +123,29 @@ fn reset_with_warp_and_mesh_switch_the_kind_and_keep_the_content() { assert!(s.execute("object.envelope.resetWithMesh", &json!({})).is_err()); } +/// `object.mesh.addLine` at a point a mesh envelope already has (one stored without handles) adds +/// no line and records no undo step, with or without a `color`; a point between its lines adds +/// them as one step. +#[test] +fn mesh_envelope_add_line_at_a_mesh_point_records_no_undo_step() { + let mut s = session(); + let (_, e) = enveloped(&mut s, "object.envelope.makeWithMesh", json!({"rows": 2, "cols": 2})); + let before = kind(&s, e); + assert!(matches!(&before, EnvelopeKind::Mesh { handles, .. } if handles.is_empty()), "{before:?}"); + let undo_len = |s: &Session| s.doc().unwrap().history.undo.len(); + let n = undo_len(&s); + for (x, y) in [(100.0, 100.0), (300.0, 200.0), (200.0, 150.0), (300.0, 150.0)] { + s.execute("object.mesh.addLine", &json!({"id": e.0, "x": x, "y": y})).unwrap(); + assert_eq!((kind(&s, e), undo_len(&s)), (before.clone(), n), "({x}, {y}): nothing changed"); + } + // An envelope's points carry no color, so a color there changes nothing either. + s.execute("object.mesh.addLine", &json!({"id": e.0, "x": 200, "y": 150, "color": "#00ff00"})).unwrap(); + assert_eq!((kind(&s, e), undo_len(&s)), (before.clone(), n), "a color changes nothing"); + s.execute("object.mesh.addLine", &json!({"id": e.0, "x": 150, "y": 125})).unwrap(); + assert!(matches!(kind(&s, e), EnvelopeKind::Mesh { rows: 3, cols: 3, .. }), "{:?}", kind(&s, e)); + assert_eq!(undo_len(&s), n + 1); +} + /// A new warp envelope bends with its style's Bézier net (`version` [`live::WARP_NET`]) and keeps /// it through Reset with Warp. One saved before the version existed keeps the earlier map when its /// warp or its options change. diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 038b8844bb..3fd187016f 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -126,6 +126,302 @@ fn a_symbol_instance_fill_with_no_opacity_keeps_swatch_links_when_expanded() { assert!(linked > 0, "the expanded art keeps the Brand swatch link"); } +/// The square of [`square`] made a symbol, its instance selected, with a new fill (`fill`) or +/// stroke on top that has no paint: it neither stains nor strokes the art. Returns the instance and +/// the new row's index. +fn instance_with_row(s: &mut Session, name: &str, fill: bool) -> (NodeId, usize) { + square(s); + let id = NodeId(run(s, "symbol.new", json!({"name": name}))["id"].as_u64().unwrap()); + run(s, if fill { "appearance.addFill" } else { "appearance.addStroke" }, json!({"ids": [id.0]})); + let row = node(s, id).appearance.items.len() - 1; + run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + (id, row) +} + +fn offset_row(s: &mut Session, id: NodeId, row: usize, offset: f64) { + run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "path.offsetPath", "params": {"offset": offset}})); +} + +fn near(p: [u8; 4], q: [u8; 4]) -> bool { + p.iter().zip(q.iter()).all(|(x, y)| x.abs_diff(*y) <= 24) +} + +const WHITE: [u8; 4] = [255, 255, 255, 255]; +const RED: [u8; 4] = [255, 0, 0, 255]; +const BLUE: [u8; 4] = [0, 0, 255, 255]; + +/// No object in `n` keeps an effect of its own or on a fill or stroke. +fn no_effects_left(n: &Node) { + n.walk(&mut |part| { + assert!(part.appearance.effects.is_empty(), "{:?} keeps object effects", part.id); + assert!(part.appearance.items.iter().all(|i| i.effects().is_empty()), "{:?} keeps fill or stroke effects", part.id); + }); +} + +/// An effect on a symbol instance's fill reshapes the filled shapes of its art, keeping their +/// colors, and leaves their strokes where they were; Expand Appearance bakes the same look into +/// editable art in one undo step. +#[test] +fn a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + assert!(!expandable(&s)); + let plain = render(&s); + assert!(near(plain.pixel(44, 100), WHITE)); + offset_row(&mut s, id, row, 10.0); + assert!(expandable(&s), "the fill's effect can be expanded"); + let before = render(&s); + assert!(near(before.pixel(44, 100), RED), "the art's red fill grows by the offset: {:?}", before.pixel(44, 100)); + assert!(near(before.pixel(50, 100), BLUE), "the blue stroke stays on the square: {:?}", before.pixel(50, 100)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert!(!matches!(n.kind, NodeKind::SymbolInstance { .. })); + no_effects_left(&n); + let mut paints = (0, 0); + n.walk(&mut |part| { + if part.appearance.fill().is_some_and(|f| f.paint.color().is_some_and(|c| c.to_hex() == "#ff0000")) { + paints.0 += 1; + } + if part.appearance.stroke().is_some_and(|st| st.paint.color().is_some_and(|c| c.to_hex() == "#0000ff")) { + paints.1 += 1; + } + }); + assert!(paints.0 > 0 && paints.1 > 0, "the art keeps its red fill and blue stroke: {paints:?}"); + let after = render(&s); + assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); + + run(&mut s, "edit.undo", json!({})); + let n = node(&s, id); + assert!(matches!(n.kind, NodeKind::SymbolInstance { .. }), "one undo gives the instance back"); + assert!(n.appearance.items[row].effects().iter().any(|e| e.id == "path.offsetPath")); +} + +/// Export bakes a symbol instance's fill effect into its art as the canvas draws it. +#[test] +fn export_bakes_a_symbol_instance_fill_effect() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + offset_row(&mut s, id, row, 10.0); + let doc = s.doc().unwrap().doc.clone(); + let baked = vectorcraft_render::effects::bake_document(&doc).expect("the instance is baked"); + let n = baked.node(id).expect("the baked art keeps the instance's id").clone(); + assert!(!matches!(n.kind, NodeKind::SymbolInstance { .. })); + no_effects_left(&n); + let b = n.geometric_bounds().expect("the baked art has bounds"); + assert!((b.x0 - 40.0).abs() < 1.0 && (b.x1 - 160.0).abs() < 1.0, "the fill grows by the offset: {b:?}"); +} + +/// An effect on a symbol instance's stroke reshapes the stroked shapes of its art and leaves +/// their fills where they were. +#[test] +fn a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", false); + assert!(near(render(&s).pixel(40, 100), WHITE)); + offset_row(&mut s, id, row, 10.0); + assert!(expandable(&s)); + let before = render(&s); + assert!(near(before.pixel(40, 100), BLUE), "the stroke moves out with the offset: {:?}", before.pixel(40, 100)); + assert!(near(before.pixel(45, 100), WHITE), "the fill keeps its shape: {:?}", before.pixel(45, 100)); + assert!(near(before.pixel(100, 100), RED)); + + run(&mut s, "effect.expandAppearance", json!({"ids": [id.0]})); + let n = node(&s, id); + assert!(!matches!(n.kind, NodeKind::SymbolInstance { .. })); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); +} + +/// A dynamic symbol's instance that paints a stroke of its own on art without one: the instance's +/// stroke effect reshapes that stroke, and its bounds take in where the stroke is drawn. +#[test] +fn a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds() { + let mut s = session(); + square(&mut s); + run(&mut s, "paint.setStroke", json!({"none": true})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Art", "type": "dynamic"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + let blue = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)); + s.edit("paint", |d, _| { + let o = vectorcraft_doc::symbol_overrides::SymbolOverride { path: vec![], stroke: Some(blue), ..Default::default() }; + d.node_mut(id).ok_or(EngineError::NoNode(id))?.extras_mut().symbol_overrides.push(o); + Ok(()) + }) + .unwrap(); + // The 1 pt stroke's center moves to x = 30.5, so it covers the pixel column from 30 to 31. + offset_row(&mut s, id, row, 19.5); + assert!(near(render(&s).pixel(30, 100), BLUE), "the added stroke moves out with the offset: {:?}", render(&s).pixel(30, 100)); + let doc = s.doc().unwrap().doc.clone(); + let b = vectorcraft_render::painted_bounds(&doc, doc.node(id).unwrap()).expect("the instance has bounds"); + assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the offset stroke: {b:?}"); + let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn"); + assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the offset stroke: {drawn:?}"); +} + +/// A group in the symbol's art with a fill of its own: the instance's fill effect reshapes what +/// that fill paints, and the instance's bounds take it in. +#[test] +fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() { + let mut s = session(); + square(&mut s); + run(&mut s, "paint.setFill", json!({"none": true})); + run(&mut s, "paint.setStroke", json!({"none": true})); + let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [g.0]})); + run(&mut s, "paint.setFill", json!({"ids": [g.0], "item": 0, "color": "#ff0000"})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Group"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + offset_row(&mut s, id, row, 20.0); + assert!(near(render(&s).pixel(35, 100), RED), "the group's fill grows by the offset: {:?}", render(&s).pixel(35, 100)); + let doc = s.doc().unwrap().doc.clone(); + let b = vectorcraft_render::painted_bounds(&doc, doc.node(id).unwrap()).expect("the instance has bounds"); + assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the group's grown fill: {b:?}"); + let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn"); + assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the group's grown fill: {drawn:?}"); + + let before = render(&s); + run(&mut s, "effect.expandAppearance", json!({})); + no_effects_left(&node(&s, id)); + let after = render(&s); + assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); +} + +/// Of several fills, only the topmost one's effects reach the art, and only while it is visible. +#[test] +fn only_the_topmost_visible_instance_fill_reshapes_the_art() { + let mut s = session(); + let (id, lower) = instance_with_row(&mut s, "Square", true); + offset_row(&mut s, id, lower, 30.0); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let top = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": top, "none": true})); + assert!(!expandable(&s), "a lower fill's effect does not reach the art"); + offset_row(&mut s, id, top, 10.0); + let both = render(&s); + assert!(near(both.pixel(44, 100), RED), "the top fill's offset shows"); + assert!(near(both.pixel(25, 100), WHITE), "the lower fill's offset does not: {:?}", both.pixel(25, 100)); + + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": top, "visible": false})); + assert!(near(render(&s).pixel(44, 100), WHITE), "a hidden top fill reshapes nothing"); + assert!(!expandable(&s)); + + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": top, "visible": true})); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + assert!(differing(&both, &after, 8) < 200, "expanding changed {} pixels", differing(&both, &after, 8)); + let n = node(&s, id); + no_effects_left(&n); +} + +/// An instance inside a symbol's art passes the outer instance's fill effect on to its own art. +#[test] +fn a_nested_symbol_instance_takes_the_outer_fill_effect() { + let mut s = session(); + square(&mut s); + run(&mut s, "symbol.new", json!({"name": "Inner"})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + offset_row(&mut s, id, row, 40.0); + let before = render(&s); + assert!(near(before.pixel(20, 100), RED), "the inner art grows by the offset: {:?}", before.pixel(20, 100)); + assert!(expandable(&s)); + // A view that shows only the grown part, right of the square: the instance is still drawn. + let doc = s.doc().unwrap().doc.clone(); + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let right = vectorcraft_render::Renderer::new().render(&doc, 200, 200, vectorcraft_geom::Affine::translate((-155.0, 0.0)), &opts); + assert!(near(right.pixel(20, 100), RED), "the grown art past the square's box is drawn: {:?}", right.pixel(20, 100)); + let b = vectorcraft_render::painted_bounds(&doc, doc.node(id).unwrap()).expect("the instance has bounds"); + assert!(b.x0 <= 11.0 && b.x1 >= 189.0, "the bounds take in the inner art's offset: {b:?}"); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert!(!matches!(n.kind, NodeKind::SymbolInstance { .. })); + n.walk(&mut |part| assert!(!matches!(part.kind, NodeKind::SymbolInstance { .. }), "the inner instance is expanded too")); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); +} + +/// A symbol whose art holds an instance of itself draws, exports and expands without running away. +/// The engine keeps no such document after an edit, so Expand Appearance refuses it and the +/// instance stays as it was. +#[test] +fn a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + offset_row(&mut s, id, row, 4.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inst = d.node(id).unwrap().clone(); + let sym = d.symbols.iter_mut().find(|sy| sy.name == "Square").unwrap(); + sym.art = std::sync::Arc::new(Node::group(NodeId(90_000), vec![sym.art.clone(), std::sync::Arc::new(inst)])); + } + let doc = s.doc().unwrap().doc.clone(); + assert!(vectorcraft_render::effects::bake_document(&doc).is_some(), "export bakes the instance"); + assert!(vectorcraft_render::painted_bounds(&doc, doc.node(id).unwrap()).is_some(), "the instance is measured"); + render(&s); + assert!(expandable(&s)); + let e = s.execute("effect.expandAppearance", &json!({})).expect_err("the symbol nests without end"); + assert!(e.to_string().contains(crate::TOO_DEEP), "{e}"); + assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "the instance stays as it was"); +} + +/// A clip group's clipping path in the art keeps its shape, a compound one included, while the art +/// it clips takes the instance's fill effect. +#[test] +fn a_compound_clipping_path_in_the_art_keeps_its_shape() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + offset_row(&mut s, id, row, 10.0); + let red = || { + let mut ap = vectorcraft_doc::Appearance::default(); + ap.items.push(vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid( + vectorcraft_color::Color::rgb(1.0, 0.0, 0.0), + )))); + ap + }; + let square = |id: u64, x: f64| { + let rect = vectorcraft_geom::Rect::new(x, 50.0, x + 100.0, 150.0); + std::sync::Arc::new(Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(rect), red())) + }; + let mut clip = Node::new(NodeId(90_001), NodeKind::Compound { children: vec![square(90_002, 40.0)], rule: Default::default() }); + clip.appearance = red().into(); + let group = Node::new(NodeId(90_003), NodeKind::Group { children: vec![std::sync::Arc::new(clip), square(90_004, 50.0)], clip: true }); + let doc = { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let sym = d.symbols.iter_mut().find(|sy| sy.name == "Square").unwrap(); + sym.art = std::sync::Arc::new(group); + d.clone() + }; + let inst = doc.node(id).unwrap(); + let art = doc.symbols.iter().find(|sy| sy.name == "Square").unwrap().art.clone(); + let out = vectorcraft_render::effects::outline_art(Some(&doc), inst, Some(&art)).expect("the instance's art"); + let mut seen = (false, false); + out.walk(&mut |part| { + let offset = part.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.id == "path.offsetPath")); + match part.id.0 { + 90_001 => { + seen.0 = true; + assert!(!offset, "the compound clipping path keeps its shape"); + } + 90_004 => { + seen.1 = true; + assert!(offset, "the clipped square takes the fill effect"); + } + _ => {} + } + }); + assert_eq!(seen, (true, true)); +} + #[test] fn two_fills_and_an_offset_stroke_become_three_paths_that_look_the_same() { let mut s = session(); diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index f2ab135817..7beb512ed0 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -1184,6 +1184,47 @@ fn mesh_add_line_on_the_edge_from_just_outside() { assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 140, "y": 210, "tolerance": 3})).is_err(), "past the tolerance"); } +/// `object.mesh.addLine` and Create Gradient Mesh `at` a point exactly on the outline add their +/// lines there with no tolerance, on the bottom and right edges as on the top and left ones. +#[test] +fn mesh_add_line_exactly_on_the_edge_needs_no_tolerance() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a]); + let r = s.execute("object.mesh.create", &json!({"at": [50, 100]})).unwrap(); + let m = mesh_of(&s, a); + assert_eq!((m.rows, m.cols), (1, 2), "a column through the bottom edge"); + assert!(m.points[r["index"].as_u64().unwrap() as usize].p.distance(Point::new(50.0, 100.0)) < 0.5); + for (x, y) in [(100.0, 30.0), (20.0, 0.0), (0.0, 80.0)] { + let r = s.execute("object.mesh.addLine", &json!({"id": a.0, "x": x, "y": y})).unwrap(); + let p = mesh_of(&s, a).points[r["index"].as_u64().unwrap() as usize].p; + assert!(p.distance(Point::new(x, y)) < 0.5, "({x}, {y}): {p:?}"); + } + assert_eq!((mesh_of(&s, a).rows, mesh_of(&s, a).cols), (3, 3)); + let n = undo_len(&s); + assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 60, "y": 100.01})).is_err(), "just outside"); + assert_eq!(undo_len(&s), n, "nothing changed"); +} + +/// `object.mesh.addLine` at a point that is already a mesh point (a corner, a point on an edge or +/// inside) adds no line and records no undo step; with a new `color` there it is one step. +#[test] +fn mesh_add_line_at_a_mesh_point_records_no_undo_step() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a]); + s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap(); + let (before, n) = (mesh_of(&s, a), undo_len(&s)); + for (x, y) in [(0.0, 0.0), (100.0, 100.0), (50.0, 100.0), (100.0, 50.0), (50.0, 50.0)] { + let r = s.execute("object.mesh.addLine", &json!({"id": a.0, "x": x, "y": y})).unwrap(); + let p = mesh_of(&s, a).points[r["index"].as_u64().unwrap() as usize].p; + assert!(p.distance(Point::new(x, y)) < 0.5, "({x}, {y}): {p:?}"); + assert_eq!((mesh_of(&s, a), undo_len(&s)), (before.clone(), n), "({x}, {y}): nothing changed"); + } + s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 100, "y": 100, "color": "#00ff00"})).unwrap(); + assert_eq!(undo_len(&s), n + 1, "a new color is a step"); +} + /// A mesh point `index`, and `rows`, `cols` or `columns` for Create Gradient Mesh, that is not a /// whole number is an error that changes nothing; 4.0 names point 4. #[test] diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 247a037e45..deaf60b64f 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -597,6 +597,10 @@ fn the_profile_follows_the_preset_access_and_reset() { let roots = crate::file_access::AutomationRoots::new(&[elsewhere.as_path()], &[dir.as_path()]).unwrap().unwrap(); let r = crate::file_access::confine(Some(&roots), || s.execute("file.new", &json!({"preset": "A4"}))).unwrap(); assert!(r.get("profile").is_none() && r["profileError"]["profile"] == "Print", "{r}"); + // The reason does not say where the folder is. + let reason = r["profileError"]["reason"].as_str().unwrap_or_default(); + let folder = dir.file_name().unwrap().to_string_lossy().to_string(); + assert!(!reason.is_empty() && !reason.contains(&folder), "{reason}"); assert!(!swatch_names(&s).contains(&"Brand Red".to_string())); // Nothing tells such a request which profiles have files. let r = crate::file_access::confine(Some(&roots), || s.execute("file.new", &json!({"preset": "Web 1920×1080"}))).unwrap(); @@ -627,6 +631,58 @@ fn the_profile_follows_the_preset_access_and_reset() { let _ = std::fs::remove_dir_all(&dir); } +/// The new document's links find their files from the profile's file, as a document opened from +/// that file does; a document without a profile has no such file. +#[test] +fn the_new_document_links_from_the_profile_file() { + let (mut s, dir) = with_profiles("links"); + edit_print_profile(&mut s, &dir); + assert_eq!(s.execute("file.new", &json!({"preset": "A4"})).unwrap()["profile"], "Print"); + let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); + assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); + s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); + assert_eq!(s.doc().unwrap().links_from, None); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A color profile the profile's file carries is installed when this machine lacks it, as opening +/// the file installs it, so the new document keeps it and a save carries it; one that can't be used +/// is a warning. +#[test] +fn a_profile_brings_the_color_profile_its_file_carries() { + use vectorcraft_color::cms; + let (mut s, dir) = with_profiles("icc"); + let builtin = cms::profiles().into_iter().find(|p| p.kind == cms::ProfileKind::Rgb && p.builtin && p.name != cms::SRGB).unwrap(); + let icc = cms::icc_bytes(&builtin.name).unwrap().to_vec(); + let name = format!("Profile RGB {}", std::process::id()); + cms::register_icc(&icc, Some(name.clone())).unwrap(); + let bytes_of = |v: &Value| vectorcraft_format::base64_decode(v.as_str().expect("base64")).unwrap(); + s.execute("file.new", &json!({"preset": "Web 1920×1080", "profile": null})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).color_profiles.rgb = Some(name.clone()); + let file = String::from_utf8(bytes_of(&s.execute("file.saveCopy", &json!({"compress": false})).unwrap()["dataBase64"])).unwrap(); + cms::unregister_icc(&name); + // A profile made on another machine names a color profile this one lacks. + let elsewhere = format!("Profile RGB elsewhere {}", std::process::id()); + assert!(cms::profile(&elsewhere).is_none()); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Web.vectorcraft"), file.replace(&name, &elsewhere)).unwrap(); + let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); + assert!(r["profile"] == "Web" && r.get("warnings").is_none(), "{r}"); + assert_eq!(cms::profile(&elsewhere).map(|p| p.kind), Some(cms::ProfileKind::Rgb)); + assert_eq!(s.doc().unwrap().doc.color_profiles.rgb.as_deref(), Some(elsewhere.as_str())); + let saved: Value = serde_json::from_slice(&bytes_of(&s.execute("file.saveCopy", &json!({"compress": false})).unwrap()["dataBase64"])).unwrap(); + assert_eq!(vectorcraft_format::base64_decode(saved["profiles"][&elsewhere]["data"].as_str().unwrap()).unwrap(), icc); + cms::unregister_icc(&elsewhere); + // Damaged profile data starts the document with a warning. + let broken = format!("Profile RGB broken {}", std::process::id()); + let mut v: Value = serde_json::from_str(&file.replace(&name, &broken)).unwrap(); + v["profiles"][&broken]["data"] = json!("AAAA"); + std::fs::write(dir.join("Web.vectorcraft"), serde_json::to_vec(&v).unwrap()).unwrap(); + let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); + assert!(r["profile"] == "Web" && r["warnings"][0].as_str().unwrap_or_default().contains(&broken), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { let (mut s, dir) = with_profiles("damaged"); diff --git a/crates/engine/src/tests/rastersettings.rs b/crates/engine/src/tests/rastersettings.rs index 2110e611ea..75659faf32 100644 --- a/crates/engine/src/tests/rastersettings.rs +++ b/crates/engine/src/tests/rastersettings.rs @@ -455,3 +455,50 @@ fn rasterize_to_cmyk_makes_a_cmyk_image() { assert_eq!((alpha.get_pixel(1, 1).0, alpha.get_pixel(25, 25).0), ([0], [255])); assert!(mask.clip); } + +/// Rasterize with the Grayscale or Bitmap colour model makes a grayscale image (#6969): the +/// image says Grayscale, its file holds one gray channel (one bit a pixel for an opaque Bitmap, +/// gray and alpha over a transparent background), in a CMYK document too, and a fill color +/// colorizes it. +#[test] +fn rasterize_to_grayscale_or_bitmap_makes_a_grayscale_image() { + for mode in ["rgb", "cmyk"] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "colorMode": mode})).unwrap(); + let r = id(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [r.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true, "ids": [r.0]})).unwrap(); + let mut rasterize = |model: &str, background: &str| { + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + let p = json!({"ppi": 72, "colorModel": model, "background": background, "addAround": 5}); + let img = id(&s.execute("object.rasterize", &p).unwrap()); + let info = s.execute("image.info", &json!({"id": img.0})).unwrap(); + let d = &s.doc().unwrap().doc; + let n = d.node(img).unwrap(); + assert!(n.extras().mask.is_none(), "{mode} {model} {background}: no opacity mask"); + let NodeKind::Image(im) = &n.kind else { panic!("an image") }; + let blob = d.images[&im.key].clone(); + let pixels = image::load_from_memory(&blob.bytes).unwrap().to_luma_alpha8(); + assert_eq!(pixels.dimensions(), (50, 50)); + let at = |x, y| pixels.get_pixel(x, y).0; + s.execute("edit.undo", &json!({})).unwrap(); + (info["colorMode"].clone(), blob.gray_source(), at(25, 25), at(1, 1)) + }; + let gray = |one_bit, alpha| Some(vectorcraft_doc::GraySource { one_bit, alpha }); + let (info, source, [level, alpha], corner) = rasterize("grayscale", "white"); + assert_eq!((info, source, alpha, corner), (json!("Grayscale"), gray(false, false), 255, [255, 255]), "{mode}"); + if mode == "rgb" { + assert_eq!(level, 54, "red's Rec. 709 luma"); + } else { + assert!((1..=254).contains(&level), "the CMYK red's screen color as a gray: {level}"); + } + assert_eq!(rasterize("grayscale", "transparent"), (json!("Grayscale"), gray(false, true), [level, 255], [255, 0]), "{mode}"); + assert_eq!(rasterize("bitmap", "white"), (json!("Grayscale"), gray(true, false), [0, 255], [255, 255]), "{mode}"); + assert_eq!(rasterize("bitmap", "transparent"), (json!("Grayscale"), gray(false, true), [0, 255], [255, 0]), "{mode}"); + // A fill color colorizes the image, as it does any grayscale image. + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + let img = id(&s.execute("object.rasterize", &json!({"ppi": 72, "colorModel": "grayscale"})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": [img.0]})).unwrap(); + assert!(s.doc().unwrap().doc.node(img).unwrap().extras().colorize.is_some(), "{mode}: colorized"); + } +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 11787f495f..c78c3e6542 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -644,7 +644,7 @@ impl<'a> Writer<'a> { } NodeKind::Compound { rule, .. } => self.shape(n, &compound_path(n), *rule, xy), NodeKind::Text(_) => self.text(n, xy), - NodeKind::Image(im) => self.image(im, xy), + NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im), xy), NodeKind::SymbolInstance { symbol, xf } if self.live_instance_in_room(n, symbol, *xf) => self.symbol_instance(symbol, *xf, xy), NodeKind::SymbolInstance { symbol, xf } => { if !self.open_group("u") { diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index d421498ff3..8d01b141d0 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -244,6 +244,10 @@ fn read(bytes: &[u8]) -> Option { const MAX_SHEETS: usize = 4096; const MAX_SHEETS_BASED_ON: usize = 16; +/// Most runs of manual kerning read of one story; the characters past them keep the automatic +/// kerning. +const MAX_KERN_RUNS: usize = 1 << 16; + /// Most frames read of one story, and most path segments of a frame. pub(crate) const MAX_FRAMES: usize = 4096; pub(crate) const MAX_SEGMENTS: usize = 1 << 16; @@ -428,6 +432,10 @@ pub(super) struct Story { paras: Vec<(usize, Para)>, /// `(characters, style)` in order. runs: Vec<(usize, Style)>, + /// `(characters, manual kerning)` in order: thousandths of an em after each of those characters + /// (key 8 of the story's text, a run's value its key 0), `None` where the automatic kerning + /// applies. Empty when the story has none. + kerns: Vec<(usize, Option)>, /// Type on a path: the spacing its first frame's layout implies ([`path_spacing`]). path_spacing: f64, /// Vertical type (Type › Type Orientation › Vertical): its lines are columns, from right to @@ -718,12 +726,13 @@ impl Texts { if runs.is_empty() { runs.push((text.chars().count(), self.style(None))); } + let kerns = manual_kerning(s.get("0")?.get("8")); let mut budget = MAX_STORY_TABS; let mut tabs_left_out = false; for (_, p) in &mut paras { tabs_left_out |= p.tabs_truncated | spend_tabs(&mut p.tabs, &mut budget); } - Some(Story { text, anchor, lines, frames, paras, runs, path_spacing, vertical, tabs_left_out: tabs_left_out.into() }) + Some(Story { text, anchor, lines, frames, paras, runs, kerns, path_spacing, vertical, tabs_left_out: tabs_left_out.into() }) } /// A paragraph's attributes (`run`: its attributes, key 5, and the paragraph style it is based @@ -1182,19 +1191,16 @@ impl Story { let to_text = xf.inverse(); let chars: Vec = text.chars().collect(); let mut runs = vec![]; + let mut kerns = Kerns::new(&self.kerns); let mut from = 0usize; for (n, st) in &self.runs { let to = from.saturating_add(*n).min(chars.len()); - let piece: String = chars.get(from..to).unwrap_or_default().iter().collect(); + kerns.split(&chars, from, to, &char_style(st, scale, to_text), &mut runs); from = to; - if piece.is_empty() { - continue; - } - runs.push(TextRun::new(piece, char_style(st, scale, to_text))); } if from < chars.len() { let last = self.runs.last().map(|r| &r.1)?; - runs.push(TextRun::new(chars.get(from..).unwrap_or_default().iter().collect::(), char_style(last, scale, to_text))); + kerns.split(&chars, from, chars.len(), &char_style(last, scale, to_text), &mut runs); } let first = self.runs.first().map(|r| char_style(&r.1, scale, to_text))?; let mut t = TextObject::point(Point::ZERO, "", first); @@ -1330,6 +1336,64 @@ impl Story { } } +/// The manual kerning of a story (`list`: key 8 of its text): each run's characters and value +/// (thousandths of an em), `None` for a run without one (the automatic kerning) or with a value +/// that can't be read. Neighbouring runs of one value are one run. Empty without the key, and past +/// [`MAX_KERN_RUNS`] runs the characters keep the automatic kerning. +fn manual_kerning(list: Option<&Val>) -> Vec<(usize, Option)> { + let mut kerns: Vec<(usize, Option)> = vec![]; + for run in list.and_then(|k| k.get("0")).map(Val::list).unwrap_or_default().iter().take(MAX_KERN_RUNS) { + let Some(n) = run.get("1").and_then(Val::num).filter(|n| *n >= 0.0 && n.fract() == 0.0) else { break }; + let value = run.get("0").and_then(|v| v.get("0")).and_then(Val::num).filter(|v| v.abs() < 1e5); + match kerns.last_mut() { + Some((count, last)) if *last == value => *count = count.saturating_add(n as usize), + _ => kerns.push((n as usize, value)), + } + } + if kerns.iter().all(|(_, v)| v.is_none()) { + kerns.clear(); + } + kerns +} + +/// A walk along a story's manual kerning runs ([`Story::kerns`]), as its style runs are made into +/// text runs. +struct Kerns<'a> { + runs: &'a [(usize, Option)], + /// The run at the walk and the character it starts at. + at: usize, + start: usize, +} + +impl<'a> Kerns<'a> { + fn new(runs: &'a [(usize, Option)]) -> Self { + Self { runs, at: 0, start: 0 } + } + + /// Push the characters `from..to` of `chars` (`from` no earlier than any before) onto `out`, + /// in style `style`, as a text run for each manual kerning they have. + fn split(&mut self, chars: &[char], from: usize, to: usize, style: &CharStyle, out: &mut Vec) { + let mut at = from; + while at < to { + while let Some((n, _)) = self.runs.get(self.at) + && self.start.saturating_add(*n) <= at + { + self.start = self.start.saturating_add(*n); + self.at += 1; + } + let (end, kerning) = match self.runs.get(self.at) { + Some((n, kerning)) => (self.start.saturating_add(*n).min(to), *kerning), + None => (to, None), + }; + let piece: String = chars.get(at..end).unwrap_or_default().iter().collect(); + if !piece.is_empty() { + out.push(TextRun::new(piece, CharStyle { kerning, ..style.clone() })); + } + at = end; + } + } +} + /// The paragraph style of paragraph attributes `p`, its lengths (indents, spacing, the /// hyphenation zone) scaled by `scale`, as sizes are. fn para_style(p: &Para, scale: f64) -> ParaStyle { @@ -1811,6 +1875,78 @@ mod tests { } } + /// Key 8 of a story's text is its manual kerning: runs of characters (key 1), each with its + /// value (key 0 of key 0, thousandths of an em) or empty where the automatic kerning applies. + /// Each character with a value takes it as the space after it, across the story's style runs; + /// a value that can't be read keeps the automatic kerning, and a run whose length can't be read + /// ends the reading there. In users' files a heading's first pair is kerned by -140 and the + /// letters of a line by 20 to 220, and the page draws those gaps that much tighter or wider. + #[test] + fn a_story_keeps_its_manual_kerning() { + // "Wave" at 20 points and a Horizontal Scale of 50%, then " tea" at 10 points. + let styles: &[u8] = b"/6 << /0 [ << /0 << /0 << /6 << /1 20.0 /6 0.5 >> >> >> /1 4 >> << /0 << /0 << /6 << /1 10.0 >> >> >> /1 5 >> ] >>"; + let texts = |kerns: &[u8]| Texts { + stories: vec![read(&[b"/0 << /0 (Wave tea\r) ", styles, b" ", kerns, b" >> /1 << /0 [ << /0 0 >> ] >>"].concat()).unwrap()], + fonts: vec![], + defaults: Val::Dict(BTreeMap::new()), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![], + para_sheets: vec![], + frames: vec![read(b"/0 << /0 [ 0 0 ] /2 << /0 0 >> >>").unwrap()], + patterns: HashMap::new(), + }; + let text = |kerns: &[u8]| -> TextObject { + let node = texts(kerns).story(0).unwrap().node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY).unwrap(); + let NodeKind::Text(t) = node.kind else { panic!("type") }; + *t + }; + let runs = |kerns: &[u8]| -> Vec<(String, f64, Option)> { + text(kerns).runs.iter().map(|r| (r.text.clone(), r.style.size, r.style.kerning)).collect() + }; + let run = |text: &str, size: f64, kerning: Option| (text.to_string(), size, kerning); + // "W" -140, "av" none, "e t" 80 across the style runs, "e" a value that can't be read, "a" none. + let kerned: &[u8] = b"/8 << /0 [ << /0 << /0 -140 >> /1 1 >> << /0 << >> /1 2 >> << /0 << /0 80 >> /1 3 >> \ + << /0 << /0 (x) >> /1 1 >> << /0 << >> /1 2 >> ] >>"; + assert_eq!( + runs(kerned), + [run("W", 20.0, Some(-140.0)), run("av", 20.0, None), run("e", 20.0, Some(80.0)), run(" t", 10.0, Some(80.0)), run("ea", 10.0, None)] + ); + // Without the key, or with no value in it, the style runs stay as they are. + let plain = [run("Wave", 20.0, None), run(" tea", 10.0, None)]; + assert_eq!(runs(b""), plain); + assert_eq!(runs(b"/8 << /0 [ << /0 << >> /1 9 >> ] >>"), plain); + // Values out of range keep the automatic kerning, and a length that can't be read ends the runs. + let out_of_range: &[u8] = b"/8 << /0 [ << /0 << /0 1e9 >> /1 1 >> << /0 << /0 NaN >> /1 1 >> << /0 << /0 60 >> /1 1 >> ] >>"; + assert_eq!(runs(out_of_range)[..2], [run("Wa", 20.0, None), run("v", 20.0, Some(60.0))]); + for bad in [b"-1".as_slice(), b"1.5", b"(1)", b"NaN"] { + let k = [b"/8 << /0 [ << /0 << /0 60 >> /1 1 >> << /0 << /0 60 >> /1 ".as_slice(), bad, b" >> << /0 << /0 60 >> /1 2 >> ] >>"].concat(); + assert_eq!(runs(&k), [run("W", 20.0, Some(60.0)), run("ave", 20.0, None), run(" tea", 10.0, None)], "{}", String::from_utf8_lossy(bad)); + } + // Laid out, the space after "W" is 140 thousandths of the em tighter than with a value of + // 0, of the em as the run's Horizontal Scale (50%) draws it. + let db = vectorcraft_text::FontDb::global(); + let gap = |t: &TextObject| { + let laid = vectorcraft_text::layout(db, t); + laid.glyphs[1].origin.x - laid.glyphs[0].origin.x + }; + let (with, zero) = (gap(&text(kerned)), gap(&text(b"/8 << /0 [ << /0 << /0 0 >> /1 1 >> ] >>"))); + assert!((zero - with - 0.14 * 20.0 * 0.5).abs() < 1e-6, "{with} {zero}"); + } + + /// Past [`MAX_KERN_RUNS`] runs of manual kerning the characters keep the automatic kerning, so a + /// story makes no more text runs of its kerning than that. + #[test] + fn manual_kerning_reads_at_most_its_limit_of_runs() { + let dict = |entries: Vec<(&str, Val)>| Val::Dict(entries.into_iter().map(|(k, v)| (k.to_string(), v)).collect()); + // One character each, the values alternating, so no two neighbouring runs are one. + let run = |i: usize| dict(vec![("0", dict(vec![("0", Val::Num(if i.is_multiple_of(2) { 10.0 } else { 20.0 }))])), ("1", Val::Num(1.0))]); + let list = dict(vec![("0", Val::List((0..MAX_KERN_RUNS + 2).map(run).collect()))]); + let kerns = manual_kerning(Some(&list)); + assert_eq!(kerns.len(), MAX_KERN_RUNS); + assert_eq!(kerns.iter().map(|(n, _)| n).sum::(), MAX_KERN_RUNS); + assert_eq!(kerns.last(), Some(&(1, Some(20.0)))); + } + /// A right-to-left paragraph is laid out right to left even when it has no right-to-left /// letters (a dimension's label " 120.5 mm " reads "mm 120.5"); a left-to-right one, or one /// that doesn't say, goes by its letters. @@ -2090,6 +2226,7 @@ mod tests { standard_vertical_roman: false, }, )], + kerns: vec![], path_spacing: 0.0, vertical: false, tabs_left_out: false.into(), diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index d8948bf42f..c7cdf20e11 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3498,6 +3498,25 @@ fn type_painted_with_a_pattern_takes_it_from_the_art_style_its_paint_names() { assert_eq!(r.document.pattern("Dots").map(|p| p.tile.height()), Some(4.0)); } +#[test] +fn type_keeps_its_manual_kerning() { + // GUARDS: the text document's manual kerning (key 8 of a story's text: runs of characters, each + // with its value or none) wasn't read, so type the file kerns by hand came in spaced by the + // font alone and drifted from the page from each kerned pair on. "Wave": "W" kerned by -140, + // "av" automatic, "e" by 60. + let doc = text_document(&[("Wave\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let run = "<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 /53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >> >> >> /1 5 >>"; + assert!(doc.contains(run)); + let kerns = "/8 << /0 [ << /0 << /0 -140 >> /1 1 >> << /0 << >> /1 2 >> << /0 << /0 60 >> /1 1 >> << /0 << >> /1 1 >> ] >>"; + let doc = doc.replacen(run, &format!("{run} ] >> {kerns}"), 1).replacen(&format!("{kerns} ] >> >>"), &format!("{kerns} >>"), 1); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &text_object(0))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + let texts = text_of(&r.document.layers[1]); + assert_eq!(texts.len(), 1, "{:?}", r.warnings); + let runs: Vec<(String, Option)> = texts[0].runs.iter().map(|r| (r.text.clone(), r.style.kerning)).collect(); + assert_eq!(runs, [("W".to_string(), Some(-140.0)), ("av".to_string(), None), ("e".to_string(), Some(60.0))]); +} + #[test] fn orientation_and_tate_chu_yoko_values_it_cant_use_are_ignored() { for bad in ["(2)", "2.5", "1e300", "-2", "1", "true", "[ 2 ]"] { diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 04c916d324..042a7ed2d2 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -179,7 +179,7 @@ pub fn writes_image_mask(doc: &Document, n: &Node) -> bool { matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })) && !n.extras().mask.as_ref().is_some_and(|m| !m.disabled) && doc - .image_blob(im) + .image_blob(&doc.shown_image(n, im)) .is_some_and(|b| b.takes_colorize() && fits(&b.bytes) && b.coverage().is_some_and(|(_, _, c)| c.iter().all(|&v| v == 0 || v == 255))) } diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 557c59ab34..06d9e0ddcc 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -283,7 +283,8 @@ impl<'a> Writer<'a> { } NodeKind::Image(im) => { self.lock(locked); - let blob = self.doc.image_blob(im); + let shown = self.doc.shown_image(n, im); + let blob = self.doc.image_blob(&shown); // A colorize color the renderer draws the image in. let colorize = n.extras().colorize.as_deref().filter(|p| matches!(p, Paint::Solid { .. }) && blob.is_some_and(ImageBlob::takes_colorize)); diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 5cc90117d7..e8ffa4b278 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -367,6 +367,8 @@ impl<'a> Scene<'a> { } NodeKind::Text(t) => self.text(n, t), NodeKind::Image(im) => { + let shown = self.doc.shown_image(n, im); + let im = &*shown; let blob = self.doc.image_blob(im); match n.extras().colorize.as_deref() { Some(p @ Paint::Solid { .. }) if blob.is_none_or(|b| b.gray_source().is_some()) => { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index aa26995efc..d66ea18445 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -469,7 +469,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.control.dock", "Dock Control Bar", "", - "{edge: \"top\"|\"bottom\"} dock the Control bar to the top of the window, under the menu bar, or to its bottom, as the bar's panel menu (Dock to Top, Dock to Bottom) and a drag of its gripper do; kept with the workspace; another edge is an error and changes nothing; returns {edge}", + "{edge: \"top\"|\"bottom\"|\"float\"} dock the Control bar to the top of the window, under the menu bar, or to its bottom, as the bar's panel menu (Dock to Top, Dock to Bottom) and a drag of its gripper do, or float it over the window at the position it last floated at (first: its top-left corner at 60, 80 in window points), as a gripper drag released away from both edges does; kept with the workspace; another edge is an error and changes nothing; returns {edge}", ), ( "window.control.options", @@ -1439,6 +1439,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{set?: index, action?: index, step?: index, command, params?: object} insert the command of a menu item as a step, without running it; the step plays as choosing the item runs it. command and params (default {}) must be those of a menu item that can be a step: one that runs an engine command, whose label does not end with \"…\", outside the VectorCraft, File, Window and Help menus, and that is not Undo, Redo, a Paste, a batch (command.batch), a preference (prefs.*) or action (action.*) command, an Object › Align item, Image Trace's Make or Make and Expand, Pattern's Make or Edit Pattern, a saved selection, saved view or recent font item, or a plug-in's item. The place is as ui.action.insertStop takes it: with set and action, after step, else after the action's last step; without them, the recording in progress. The new step becomes the panel's selected step, and its action and set become the selected ones. A command and params that no such menu item has, a param of another type, params that are not an object, no action and no recording, or a step that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. The panel menu's Insert Menu Item… (dialog `actionInsertMenuItem` with find, command, params, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", ), + ( + "ui.action.insertSelectObject", + "Select Object", + "", + "{set?: index, action?: index, step?: index, note, caseSensitive?: bool, wholeWord?: bool} insert a Select Object step, without running it: playback runs select.byNote {note, caseSensitive, wholeWord}, which selects the objects whose Attributes note matches note, and a playback that finds no such object stops there with an error. note loses its leading and trailing spaces and must then be 1 to 1,024 bytes; caseSensitive and wholeWord default to false. The place is as ui.action.insertStop takes it: with set and action, after step, else after the action's last step; without them, the recording in progress. The new step becomes the panel's selected step, and its action and set become the selected ones. A missing or empty note, a param of another type, params that are not an object, no action and no recording, or a step that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. The panel menu's Select Object… (dialog `actionSelectObject`, Set Selection, with note, caseSensitive, wholeWord, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", + ), ( "ui.action.continue", "Continue Action", diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index ac5cf183cd..ecba61ce8e 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -213,7 +213,7 @@ impl<'a> Scene<'a> { self.node(&o, true); } } - NodeKind::Image(im) => self.image(im), + NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)), NodeKind::SymbolInstance { symbol, xf } => { if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 2143ecba61..c377b9f7e4 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -165,6 +165,9 @@ impl Exporter<'_> { pub(super) fn masked_image(&mut self, im: &vectorcraft_doc::ImageObject, m: &vectorcraft_doc::OpacityMask, interpolate: bool) -> Option { let art = &m.art; let NodeKind::Image(mi) = &art.kind else { return None }; + // A color-masked image in the mask's art masks with the pixels it shows. + let shown = self.doc.shown_image(art, mi); + let mi = &*shown; let plain = art.opacity >= 1.0 && art.blend == BlendMode::Normal && art.extras().mask.is_none() && !art.appearance.effects.iter().any(|e| e.visible); if m.invert || !plain || (mi.xf, mi.width, mi.height) != (im.xf, im.width, im.height) { diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 2d4113a1fa..f8fb792ec2 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -249,8 +249,9 @@ impl Exporter<'_> { self.shape(s, n, &bp, *rule, page); } NodeKind::Text(t) => self.text(s, n, t, page), - NodeKind::Image(im) => match n.extras().colorize.as_deref() { - Some(p @ Paint::Solid { .. }) if self.doc.image_blob(im).is_none_or(vectorcraft_doc::ImageBlob::takes_colorize) => { + NodeKind::Image(im) => match (n.extras().colorize.as_deref(), self.doc.shown_image(n, im)) { + (Some(p @ Paint::Solid { .. }), im) if self.doc.image_blob(&im).is_none_or(vectorcraft_doc::ImageBlob::takes_colorize) => { + let im = &*im; if writable(s, im.xf, Rect::new(0.0, 0.0, im.width.max(1).into(), im.height.max(1).into())) { if let Some(colorized) = self.colorized_image(im, p, !n.extras().pixelated) { self.image(s, im, Some(colorized), n.extras().pixelated); @@ -263,7 +264,7 @@ impl Exporter<'_> { self.warn(super::exporter::UNWRITABLE_IMAGE); } } - _ => self.image(s, im, alpha, n.extras().pixelated), + (_, im) => self.image(s, &im, alpha, n.extras().pixelated), }, NodeKind::SymbolInstance { symbol, xf } => { // Within the objects a frame may draw of symbol instances, as on screen: nested diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index a46d1137a7..42ca9e5a1d 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -153,25 +153,34 @@ fn colorized_key(key: &str) -> String { } /// Point the colorized images in `n`'s subtree at [`colorized_key`], collecting their keys in -/// `keys`. An image whose pixels in `images` don't take its colorize paint -/// ([`ImageBlob::takes_colorize`]) loses the paint instead, and is separated as the image it shows. +/// `keys`. A colorized image with a color mask is separated as it shows: its masked pixels +/// ([`Document::shown_image`]). An image whose pixels it shows in `images` don't take its colorize +/// paint ([`ImageBlob::takes_colorize`]) loses the paint instead, and is separated as the image it +/// shows. fn keep_colorized_pixels(n: &mut Arc, images: &BTreeMap, keys: &mut BTreeSet) { let colorized = |n: &Node| matches!(n.kind, NodeKind::Image(ref im) if im.pixels.is_none()) && n.extras().colorize.is_some(); if !colorized(n) && n.children().is_none_or(|ch| ch.is_empty()) { return; } let node = Arc::make_mut(n); - if colorized(node) - && let NodeKind::Image(im) = &node.kind - && images.get(&im.key).is_some_and(|b| !b.takes_colorize()) - { + let shown = match &node.kind { + NodeKind::Image(im) if colorized(node) => { + let mask = Document::color_mask_of(node).filter(|m| m.made_for(im) && images.contains_key(&m.key)); + Some(mask.map_or(&im.key, |m| &m.key).clone()) + } + _ => None, + }; + if shown.as_ref().and_then(|key| images.get(key)).is_some_and(|b| !b.takes_colorize()) { node.extras_mut().colorize = None; } - if colorized(node) - && let NodeKind::Image(im) = &mut node.kind - { - keys.insert(im.key.clone()); - im.key = colorized_key(&im.key); + if let Some(key) = shown.filter(|_| colorized(node)) { + if let Some(e) = node.extras_if_any() { + e.color_mask = None; + } + if let NodeKind::Image(im) = &mut node.kind { + im.key = colorized_key(&key); + keys.insert(key); + } } if let Some(ch) = node.children_mut() { for c in ch.iter_mut() { diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 6abe2f3885..2ad5ab8bba 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -380,6 +380,11 @@ fn the_output_settings_convert_cmyk_images_and_compression_recompresses_them_in_ /// A Press Quality export of a 2 × 2 CMYK image masked by PNG `mask` on its own pixel grid /// (`clip`, `invert`): the file, and the decoded soft mask of each CMYK image (`None`: it has none). fn export_masked(mask: Vec, clip: bool, invert: bool) -> (Vec, Vec>>) { + export_smasks(&masked_doc(mask, clip, invert)) +} + +/// A document of a 2 × 2 CMYK image masked by PNG `mask` (key `alpha`) on its own pixel grid. +fn masked_doc(mask: Vec, clip: bool, invert: bool) -> Document { let ink = [0u8, 102, 255, 0]; let mut d = Document::new_with_mode(100.0, 100.0, ColorMode::Cmyk); d.images.insert("img".into(), ImageBlob::cmyk_tiff(&Inks::new(2, 2, flat(ink, 4)).unwrap()).unwrap()); @@ -400,8 +405,14 @@ fn export_masked(mask: Vec, clip: bool, invert: bool) -> (Vec, Vec (Vec, Vec>>) { let press = builtin_presets().into_iter().find(|p| p.name == "Press Quality").unwrap().settings; - let out = export_with_report(&d, &PdfOptions { settings: press, created: Some(1_700_000_000), ..Default::default() }).unwrap(); + let out = export_with_report(d, &PdfOptions { settings: press, created: Some(1_700_000_000), ..Default::default() }).unwrap(); let file = Pdf::new(Arc::new(out.bytes.clone())).unwrap(); let smasks = file .objects() @@ -440,6 +451,34 @@ fn a_cmyk_image_masked_by_a_grey_image_of_its_grid_writes_it_as_its_smask() { assert!(String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "a luminosity soft mask"); } +/// A grey mask image with a color mask masks the CMYK image with the pixels it shows: its hidden +/// pixels are clear in the image's `/SMask`. +#[test] +fn a_color_masked_grid_mask_image_writes_the_pixels_it_shows_as_the_smask() { + let mut d = masked_doc(png(image::GrayImage::from_raw(2, 2, vec![255, 128, 0, 64]).unwrap()), true, false); + // The last pixel hidden. + d.images.insert( + "shown".into(), + ImageBlob::new("image/png", png(image::GrayAlphaImage::from_raw(2, 2, vec![255, 255, 128, 255, 0, 255, 64, 0]).unwrap())), + ); + let id = d.layers[0].children().unwrap()[0].id; + let mut mask = d.node(id).unwrap().extras().mask.clone().unwrap(); + let art = std::sync::Arc::make_mut(&mut mask.art); + art.extras_mut().color_mask = Some(Box::new(vectorcraft_doc::color_mask::ColorMask { + key: "shown".into(), + from: "alpha".into(), + background: vectorcraft_doc::color_mask::MaskBackground::Colors, + colors: vec![[64, 64, 64]], + contiguous: false, + measure: vectorcraft_doc::color_mask::MaskMatch::Distance, + tolerance: 0.0, + softness: 0.0, + })); + d.node_mut(id).unwrap().extras_mut().mask = Some(mask); + let (_, smasks) = export_smasks(&d); + assert_eq!(smasks, [Some(vec![255, 128, 0, 0])]); +} + /// A pixelated CMYK image (an envelope's with Anti-Alias off) masked by a grey image of its grid /// is written without /Interpolate, as one without a mask is. #[test] diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index f81fc17514..60d7a9bd67 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -168,6 +168,76 @@ fn separations_print_the_image_on_its_ink_plate() { } } +/// Printed separations separate a colorized image with a color mask as it shows: the pixels the +/// mask hides print on no plate. +#[test] +fn separations_print_a_color_masked_image_as_it_shows() { + let spot = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 }; + let mut d = doc(ColorMode::Cmyk, Some(spot)); + // The black pixel hidden. + let mut png = vec![]; + image::GrayAlphaImage::from_raw(2, 1, vec![0, 0, 255, 255]) + .unwrap() + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + d.images.insert("shown".into(), ImageBlob::png(png)); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().color_mask = Some(Box::new(vectorcraft_doc::color_mask::ColorMask { + key: "shown".into(), + from: "pic".into(), + background: vectorcraft_doc::color_mask::MaskBackground::Colors, + colors: vec![[0, 0, 0]], + contiguous: false, + measure: vectorcraft_doc::color_mask::MaskMatch::Distance, + tolerance: 0.0, + softness: 0.0, + })); + let settings: PrintSettings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap(); + let job = plan(&d, &PrintOptions { settings, ..Default::default() }).unwrap(); + assert!(!job.plates.is_empty()); + for p in &job.plates { + let n = &p.layers[0].children().unwrap()[0]; + let NodeKind::Image(im) = &n.kind else { panic!("an image") }; + assert_eq!(p.image_blob(im).and_then(|b| b.coverage()).unwrap().2, [0, 0], "the hidden black pixel prints on no plate"); + } +} + +/// A colorized image with a color mask keeps its colorize paint on the plates when its masked +/// pixels take it, as on the canvas, though its own pixels are a preview that doesn't. +#[test] +fn separations_colorize_masked_pixels_whose_own_pixels_are_a_preview() { + let spot = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 }; + let mut d = doc(ColorMode::Cmyk, Some(spot)); + let preview = Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); + d.images.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }); + let mut png = vec![]; + image::GrayAlphaImage::from_raw(2, 1, vec![0, 0, 255, 255]) + .unwrap() + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + d.images.insert("shown".into(), ImageBlob::png(png)); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().color_mask = Some(Box::new(vectorcraft_doc::color_mask::ColorMask { + key: "shown".into(), + from: "pic".into(), + background: vectorcraft_doc::color_mask::MaskBackground::Colors, + colors: vec![[0, 0, 0]], + contiguous: false, + measure: vectorcraft_doc::color_mask::MaskMatch::Distance, + tolerance: 0.0, + softness: 0.0, + })); + let settings: PrintSettings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap(); + let job = plan(&d, &PrintOptions { settings, ..Default::default() }).unwrap(); + assert!(!job.plates.is_empty()); + for p in &job.plates { + let n = &p.layers[0].children().unwrap()[0]; + let NodeKind::Image(im) = &n.kind else { panic!("an image") }; + assert!(n.extras().colorize.is_some(), "the masked pixels take the colorize paint"); + assert_eq!(p.image_blob(im).and_then(|b| b.coverage()).unwrap().2, [0, 0], "separated as the masked pixels"); + } +} + /// A linked image showing the missing-link placeholder is written in the placeholder's own colors /// though it keeps a colorize paint for its file, and printed separations separate it as an /// uncolorized image. diff --git a/crates/render/src/encode/png.rs b/crates/render/src/encode/png.rs index f55fd316db..6a62034e10 100644 --- a/crates/render/src/encode/png.rs +++ b/crates/render/src/encode/png.rs @@ -53,6 +53,21 @@ pub fn encode(rgba: &[u8], width: u32, height: u32, o: &PngOptions) -> Result Result, String> { + check_size(width, height)?; + if gray_alpha.len() as u64 != u64::from(width) * u64::from(height) * 2 { + return Err("PNG encoding failed: pixel buffer doesn't match the image size".into()); + } + let px = gray_alpha.as_chunks::<2>().0; + if px.iter().all(|p| p[1] == 255) { + let levels: Vec = px.iter().map(|p| p[0]).collect(); + return write(&levels, width, height, Layout { channels: 1, bits: 8, color_type: 0 }, &[], o); + } + write(gray_alpha, width, height, Layout { channels: 2, bits: 8, color_type: 4 }, &[], o) +} + /// Encode a palette image as an indexed PNG (colour type 3: `PLTE`, and `tRNS` for its /// transparent entry) at 1, 2, 4 or 8 bits per pixel, as few as the palette needs. pub fn encode_indexed(img: &Indexed, o: &PngOptions) -> Result, String> { diff --git a/crates/render/src/encode/tests.rs b/crates/render/src/encode/tests.rs index 0935ba3567..a910480641 100644 --- a/crates/render/src/encode/tests.rs +++ b/crates/render/src/encode/tests.rs @@ -67,6 +67,41 @@ fn png_refuses_a_buffer_of_the_wrong_size() { assert!(encode(&[], 0, 0, &PngOptions::default()).is_err()); } +/// Object › Rasterize's Grayscale and Bitmap images (#6969): a grey PNG of one channel when +/// opaque and grey and alpha otherwise; Bitmap's black and white as a 1-bit TIFF when opaque, +/// else as a grey PNG with alpha. Odd widths keep each row on a byte. +#[test] +fn gray_and_bilevel_images_store_gray() { + let header = |file: &[u8]| (file[24], file[25]); + let gray = |file: &[u8]| image::load_from_memory(file).unwrap().to_luma_alpha8().into_raw(); + // 3 × 2, premultiplied: black, red, light grey; white, mid grey, almost black. + let mut img = Rendered { + width: 3, + height: 2, + pixels: [[0, 0, 0], [255, 0, 0], [200; 3], [255; 3], [128; 3], [127; 3]].iter().flat_map(|&[r, g, b]| [r, g, b, 255]).collect(), + }; + let levels: Vec = [0u8, 54, 200, 255, 128, 127].iter().flat_map(|&g| [g, 255]).collect(); + let file = img.to_gray_png().unwrap(); + assert_eq!(header(&file), (8, 0), "8-bit grey"); + assert_eq!(gray(&file), levels); + let (mime, file) = img.to_bilevel(150.0).unwrap(); + assert_eq!(mime, "image/tiff"); + let mut d = ::tiff::decoder::Decoder::new(std::io::Cursor::new(&file)).unwrap(); + assert_eq!(d.colortype().unwrap(), ::tiff::ColorType::Gray(1)); + let bw: Vec = [0u8, 0, 255, 255, 255, 0].iter().flat_map(|&g| [g, 255]).collect(); + assert_eq!(gray(&file), bw, "from 128 up is white"); + // Half-covered white over the light grey; a clear pixel is white. + img.pixels[8..12].copy_from_slice(&[100, 100, 100, 100]); + img.pixels[20..24].copy_from_slice(&[0; 4]); + let file = img.to_gray_png().unwrap(); + assert_eq!(header(&file), (8, 4), "grey and alpha"); + assert_eq!(gray(&file), [0, 255, 54, 255, 255, 100, 255, 255, 128, 255, 255, 0]); + let (mime, file) = img.to_bilevel(150.0).unwrap(); + assert_eq!((mime, header(&file)), ("image/png", (8, 4)), "no 1-bit grey with alpha"); + assert_eq!(gray(&file), [0, 255, 0, 255, 255, 100, 255, 255, 255, 255, 255, 0], "still black and white"); + assert!(super::png::encode_gray(&levels[..10], 3, 2, &PngOptions::default()).is_err()); +} + /// A 40×30 pt document with a black circle off the pixel grid. fn circle_doc() -> Document { let mut d = Document::new(40.0, 30.0); diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 58c8714306..6fbd9f37ac 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -4,6 +4,7 @@ use super::{ Affine, AppearanceItem, Arc, BezPath, Document, Effect, FillRule, GeomContext, Node, NodeKind, PathEl, Rect, Renderer, Shape, SymbolBoxes, effects, }; +use vectorcraft_doc::symbol_overrides::dynamic_art; fn node_bezpath(n: &Node) -> Option { match &n.kind { @@ -203,11 +204,14 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { // effects in a symbol's art and a live object's content paint past it. _ if has_object_fx(n) => { let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()), + NodeKind::SymbolInstance { symbol, .. } => { + symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n)) + } _ => None, }; - let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_deref()); + let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref()); let b = match &reshaped { + Some(r) if matches!(n.kind, NodeKind::SymbolInstance { .. }) && effects::has_item_geometry(n) => instance_piece_bounds(symbols, r), Some(r) if matches!(n.kind, NodeKind::Text(_)) || (matches!(n.kind, NodeKind::Image(_)) && !r.clips()) => { r.children().into_iter().flatten().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, painted_reach(symbols, c))) } @@ -230,6 +234,55 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { } } +/// The bounds of `art`, the art [`effects::reshape`] made of a symbol instance whose active fill or +/// stroke has geometry effects ([`effects::has_item_geometry`]): its paths measured with the +/// geometry effects of their fills and strokes ([`visual_bounds`]), the symbol instances in it that +/// took those effects by their own reshaped art in turn, its groups and layers with their own fills +/// and strokes by the art those paint ([`effects::evaluate_container`]), its clip groups by their +/// clipping paths and other objects as [`Node::visual_bounds_with`] measures them. Hidden objects are left out. +/// An instance more than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, or whose art would +/// take the objects measured so far past [`effects::SYMBOL_ART_MAX_NODES`], is measured as +/// [`Node::visual_bounds_with`] measures it. +fn instance_piece_bounds(symbols: &SymbolBoxes, art: &Node) -> Option { + let mut budget = effects::SYMBOL_ART_MAX_NODES; + pieces_within(symbols, art, 1, &mut budget) +} + +/// [`instance_piece_bounds`] of `art`, `depth` instances deep, with `budget` objects left to measure. +fn pieces_within(symbols: &SymbolBoxes, art: &Node, depth: usize, budget: &mut u64) -> Option { + if !art.visible { + return None; + } + match &art.kind { + NodeKind::Group { clip: false, .. } | NodeKind::Layer { clip: false, .. } => { + // A group's or layer's own fills and strokes as the art among its members that they paint. + let evaluated = effects::has_container_appearance(art).then(|| effects::evaluate_container(Some(symbols.document()), art)).flatten(); + let g = evaluated.as_ref().unwrap_or(art); + if g.clips() { + return g.visual_bounds_with(symbols); + } + g.children().into_iter().flatten().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, pieces_within(symbols, c, depth, budget))) + } + NodeKind::Path { .. } | NodeKind::Compound { .. } if has_fx(art) => visual_bounds(symbols, art), + NodeKind::SymbolInstance { symbol, .. } if depth < vectorcraft_doc::depth::MAX_DEPTH && effects::has_item_geometry(art) => { + let doc = symbols.document(); + let reshaped = doc.symbols.iter().find(|s| s.name == *symbol).and_then(|s| { + let count = s.art.count() as u64; + if count > *budget { + return None; + } + *budget -= count; + effects::reshape(Some(doc), art, Some(&dynamic_art(&s.art, art))) + }); + match reshaped { + Some(r) => pieces_within(symbols, &r, depth + 1, budget), + None => art.visual_bounds_with(symbols), + } + } + _ => art.visual_bounds_with(symbols), + } +} + /// [`drawn_bounds`] of `n` grown by how far its own raster effects paint past them. With Crop /// Marks, the [`drawn_bounds`] of its art: the marks and the object, which paints its own raster /// effects inside the art. @@ -406,11 +459,14 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool) -> Optio // symbol instance's art paint past that art. _ if has_object_fx(n) => { let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()), + NodeKind::SymbolInstance { symbol, .. } => { + symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n)) + } _ => None, }; - let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_deref()); + let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref()); let b = match &reshaped { + Some(r) if matches!(n.kind, NodeKind::SymbolInstance { .. }) && effects::has_item_geometry(n) => instance_piece_bounds(symbols, r), Some(r) if matches!(n.kind, NodeKind::Text(_)) || (matches!(n.kind, NodeKind::Image(_)) && !r.clips()) => { r.children().into_iter().flatten().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, inner(c))) } diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index e9aa8486d8..1e4c39f4eb 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -662,14 +662,20 @@ impl Renderer { // shortcut: art kept by `fx_arts` isn't made again when only a swatch's kind (spot or // process) changes, which Duotone reads; editing the object makes it again. let swatches = |name: &str| effects::addons::duotone::swatch_kind(doc, name); - let adjusted = effects::adjust(&art, outer, &swatches, &mut |key, map| { - let mut h = std::hash::DefaultHasher::new(); - std::hash::Hash::hash(&format!("{map:?}"), &mut h); - let hash = std::hash::Hasher::finish(&h); - let derived = format!("{key}\u{0}adjust\u{0}{hash:016x}"); - wanted.push((key.to_string(), derived.clone(), hash, map.clone())); - Some(derived) - }); + let adjusted = effects::adjust( + &art, + outer, + &swatches, + &mut |key, map| { + let mut h = std::hash::DefaultHasher::new(); + std::hash::Hash::hash(&format!("{map:?}"), &mut h); + let hash = std::hash::Hasher::finish(&h); + let derived = format!("{key}\u{0}adjust\u{0}{hash:016x}"); + wanted.push((key.to_string(), derived.clone(), hash, map.clone())); + Some(derived) + }, + &|key| doc.images.contains_key(key), + ); for (key, derived, hash, map) in wanted { self.adjusted_image(&key, derived, hash, &map); } diff --git a/crates/render/src/options.rs b/crates/render/src/options.rs index 8ca670eb3f..7a9a9b81f2 100644 --- a/crates/render/src/options.rs +++ b/crates/render/src/options.rs @@ -356,6 +356,58 @@ impl Rendered { img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?; Ok(buf) } + /// Each pixel's grey level and alpha: the Rec. 709 luma of its straight colour, with `bilevel` + /// black below 128 and white from there up. A clear pixel is white: no ink where a fill + /// colour colorizes the image. + fn gray_alpha(&self, bilevel: bool) -> Vec { + let straight = self.to_straight(); + let px = straight.as_chunks::<4>().0; + px.iter() + .flat_map(|&[r, g, b, a]| { + let y = (0.2126 * f32::from(r) + 0.7152 * f32::from(g) + 0.0722 * f32::from(b)).round().clamp(0.0, 255.0) as u8; + let y = if a == 0 || (bilevel && y >= 128) { + 255 + } else if bilevel { + 0 + } else { + y + }; + [y, a] + }) + .collect() + } + /// Encode as a greyscale PNG without metadata (Object › Rasterize's Grayscale colour model): + /// grey levels ([`Self::gray_alpha`]), with alpha only when some pixel isn't opaque. + pub fn to_gray_png(&self) -> Result, String> { + encode::png::encode_gray(&self.gray_alpha(false), self.width, self.height, &encode::png::PngOptions::default()) + } + /// Encode in black and white (Object › Rasterize's Bitmap colour model): a 1-bit TIFF at `ppi` + /// when every pixel is opaque, else a grey PNG with alpha of only black and white (one-bit grey + /// with alpha is no format readers take). Returns the media type and the file. + pub fn to_bilevel(&self, ppi: f64) -> Result<(&'static str, Vec), String> { + let gray_alpha = self.gray_alpha(true); + let px = gray_alpha.as_chunks::<2>().0; + if !px.iter().all(|p| p[1] == 255) { + return Ok(("image/png", encode::png::encode_gray(&gray_alpha, self.width, self.height, &encode::png::PngOptions::default())?)); + } + // WhiteIsZero: a set bit is black. Each row starts on a byte. + let mut bits = Vec::with_capacity(px.len() / 8 + self.height as usize); + for row in px.chunks(self.width.max(1) as usize) { + bits.extend(row.chunks(8).map(|byte| byte.iter().enumerate().fold(0u8, |b, (i, p)| b | u8::from(p[0] == 0) << (7 - i)))); + } + let image = encode::tiff::Image { + width: self.width, + height: self.height, + data: &bits, + photometric: encode::tiff::Photometric::WhiteIsZero, + samples: 1, + bits: 1, + alpha: false, + }; + let layout = + encode::tiff::Layout { byte_order: encode::tiff::ByteOrder::Little, compression: encode::tiff::Compression::PackBits, ppi, icc: None }; + Ok(("image/tiff", encode::tiff::write(&image, &layout)?)) + } /// Encode as JPEG (flattened on white) at `quality` 1..=100. pub fn to_jpeg(&self, quality: u8) -> Result, String> { encode::jpeg(self, quality, None) diff --git a/crates/render/src/renderer/images.rs b/crates/render/src/renderer/images.rs index a604481dd4..76b3bf53f2 100644 --- a/crates/render/src/renderer/images.rs +++ b/crates/render/src/renderer/images.rs @@ -11,7 +11,7 @@ use crate::images; pub(super) fn image_tint(doc: &Document, n: &Node, ink: Ink) -> Option<[u8; 3]> { let c = n.extras().colorize.as_deref()?.color()?; if let NodeKind::Image(im) = &n.kind - && doc.image_blob(im).is_some_and(|b| !b.takes_colorize()) + && doc.image_blob(&doc.shown_image(n, im)).is_some_and(|b| !b.takes_colorize()) { return None; } diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index ca6611ea5f..47f2dec770 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -250,7 +250,7 @@ impl Renderer { && let Some(region) = self.clip_of(&m.art) && shape_masked_image(a, im, ®ion.0) { - self.draw_image_in(ctx, f, im, Some(®ion), images::image_tint(f.doc, a, f.ink), a.extras().pixelated); + self.draw_image_in(ctx, f, &f.doc.shown_image(a, im), Some(®ion), images::image_tint(f.doc, a, f.ink), a.extras().pixelated); self.stats.drawn += 1; return; } @@ -518,7 +518,8 @@ impl Renderer { && let NodeKind::Image(im) = &image.kind && plain_image(image, im, ®ion.0) { - self.draw_image_in(ctx, f, im, Some(®ion), images::image_tint(f.doc, image, f.ink), image.extras().pixelated); + let im = f.doc.shown_image(image, im); + self.draw_image_in(ctx, f, &im, Some(®ion), images::image_tint(f.doc, image, f.ink), image.extras().pixelated); self.stats.drawn += 1; return; } @@ -568,7 +569,9 @@ impl Renderer { } } NodeKind::Text(t) => self.draw_text(ctx, f, n, t), - NodeKind::Image(im) => self.draw_image_in(ctx, f, im, None, images::image_tint(f.doc, n, f.ink), n.extras().pixelated), + NodeKind::Image(im) => { + self.draw_image_in(ctx, f, &f.doc.shown_image(n, im), None, images::image_tint(f.doc, n, f.ink), n.extras().pixelated) + } NodeKind::SymbolInstance { symbol, xf } => { if let Some(sym) = f.doc.symbols.iter().find(|s| &s.name == symbol) { // The instance draws when the frame has room for its art's objects; a symbol diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index c5a98aebf1..73700eb8e3 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -767,6 +767,8 @@ impl Writer<'_> { } NodeKind::Text(t) => self.text_node(n, t), NodeKind::Image(im) => { + let shown = self.doc.shown_image(n, im); + let im = &*shown; if let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() && let Some(blob) = self.doc.image_blob(im) && blob.gray_source().is_some() diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index 515e556a4b..29c502cbdd 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -42,6 +42,8 @@ impl Writer<'_> { art.walk(&mut |n| { let NodeKind::Image(im) = &n.kind else { return }; let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() else { return }; + let shown = self.doc.shown_image(n, im); + let im = &*shown; if self.doc.image_blob(im).is_none_or(|blob| blob.gray_source().is_none()) { return; } @@ -176,12 +178,14 @@ impl Writer<'_> { let mut seen: HashMap<(String, u32, u32), (usize, vectorcraft_doc::ImageObject)> = HashMap::new(); art.walk(&mut |c| { if let NodeKind::Image(im) = &c.kind { + let shown = self.doc.shown_image(c, im); + let im = &*shown; if matches!(c.extras().colorize.as_deref(), Some(Paint::Solid { .. })) && self.doc.image_blob(im).is_none_or(|b| b.gray_source().is_some()) { return; } - seen.entry((im.key.clone(), im.width, im.height)).or_insert_with(|| (0, (**im).clone())).0 += 1; + seen.entry((im.key.clone(), im.width, im.height)).or_insert_with(|| (0, im.clone())).0 += 1; } }); let mut repeated: Vec<_> = seen.into_iter().filter(|(k, (n, _))| *n > 1 && !self.shared_images.contains_key(k)).collect(); diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 13e98ec4ee..362262b488 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -232,7 +232,7 @@ id = "Curvature" group = "Pen" shown_when = [ "The Curvature tool over empty canvas, or anywhere while drawing a path away from its points.", - "Elsewhere the Curvature tool borrows Pen-family cursors: PenAdd over a segment, Move over an anchor, PenContinue at an open end, PenConvert with Alt, PenClose over the first point of the path being drawn.", + "Elsewhere the Curvature tool borrows Pen-family cursors: PenAdd over a segment, Move over an anchor, PenContinue at an open end of a selected path (Alt held or not), PenConvert with Alt over any other anchor or a point of the path being drawn, PenClose over the first point of the path being drawn.", ] hotspot = "The nib's tip." look = "The Pen nib with a curve badge." diff --git a/crates/tools/src/draw2/curvature.rs b/crates/tools/src/draw2/curvature.rs index b92f8adfba..c40607ee63 100644 --- a/crates/tools/src/draw2/curvature.rs +++ b/crates/tools/src/draw2/curvature.rs @@ -1,6 +1,7 @@ //! The Curvature tool (Shift+~). //! -//! Each click adds a point and the path curves smoothly through all points. Alt-click or +//! Each click adds a point and the path curves smoothly through all points; an Alt-click adds a +//! corner point, the first point included. Alt-click or //! double-click a point toggles it between smooth and corner; drag a point to move it; click the //! first point to close; Backspace/Delete removes the last touched point; Esc/Enter ends the path. //! A rubber band shows the curve to the cursor (Enable Rubber Band for Curvature Tool). Each point @@ -8,8 +9,10 @@ //! //! It edits any selected path too, whatever drew it, keeping its shape except where edited //! (#798). A click on one of its points makes that the current point (direct-selected); a drag -//! moves it, re-curving only the two segments at it ([`curvature_move`]); Alt-click or -//! double-click toggles it between smooth and corner and Backspace/Delete removes it, the curve +//! moves it, re-curving only the two segments at it ([`curvature_move`]); double-click, or +//! Alt-click on any point but an end of an open path, toggles it between smooth and corner. An +//! Alt-click on an end of an open path makes it the current point without changing it, so the +//! next click goes on from it. Backspace/Delete removes the current point, the curve //! where it was then following the remaining points ([`curvature_remove`]). A click on //! a segment adds a smooth point there without changing the shape ([`curvature_insert`]), and a //! drag moves the new point at once. While the current point is an end of an open path, clicks go @@ -429,12 +432,16 @@ fn delete_point((id, si, ai): (NodeId, usize, usize)) -> Action { fn toggle(cx: &ToolContext, (id, si, ai): (NodeId, usize, usize)) -> Option { let sp = subpath(cx, id, si)?; let a = sp.anchors.get(ai)?; - let open_end = !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len()); - let smooth = if open_end { a.has_in() || a.has_out() } else { a.kind == AnchorKind::Smooth }; + let smooth = if open_end(sp, ai) { a.has_in() || a.has_out() } else { a.kind == AnchorKind::Smooth }; let to = if smooth { "corner" } else { "smooth" }; Some(Action::Exec("path.convertAnchor".into(), json!({"id": id.0, "subpath": si, "anchor": ai, "to": to}))) } +/// Whether anchor `ai` is an end of the open subpath `sp`. +fn open_end(sp: &SubPath, ai: usize) -> bool { + !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len()) +} + /// Snap targets for dragging anchors `anchors` of subpath `si` of `id` (the rest of the path /// pulls). fn hold_targets(snap: &mut DrawSnap, cx: &ToolContext, id: NodeId, si: usize, anchors: &[usize]) { @@ -507,12 +514,13 @@ impl CurvatureTool { } /// A press on a selected path the tool isn't drawing: on the other end of the open path going - /// on (it closes), on a point, anywhere while an end is current (the path goes on), or on a + /// on (without Alt it closes), on a point, anywhere while an end is current (the path goes on), or on a /// segment. None elsewhere: a new path starts. fn press_selected(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { let (p, tol) = (ev.pos, point_tol(cx)); let end = current_end(cx); - if let Some(e) = end.filter(|e| e.anchors >= 3 && p.distance(e.other) <= tol) { + // An Alt-click on the other end makes it current instead (below). + if let Some(e) = end.filter(|e| !ev.mods.alt && e.anchors >= 3 && p.distance(e.other) <= tol) { let how = self.how(&e); self.placed = None; let v = json!({"id": e.id.0, "subpath": e.si, "op": "close", "end": e.name(), "from": how.name()}); @@ -520,11 +528,14 @@ impl CurvatureTool { } if let Some(hit) = anchor_in(cx, editable_paths(cx), p, tol) { let mut out = vec![select_point(hit)]; + let (id, si, ai) = hit; if ev.mods.alt { - out.extend(toggle(cx, hit)); + // On an end of an open path the path goes on from it; any other point toggles. + if !subpath(cx, id, si).is_some_and(|sp| open_end(sp, ai)) { + out.extend(toggle(cx, hit)); + } return Some(out); } - let (id, si, ai) = hit; hold_targets(&mut self.snap, cx, id, si, &[ai]); self.drag = Some((Grab::Anchor(id, si, ai), p, false)); return Some(out); @@ -596,7 +607,7 @@ impl Tool for CurvatureTool { // Start a new path. self.reset(); let p = self.snap.press(cx, p, &[], None); - self.pts.push((p, false)); + self.pts.push((p, ev.mods.alt)); self.current = Some(0); vec![Action::Exec("path.curvature".into(), self.params()), Action::Notify("created".into())] } @@ -762,15 +773,14 @@ impl Tool for CurvatureTool { } let tol = point_tol(cx); let end = current_end(cx); - if end.is_some_and(|e| e.anchors >= 3 && p.distance(e.other) <= tol) { + if !m.alt && end.is_some_and(|e| e.anchors >= 3 && p.distance(e.other) <= tol) { return Cursor::PenClose; } if let Some((id, si, ai)) = anchor_in(cx, editable_paths(cx), p, tol) { - let open_end = subpath(cx, id, si).is_some_and(|sp| !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len())); - return if m.alt { - Cursor::PenConvert - } else if open_end { + return if subpath(cx, id, si).is_some_and(|sp| open_end(sp, ai)) { Cursor::PenContinue + } else if m.alt { + Cursor::PenConvert } else { Cursor::Move }; diff --git a/crates/tools/src/draw2/curvature/tests.rs b/crates/tools/src/draw2/curvature/tests.rs index 05593a3dc3..f21deec016 100644 --- a/crates/tools/src/draw2/curvature/tests.rs +++ b/crates/tools/src/draw2/curvature/tests.rs @@ -300,17 +300,69 @@ fn curvature_remove_keeps_a_corner_neighbors_handle_direction() { assert_eq!((sp.anchors[1].h_in, sp.anchors[1].h_out), (corner.h_in, corner.p)); } -/// A curved end counts as smooth for the toggle: Alt-click turns it into a corner. +/// A curved end counts as smooth for the toggle: a double-click turns it into a corner. #[test] -fn alt_click_on_a_curved_end_makes_it_a_corner() { +fn double_click_on_a_curved_end_makes_it_a_corner() { let sp = curvature_spline(&[(pt(100.0, 300.0), false), (pt(200.0, 200.0), false), (pt(300.0, 300.0), false)], false); let (d, id) = doc_with(sp); let (s, p) = (selected(id, None), paint()); let cx = quiet(&d, &s, &p); - let a = press(&mut CurvatureTool::default(), &cx, 100.0, 300.0, true); + let a = CurvatureTool::default().pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 100.0, 300.0)); assert!(a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "path.convertAnchor" && v["anchor"] == 0 && v["to"] == "corner")), "{a:?}"); } +/// An Alt-click on either end of a selected open path makes it the current point without +/// converting it, and the next click goes on from it. +#[test] +fn alt_click_on_an_open_end_goes_on_from_it() { + let (d, id) = doc_with(wave()); + let (s, p) = (selected(id, None), paint()); + let cx = quiet(&d, &s, &p); + let mut t = CurvatureTool::default(); + let alt = Mods { alt: true, ..Mods::default() }; + for (x, y, ai) in [(450.0, 60.0, 4), (0.0, 100.0, 0)] { + assert_eq!(t.cursor(&cx, pt(x, y), alt), Cursor::PenContinue); + let a = press(&mut t, &cx, x, y, true); + assert_eq!(a, vec![select_point((id, 0, ai))]); + assert!(!t.busy(), "an Alt-click does not grab the point"); + } + // As the engine does it: the Alt-clicked end is current, and the next click goes on from it. + let s = selected(id, Some(0)); + let a = press(&mut t, &quiet(&d, &s, &p), -50.0, 150.0, false); + assert!(matches!(edit_op(&a[0]), Some(("extend", v)) if v["end"] == "start" && v["from"] == "keep"), "{a:?}"); + // With the start current, an Alt-click on the other end makes that end current; a plain click + // there closes the path. + let cx = quiet(&d, &s, &p); + assert_eq!(t.cursor(&cx, pt(450.0, 60.0), alt), Cursor::PenContinue); + assert_eq!(press(&mut t, &cx, 450.0, 60.0, true), vec![select_point((id, 0, 4))]); + assert_eq!(t.cursor(&cx, pt(450.0, 60.0), Mods::default()), Cursor::PenClose); + assert!(matches!(edit_op(&press(&mut t, &cx, 450.0, 60.0, false)[0]), Some(("close", v)) if v["end"] == "start")); + // A closed path has no ends: an Alt-click on its first point converts it. + let mut closed = wave(); + closed.closed = true; + let (d, id) = doc_with(closed); + let s = selected(id, None); + let cx = quiet(&d, &s, &p); + assert_eq!(t.cursor(&cx, pt(0.0, 100.0), alt), Cursor::PenConvert); + let a = press(&mut t, &cx, 0.0, 100.0, true); + assert!(a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "path.convertAnchor" && v["anchor"] == 0)), "{a:?}"); +} + +/// An Alt-click that starts a path places a corner point, as later Alt-clicks do; a plain click +/// places a smooth one. +#[test] +fn alt_click_starts_a_path_with_a_corner() { + let d = Document::new(800.0, 600.0); + let (s, p) = (Selection::default(), paint()); + let cx = quiet(&d, &s, &p); + for alt in [true, false] { + let mut t = CurvatureTool::default(); + let a = press(&mut t, &cx, 100.0, 120.0, alt); + assert!(matches!(&a[0], Action::Exec(c, v) if c == "path.curvature" && v["points"][0]["corner"] == alt), "{a:?}"); + assert_eq!(t.pts, vec![(pt(100.0, 120.0), alt)]); + } +} + /// A document with one path, `sp`. fn doc_with(sp: SubPath) -> (Document, NodeId) { let mut d = Document::new(800.0, 600.0); diff --git a/crates/ui-egui/src/addons/image.rs b/crates/ui-egui/src/addons/image.rs index f8aa72b8a1..9388b104e2 100644 --- a/crates/ui-egui/src/addons/image.rs +++ b/crates/ui-egui/src/addons/image.rs @@ -1,6 +1,7 @@ //! Image Tools in the interface: its submenu (Object › Plug-ins › Image Tools). Remove Background's //! menu item opens the generic command dialog (`ui.paramDialog`) on its options, with a Preview -//! (`dialogs::command`). +//! (`dialogs::command`). Color Mask's opens the same dialog on the selected image's mask settings +//! (the command's report, see `menus::invoke`), or the defaults for an image without one. use serde_json::json; @@ -8,18 +9,29 @@ use crate::menus::Item; /// Remove Background's command. pub const REMOVE_BACKGROUND: &str = "addon.image.removeBackground"; -/// Remove Background › Background: what the command's `background` takes, by name. +/// Color Mask's command. +pub const COLOR_MASK: &str = "addon.image.colorMask"; +/// Remove Color Mask's command. +pub const REMOVE_COLOR_MASK: &str = "addon.image.removeColorMask"; +/// Apply Color Mask's command. +pub const APPLY_COLOR_MASK: &str = "addon.image.applyColorMask"; +/// Remove Background and Color Mask › Background: what the commands' `background` takes, by name. pub const BACKGROUNDS: &[(&str, &str)] = &[("Edge Color", "edges"), ("Corner Color", "corners"), ("Picked Colors", "colors")]; -/// Remove Background › Match: what the command's `match` takes, by name. +/// Remove Background and Color Mask › Match: what the commands' `match` takes, by name. pub const MATCHES: &[(&str, &str)] = &[("Distance", "distance"), ("Each Channel", "channels")]; /// Object › Plug-ins › Image Tools. pub fn menu() -> Vec { - vec![Item::Cmd( - "Remove Background…", - REMOVE_BACKGROUND, - json!({"background": "edges", "colors": "#ffffff", "contiguous": true, "match": "distance", "tolerance": 10, "softness": 10}), - )] + vec![ + Item::Cmd( + "Remove Background…", + REMOVE_BACKGROUND, + json!({"background": "edges", "colors": "#ffffff", "contiguous": true, "match": "distance", "tolerance": 10, "softness": 10}), + ), + Item::Cmd("Color Mask…", COLOR_MASK, json!({})), + Item::Cmd("Remove Color Mask", REMOVE_COLOR_MASK, json!({})), + Item::Cmd("Apply Color Mask", APPLY_COLOR_MASK, json!({})), + ] } #[cfg(test)] diff --git a/crates/ui-egui/src/addons/image/tests.rs b/crates/ui-egui/src/addons/image/tests.rs index 64563e611b..67b5b48ec5 100644 --- a/crates/ui-egui/src/addons/image/tests.rs +++ b/crates/ui-egui/src/addons/image/tests.rs @@ -41,13 +41,75 @@ fn alphas(app: &VectorcraftApp) -> [u8; 3] { } fn open(app: &mut VectorcraftApp) { - let entries = menus::menu_entries(app); - let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Image Tools"] && e.label == "Remove Background…").unwrap(); - assert!(item.enabled); + click(app, "Remove Background…"); +} + +/// Choose Object › Plug-ins › Image Tools › `label`, which must be enabled. +fn click(app: &mut VectorcraftApp, label: &str) { + let item = menu_item(app, label); + assert!(item.enabled, "{label} enabled"); let (id, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); menus::invoke(app, &id, p); } +fn menu_item(app: &VectorcraftApp, label: &str) -> menus::MenuEntry { + menus::menu_entries(app).into_iter().find(|e| e.path == ["Object", "Plug-ins", "Image Tools"] && e.label == label).unwrap() +} + +/// The selected image's color mask, if it has one. +fn mask(app: &VectorcraftApp) -> Option { + let st = app.session.doc().unwrap(); + st.selection.objects.first().and_then(|id| st.doc.node(*id)).and_then(vectorcraft_doc::Document::color_mask_of).cloned() +} + +/// The alpha of the selected image's masked pixels at the corner, on the ring and in the block +/// (all 255 without a mask). +fn masked_alphas(app: &VectorcraftApp) -> [u8; 3] { + let Some(m) = mask(app) else { return [255; 3] }; + let px = image::load_from_memory(&app.session.doc().unwrap().doc.images[&m.key].bytes).unwrap().to_rgba8(); + [(0, 0), (1, 1), (4, 4)].map(|(x, y)| px.get_pixel(x, y).0[3]) +} + +/// Object › Plug-ins › Image Tools › Color Mask… opens the command dialog on the defaults, previews +/// a mask while the image's pixels stay, and keeps it on OK as one step; opened again it shows the +/// image's mask settings. Remove Color Mask and Apply Color Mask are enabled only for an image +/// with a mask. +#[test] +fn color_mask_previews_keeps_its_settings_and_comes_off() { + let mut app = app(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let (start, n) = (image(&app), steps(&app)); + assert!(!menu_item(&app, "Remove Color Mask").enabled && !menu_item(&app, "Apply Color Mask").enabled); + + click(&mut app, "Color Mask…"); + let d = app.ui.dialog.as_ref().expect("a dialog opens"); + assert_eq!((d.str("__command"), d.str("__label")), (super::COLOR_MASK.to_string(), "Color Mask".to_string())); + assert_eq!((d.str("background"), d.f64("tolerance", -1.0), d.bool("preview")), ("edges".to_string(), 10.0, false)); + assert!(!d.fields.contains_key("masked")); + let shown = show(&mut app); + for s in ["Color Mask", "Edge Color", "Contiguous", "Match", "Tolerance", "Softness", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + set(&mut app, "preview", json!(true)); + set(&mut app, "tolerance", json!(20)); + show(&mut app); + assert_eq!(masked_alphas(&app), [0, 0, 255], "the preview hides the white and the ring"); + assert_eq!(image(&app), start, "the image's pixels stay"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), image(&app)), (n + 1, start.clone()), "one undo step; the pixels as they were"); + assert_eq!(mask(&app).map(|m| m.tolerance), Some(20.0)); + + // Opened again: the image's mask settings. + click(&mut app, "Color Mask…"); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("tolerance", -1.0), 20.0); + crate::dialogs::cancel(&mut app); + assert_eq!(steps(&app), n + 1); + + assert!(menu_item(&app, "Apply Color Mask").enabled); + click(&mut app, "Remove Color Mask"); + assert_eq!((mask(&app), image(&app), steps(&app)), (None, start, n + 2)); +} + fn show(app: &mut VectorcraftApp) -> String { painted_text(app, |app, ui| crate::dialogs::show(app, ui.ctx())) } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bc586767c2..67e67ac444 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -577,10 +577,10 @@ impl VectorcraftApp { chrome::hint_bar(self, ui); } if (self.ui.screen_mode >= 3 || (!self.ui.status_bar && !self.ui.help_bar)) - && !(self.ui.control_bar && self.ui.control_bar_bottom && self.ui.screen_mode < 2) + && !(self.ui.control_bar && self.ui.control_bar_bottom && !self.ui.control_bar_floating && self.ui.screen_mode < 2) { // Keeps the previous frame's value valid for menus drawn above, before the bars. A - // Control bar docked at the bottom has set it to the bar's top. + // Control bar docked at the bottom has set it to the bar's top; a floating one sets none. widgets::set_menu_floor(&ctx, ctx.content_rect().bottom()); } if self.ui.toolbar && self.ui.screen_mode < 3 { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 513aa54df4..855d542d08 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -18,9 +18,12 @@ mod hints; mod status_bar; mod tabs; +pub use control_bar::{ + AnchorControls, CONTROL_BAR_EDGES, CONTROL_BAR_GROUPS, anchor_buttons, anchor_controls, control_bar, control_bar_moving, control_bar_placement, + read_hidden_groups, +}; #[cfg(test)] -use control_bar::ISOLATION_BUTTON; -pub use control_bar::{AnchorControls, CONTROL_BAR_EDGES, CONTROL_BAR_GROUPS, anchor_buttons, anchor_controls, control_bar, read_hidden_groups}; +use control_bar::{CONTROL_BAR_FLOAT_AT, ISOLATION_BUTTON}; #[cfg(test)] use hints::hint_segments; pub use hints::{hint_bar, hint_strings}; diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 3315387d4f..9b862cf636 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -303,9 +303,18 @@ fn artboard_align_group(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// The edges of the window the Control bar docks to (`window.control.dock {edge}`): the top, then -/// the bottom. -pub const CONTROL_BAR_EDGES: [&str; 2] = ["top", "bottom"]; +/// The places the Control bar goes to (`window.control.dock {edge}`): docked to the top or the +/// bottom of the window, or floating over it. +pub const CONTROL_BAR_EDGES: [&str; 3] = ["top", "bottom", "float"]; + +/// Where `window.control.dock {edge: "float"}` floats the Control bar the first time: its top-left +/// corner in window points. +pub const CONTROL_BAR_FLOAT_AT: [f32; 2] = [60.0, 80.0]; + +/// The entry of [`CONTROL_BAR_EDGES`] the Control bar is at in `ui`. +pub fn control_bar_placement(ui: &crate::state::UiState) -> &'static str { + CONTROL_BAR_EDGES[if ui.control_bar_floating { 2 } else { usize::from(ui.control_bar_bottom) }] +} /// The groups of the Control bar's options that its panel menu turns on or off /// (`window.control.options {group, visible?}`), by id, in the menu's order. Every group is on @@ -370,6 +379,76 @@ const MENU_BUTTON: f32 = 16.0; /// The height of the band drawn along the edge of the window that a gripper drag docks the bar to. const DOCK_BAND: f32 = 4.0; +/// The Control bar's height, docked or floating. +const HEIGHT: f32 = 34.0; + +/// The Control bar's inner margin left and right, around its gripper and its panel menu button. +const MARGIN: f32 = 10.0; + +/// The width the floating Control bar takes in a window wide enough for it. +const FLOAT_WIDTH: f32 = 800.0; + +/// How near the edge the bar docks to a gripper drag is released for the bar to dock there; a +/// release farther from both edges floats the bar. +const DOCK_ZONE: f32 = 24.0; + +/// The key of a gripper drag in progress: where the pointer holds the bar from its top-left +/// corner, and the gripper's widget id. +fn move_id() -> egui::Id { + egui::Id::unique("control_bar_gripper_move") +} + +/// Is the Control bar's gripper being dragged, the frame that releases it included? An Escape then +/// cancels the drag, and nothing else. A drag left over from a bar hidden while the button was held +/// ends with the button. +pub fn control_bar_moving(ctx: &egui::Context) -> bool { + let Some((_, gripper)) = ctx.data(|d| d.get_temp::<(egui::Vec2, egui::Id)>(move_id())) else { return false }; + ctx.input(|i| i.pointer.primary_down()) || ctx.drag_stopped_id() == Some(gripper) +} + +/// Where a gripper release puts the Control bar. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Release { + /// Docked to the bottom (true) or the top (false). + Edge(bool), + /// Floating, its top-left corner here. + Float(egui::Pos2), +} + +/// The width of the floating Control bar in a window whose room below the menu bar is `room`. +fn float_width(room: egui::Rect) -> f32 { + FLOAT_WIDTH.min(room.width()).max(2.0 * MARGIN + MENU_BUTTON + 6.0) +} + +/// The floating Control bar's rect for its saved corner `pos`, kept inside `room`, the window below +/// the menu bar, so its gripper and panel menu stay in reach. +fn float_rect(pos: Option<[f32; 2]>, room: egui::Rect) -> egui::Rect { + let size = vec2(float_width(room), HEIGHT); + egui::Rect::from_min_size(crate::tools_float::clamp(pos.unwrap_or(CONTROL_BAR_FLOAT_AT), size, room), size) +} + +/// Where a gripper drag released at `at` puts the bar, held at `grab` from its top-left corner: +/// within [`DOCK_ZONE`] of the top or the bottom of `room` (the window below the menu bar) docked +/// there, farther from both floating under the pointer. In a window too short for the two zones +/// and a floating bar between them, it docks at the nearer edge. A release outside `window` puts +/// it nowhere, and the bar stays where it was. +fn release_at(at: egui::Pos2, grab: egui::Vec2, room: egui::Rect, window: egui::Rect) -> Option { + if !window.contains(at) || !at.x.is_finite() || !at.y.is_finite() { + return None; + } + if room.height() < 2.0 * DOCK_ZONE + HEIGHT { + return Some(Release::Edge(at.y > room.center().y)); + } + Some(if at.y < room.top() + DOCK_ZONE { + Release::Edge(false) + } else if at.y > room.bottom() - DOCK_ZONE { + Release::Edge(true) + } else { + let corner = at - grab; + Release::Float(float_rect(Some([corner.x, corner.y]), room).min) + }) +} + /// Docks the Control bar to `edge` of [`CONTROL_BAR_EDGES`], through its command. fn dock(app: &mut VectorcraftApp, edge: &str) { crate::menus::invoke(app, "window.control.dock", json!({ "edge": edge })); @@ -377,7 +456,8 @@ fn dock(app: &mut VectorcraftApp, edge: &str) { /// The Control bar's panel menu: an item for each group of [`CONTROL_BAR_GROUPS`], checked while /// the group is on, which turns it on or off; then Dock to Top and Dock to Bottom, the edge the bar -/// is docked to checked. In a window too short for every item, the list scrolls. +/// is docked to checked, and neither while it floats. In a window too short for every item, the +/// list scrolls. fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { let resp = crate::panels::menu_button(ui, "control", rect); egui::Popup::menu(&resp).show(|ui| { @@ -390,7 +470,7 @@ fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { } ui.separator(); for (i, label) in [tl!("Dock to Top"), tl!("Dock to Bottom")].into_iter().enumerate() { - if widgets::menu_item(ui, label, true, usize::from(app.ui.control_bar_bottom) == i) { + if widgets::menu_item(ui, label, true, control_bar_placement(&app.ui) == CONTROL_BAR_EDGES[i]) { dock(app, CONTROL_BAR_EDGES[i]); } } @@ -453,170 +533,227 @@ fn opacity_and_style(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, opacity: } } -/// The Control bar's gripper. Dragging it shows a band along the top or the bottom edge of the -/// window, whichever the pointer is nearer, and docks the bar there on release. -fn gripper(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens) { +/// The Control bar's gripper, at the left end of the bar `bar`. Dragging it shows where a release +/// puts the bar ([`release_at`] in `dock_room`, the window below the menu bar): a band along the +/// edge it docks to, or the outline of the bar floating under the pointer. The bar stays where it is +/// until the release. Escape, or the window losing the focus, cancels the drag, and a release +/// outside the window leaves the bar where it was. +fn gripper(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, dock_room: egui::Rect) { let (g, resp) = ui.allocate_exact_size(vec2(6.0, 20.0), Sense::drag()); for i in 0..5 { ui.painter().circle_filled(g.center_top() + vec2(0.0, 2.0 + i as f32 * 4.0), 0.9, t.text_disabled); } let resp = resp.on_hover_cursor(egui::CursorIcon::Grab); - if !resp.dragged() && !resp.drag_stopped() { + let ctx = ui.ctx().clone(); + if resp.drag_started() + && let Some(press) = ctx.input(|i| i.pointer.press_origin()) + { + ctx.data_mut(|d| d.insert_temp(move_id(), (press - bar.min, resp.id))); + } + let Some((grab, _)) = ctx.data(|d| d.get_temp::<(egui::Vec2, egui::Id)>(move_id())) else { return }; + let canceled = ctx.input(|i| i.key_pressed(egui::Key::Escape) || !i.focused); + if canceled || !(resp.dragged() || resp.drag_stopped()) { + ctx.data_mut(|d| d.remove::<(egui::Vec2, egui::Id)>(move_id())); return; } - let Some(pos) = resp.interact_pointer_pos().or_else(|| ui.ctx().pointer_latest_pos()) else { return }; - let window = ui.ctx().content_rect(); - let bottom = pos.y > window.center().y; + let window = ctx.content_rect(); + let target = ctx.input(|i| i.pointer.latest_pos()).and_then(|at| release_at(at, grab, dock_room, window)); if resp.drag_stopped() { - if bottom != app.ui.control_bar_bottom { - dock(app, CONTROL_BAR_EDGES[usize::from(bottom)]); + ctx.data_mut(|d| d.remove::<(egui::Vec2, egui::Id)>(move_id())); + match target { + Some(Release::Edge(bottom)) if app.ui.control_bar_floating || bottom != app.ui.control_bar_bottom => { + dock(app, CONTROL_BAR_EDGES[usize::from(bottom)]); + } + Some(Release::Float(at)) => { + app.ui.control_bar_float_pos = Some([at.x, at.y]); + if !app.ui.control_bar_floating { + dock(app, CONTROL_BAR_EDGES[2]); + } + } + _ => {} } return; } - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - let band = if bottom { - egui::Rect::from_min_max(egui::pos2(window.left(), window.bottom() - DOCK_BAND), window.max) - } else { - egui::Rect::from_min_max(window.min, egui::pos2(window.right(), window.top() + DOCK_BAND)) - }; - let layer = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("control_bar_dock_band")); - ui.ctx().layer_painter(layer).rect_filled(band, 0.0, t.accent); + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("control_bar_dock_band"))); + match target { + Some(Release::Edge(bottom)) => { + let band = if bottom { + egui::Rect::from_min_max(egui::pos2(dock_room.left(), dock_room.bottom() - DOCK_BAND), dock_room.max) + } else { + egui::Rect::from_min_max(dock_room.min, egui::pos2(dock_room.right(), dock_room.top() + DOCK_BAND)) + }; + painter.rect_filled(band, 0.0, t.accent); + } + Some(Release::Float(at)) => { + let outline = egui::Rect::from_min_size(at, vec2(float_width(dock_room), HEIGHT)); + painter.rect_stroke(outline, 0.0, Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); + } + None => {} + } } /// The Control bar (Window → Control), context-sensitive like Illustrator's, docked to the top or -/// the bottom of the window. +/// the bottom of the window, or floating over the window below the menu bar, where it takes no room +/// from the canvas. A floating bar is [`FLOAT_WIDTH`] wide, or as wide as the window when that is +/// narrower, and is kept inside the window when the window shrinks. pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); + // The window below the menu bar: where the bar docks at the top, and where it floats. + let dock_room = ui.available_rect_before_wrap(); + let frame = egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin::symmetric(10, 0)).stroke(Stroke::new(1.0, t.border)); + if app.ui.control_bar_floating { + let bar = float_rect(app.ui.control_bar_float_pos, dock_room); + let ctx = ui.ctx().clone(); + let area = egui::Area::new(egui::Id::unique("control_bar_floating")).order(egui::Order::Middle).fixed_pos(bar.min).constrain(false); + area.show(&ctx, |ui| { + frame.show(ui, |ui| { + // Inside the frame's margins and its 1-point border. + ui.set_width(bar.width() - 2.0 * MARGIN - 2.0); + ui.set_height(HEIGHT - 2.0); + contents(app, ui, &t, bar, dock_room, true); + }); + }); + return; + } let bottom = app.ui.control_bar_bottom; let panel = if bottom { egui::Panel::bottom("control_bar") } else { egui::Panel::top("control_bar") }; - let bar = panel - .exact_size(34.0) - .frame(egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin::symmetric(10, 0)).stroke(Stroke::new(1.0, t.border))) - .show(ui, |ui| { - // The panel menu button takes the right end, and the controls trim to the room left of it: - // they are laid out in that room, so every room check below leaves the button's width. - let full = ui.max_rect(); - let menu = egui::Rect::from_center_size(egui::pos2(full.right() - MENU_BUTTON / 2.0, full.center().y), vec2(MENU_BUTTON, MENU_BUTTON)); - let room = egui::Rect::from_min_max(full.min, egui::pos2(menu.left() - ui.spacing().item_spacing.x, full.bottom())); - let layout = egui::Layout::left_to_right(egui::Align::Center); - let controls = ui.scope_builder(egui::UiBuilder::new().max_rect(room).layout(layout), |ui| { - gripper(app, ui, &t); - if app.session.active().is_none() { - ui.label(egui::RichText::new(tl!("No Document")).color(t.text_dim)); - return; - } - // The Artboard tool's controls fill the narrowest window, so they keep it to themselves there. - if group_on(app, "snapping") && (app.session.tool_id() != "artboard" || ui.available_width() >= ARTBOARD_SNAPPING_WIDTH) { - snapping_menu(app, ui); - } - let Some(st) = app.session.active() else { return }; - let sel = st.selection.objects.clone(); - let units = app.session.general_unit(); - let first = sel.first().and_then(|id| st.doc.node(*id)); - let anchors = anchor_controls(app); - let label = match first { - _ if app.session.tool_id() == "artboard" => tl!("Artboard"), - Some(_) if sel.len() == 1 && anchors != AnchorControls::None => { - tl!("Anchor Point") - } - Some(vectorcraft_doc::Node { kind: NodeKind::Image(im), .. }) if sel.len() == 1 => { - if im.link.is_some() { - tl!("Linked File") - } else { - tl!("Embedded") - } - } - Some(n) if sel.len() == 1 && crate::panels::image_trace::is_trace(n) => { - tl!("Image Tracing") - } - _ => tl!(crate::panels::appearance::object_label(app)), - }; - let has_first = first.is_some(); - ui.label(egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text)); - // With the Artboard tool in use, the bar shows the active artboard's controls in place - // of the object controls. - let (artboard_options, transform) = (group_on(app, "artboardOptions"), group_on(app, "transform")); - if crate::panels::artboards::control_bar(app, ui, artboard_options, transform) { - artboard_align_group(app, ui); - return; - } - if anchors != AnchorControls::None && group_on(app, "anchors") { - anchor_buttons(app, ui, anchors); - } - let object_options = group_on(app, "objectOptions"); - if object_options { - isolation_button(app, ui); - } - ui.add_space(6.0); - // An image or an Image Trace object shows its own controls in place of Fill and Stroke, - // and leaves Fill and Stroke out while the Image Options group is off too. - let image = if group_on(app, "imageOptions") { - crate::place::control_bar_details(app, ui) || crate::panels::image_trace::control_bar(app, ui) - } else { - crate::place::selected_image_info(app).is_some() || crate::panels::image_trace::selected_trace(app).is_some() - }; - if group_on(app, "toolOptions") { - crate::toolbar::control_bar_options(app, ui); - } - if object_options { - crate::dialogs::envelope::control_bar(app, ui); - crate::panels::symbols::control_bar(app, ui); - } - let opacity = if has_first { crate::panels::current_transparency(app).map_or(1.0, |t| t.0) } else { 1.0 }; - if !image && group_on(app, "fillStroke") { - fill_and_stroke(app, ui); - } - opacity_and_style(app, ui, &t, opacity, !sel.is_empty()); - if group_on(app, "character") { - crate::panels::character::control_bar(app, ui); - } - if !groups_before_transform(app, ui, sel.len()) { - return; - } - // The Transform link opens the whole Transform panel (reference point, rotate, - // shear, options) in a popover; X/Y/W/H follow inline while the bar has room. - crate::panels::transform::link(app, ui); - // The bounding box, rotated with rotated objects: its centre and its own sides. - if let Some(b) = app.selection_box() - && ui.available_width() >= inline_transform_width(ui, &t) - { - let c = b.center(); - let origin = app.ruler_origin(); - let link = crate::panels::transform::proportional(app, ui); - let copy = crate::panels::transform::alt_enter_copies(app, ui); - let values = [(c.x, origin.x), (c.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)]; - // The W/H link sits between W and H, but is made after H so Tab goes from W - // straight to H and finds the link after it. - let mut link_room = None; - for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) { - if k == "height" { - link_room = Some(crate::panels::transform::constrain_link_room(ui)); - } - widgets::field_label(ui, inline_label(&t, lbl)); - let (id, shown) = (("cb", k), Some(v - offset)); - let set = if matches!(k, "width" | "height") { - widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH) - } else { - widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH) - }; - if let Some(nv) = set { - app.run("object.setBounds", json!({k: nv + offset, "reference": 4, "proportional": link, "copy": copy})).ok(); - } - } - if let Some(room) = link_room { - let id = ui.scope_id().with("cb-constrain-link"); - crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click())); - } - } - }); - // Controls that keep their size can still run into the button's room in a narrow window; - // the button is left out then. - if controls.response.rect.right() <= menu.left() { - panel_menu(app, ui, menu); - } - }); + let bar = panel.exact_size(HEIGHT).frame(frame).show(ui, |ui| { + // Out to the frame's 1-point border. + let outer = ui.max_rect().expand2(vec2(MARGIN + 1.0, 1.0)); + contents(app, ui, &t, outer, dock_room, false); + }); // Docked at the bottom, the bar is a bottom bar that menus stop above. if bottom { widgets::set_menu_floor(ui.ctx(), bar.response.rect.top()); } } + +/// The Control bar's gripper, controls and panel menu, in the bar `bar`. A `floating` bar clips its +/// controls to the room left of the panel menu button, and always shows the button. +fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, dock_room: egui::Rect, floating: bool) { + // The panel menu button takes the right end, and the controls trim to the room left of it: + // they are laid out in that room, so every room check below leaves the button's width. + let full = ui.max_rect(); + let menu = egui::Rect::from_center_size(egui::pos2(full.right() - MENU_BUTTON / 2.0, full.center().y), vec2(MENU_BUTTON, MENU_BUTTON)); + let room = egui::Rect::from_min_max(full.min, egui::pos2(menu.left() - ui.spacing().item_spacing.x, full.bottom())); + let layout = egui::Layout::left_to_right(egui::Align::Center); + let controls = ui.scope_builder(egui::UiBuilder::new().max_rect(room).layout(layout), |ui| { + if floating { + ui.set_clip_rect(room.intersect(ui.clip_rect())); + } + gripper(app, ui, t, bar, dock_room); + if app.session.active().is_none() { + ui.label(egui::RichText::new(tl!("No Document")).color(t.text_dim)); + return; + } + // The Artboard tool's controls fill the narrowest window, so they keep it to themselves there. + if group_on(app, "snapping") && (app.session.tool_id() != "artboard" || ui.available_width() >= ARTBOARD_SNAPPING_WIDTH) { + snapping_menu(app, ui); + } + let Some(st) = app.session.active() else { return }; + let sel = st.selection.objects.clone(); + let units = app.session.general_unit(); + let first = sel.first().and_then(|id| st.doc.node(*id)); + let anchors = anchor_controls(app); + let label = match first { + _ if app.session.tool_id() == "artboard" => tl!("Artboard"), + Some(_) if sel.len() == 1 && anchors != AnchorControls::None => { + tl!("Anchor Point") + } + Some(vectorcraft_doc::Node { kind: NodeKind::Image(im), .. }) if sel.len() == 1 => { + if im.link.is_some() { + tl!("Linked File") + } else { + tl!("Embedded") + } + } + Some(n) if sel.len() == 1 && crate::panels::image_trace::is_trace(n) => { + tl!("Image Tracing") + } + _ => tl!(crate::panels::appearance::object_label(app)), + }; + let has_first = first.is_some(); + ui.label(egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text)); + // With the Artboard tool in use, the bar shows the active artboard's controls in place + // of the object controls. + let (artboard_options, transform) = (group_on(app, "artboardOptions"), group_on(app, "transform")); + if crate::panels::artboards::control_bar(app, ui, artboard_options, transform) { + artboard_align_group(app, ui); + return; + } + if anchors != AnchorControls::None && group_on(app, "anchors") { + anchor_buttons(app, ui, anchors); + } + let object_options = group_on(app, "objectOptions"); + if object_options { + isolation_button(app, ui); + } + ui.add_space(6.0); + // An image or an Image Trace object shows its own controls in place of Fill and Stroke, + // and leaves Fill and Stroke out while the Image Options group is off too. + let image = if group_on(app, "imageOptions") { + crate::place::control_bar_details(app, ui) || crate::panels::image_trace::control_bar(app, ui) + } else { + crate::place::selected_image_info(app).is_some() || crate::panels::image_trace::selected_trace(app).is_some() + }; + if group_on(app, "toolOptions") { + crate::toolbar::control_bar_options(app, ui); + } + if object_options { + crate::dialogs::envelope::control_bar(app, ui); + crate::panels::symbols::control_bar(app, ui); + } + let opacity = if has_first { crate::panels::current_transparency(app).map_or(1.0, |t| t.0) } else { 1.0 }; + if !image && group_on(app, "fillStroke") { + fill_and_stroke(app, ui); + } + opacity_and_style(app, ui, t, opacity, !sel.is_empty()); + if group_on(app, "character") { + crate::panels::character::control_bar(app, ui); + } + if !groups_before_transform(app, ui, sel.len()) { + return; + } + // The Transform link opens the whole Transform panel (reference point, rotate, + // shear, options) in a popover; X/Y/W/H follow inline while the bar has room. + crate::panels::transform::link(app, ui); + // The bounding box, rotated with rotated objects: its centre and its own sides. + if let Some(b) = app.selection_box() + && ui.available_width() >= inline_transform_width(ui, t) + { + let c = b.center(); + let origin = app.ruler_origin(); + let link = crate::panels::transform::proportional(app, ui); + let copy = crate::panels::transform::alt_enter_copies(app, ui); + let values = [(c.x, origin.x), (c.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)]; + // The W/H link sits between W and H, but is made after H so Tab goes from W + // straight to H and finds the link after it. + let mut link_room = None; + for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) { + if k == "height" { + link_room = Some(crate::panels::transform::constrain_link_room(ui)); + } + widgets::field_label(ui, inline_label(t, lbl)); + let (id, shown) = (("cb", k), Some(v - offset)); + let set = if matches!(k, "width" | "height") { + widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH) + } else { + widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH) + }; + if let Some(nv) = set { + app.run("object.setBounds", json!({k: nv + offset, "reference": 4, "proportional": link, "copy": copy})).ok(); + } + } + if let Some(room) = link_room { + let id = ui.scope_id().with("cb-constrain-link"); + crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click())); + } + } + }); + // Controls that keep their size can still run into the button's room in a narrow window; + // the button is left out then. A floating bar clips them, so its button always shows. + if floating || controls.response.rect.right() <= menu.left() { + panel_menu(app, ui, menu); + } +} diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index bc06c8687e..626ff8c66e 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -2354,49 +2354,279 @@ fn the_control_bar_panel_menu_scrolls_in_a_short_window() { assert!(app.ui.control_bar_bottom, "Dock to Bottom docks the bar at the bottom"); } -/// Dragging the Control bar's gripper docks the bar at the edge of the window the pointer is -/// released nearer; a drag released nearer the edge it is at leaves it there. +/// The gripper of a Control bar docked at the top or the bottom of [`DOCK_SCREEN`]: the bar's first +/// item, inside its 10-point margin, centered in the 34-point bar. +fn docked_grip(bottom: bool) -> egui::Pos2 { + egui::pos2(13.0, if bottom { DOCK_SCREEN.bottom() - 17.0 } else { 17.0 }) +} + +/// The gripper of the Control bar floating with its top-left corner at `pos`: inside its 1-point +/// border and 10-point margin. +fn floating_grip(pos: [f32; 2]) -> egui::Pos2 { + egui::pos2(pos[0] + 14.0, pos[1] + 17.0) +} + +/// A drag of the Control bar's gripper from `from` to `to` in window `screen`, with `during` sent +/// at the last move before the release, released at `to`. +fn drag_gripper_in( + app: &mut crate::VectorcraftApp, + ctx: &egui::Context, + screen: egui::Rect, + from: egui::Pos2, + to: egui::Pos2, + during: Vec, +) { + // A bar that has just started floating takes a frame to show. + control_bar_frame_in(app, ctx, screen, vec![]); + control_bar_frame_in(app, ctx, screen, vec![]); + control_bar_frame_in(app, ctx, screen, vec![egui::Event::PointerMoved(from), press_at(from, true)]); + for k in 1..=4 { + control_bar_frame_in(app, ctx, screen, vec![egui::Event::PointerMoved(from.lerp(to, k as f32 / 4.0))]); + } + control_bar_frame_in(app, ctx, screen, during); + control_bar_frame_in(app, ctx, screen, vec![press_at(to, false)]); + control_bar_frame_in(app, ctx, screen, vec![]); +} + +/// [`drag_gripper_in`] in [`DOCK_SCREEN`] with nothing sent during the drag. +fn drag_gripper(app: &mut crate::VectorcraftApp, ctx: &egui::Context, from: egui::Pos2, to: egui::Pos2) { + drag_gripper_in(app, ctx, DOCK_SCREEN, from, to, vec![]); +} + +/// Dragging the Control bar's gripper and releasing it within 24 points of the top or the bottom of +/// the window docks the bar at that edge, the edge it is at included. #[test] fn dragging_the_control_bar_gripper_docks_it_at_the_nearer_edge() { let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); - // The gripper is the bar's first item, inside its 10-point margin, centered in the 34-point bar. - let grip = |bottom: bool| egui::pos2(13.0, if bottom { DOCK_SCREEN.bottom() - 17.0 } else { 17.0 }); - let drag = |app: &mut crate::VectorcraftApp, from: egui::Pos2, to: egui::Pos2| { - control_bar_frame(app, &ctx, vec![]); - control_bar_frame(app, &ctx, vec![egui::Event::PointerMoved(from), press_at(from, true)]); - for k in 1..=4 { - control_bar_frame(app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, k as f32 / 4.0))]); - } - control_bar_frame(app, &ctx, vec![press_at(to, false)]); - }; - drag(&mut app, grip(false), egui::pos2(400.0, 200.0)); - assert!(app.ui.control_bar_bottom, "released nearer the bottom: docked at the bottom"); - drag(&mut app, grip(true), egui::pos2(400.0, 160.0)); - assert!(app.ui.control_bar_bottom, "released nearer the bottom again: still at the bottom"); - drag(&mut app, grip(true), egui::pos2(400.0, 120.0)); - assert!(!app.ui.control_bar_bottom, "released nearer the top: docked at the top"); - drag(&mut app, grip(false), egui::pos2(400.0, 140.0)); - assert!(!app.ui.control_bar_bottom, "released nearer the top again: still at the top"); + drag_gripper(&mut app, &ctx, docked_grip(false), egui::pos2(400.0, 290.0)); + assert!(app.ui.control_bar_bottom && !app.ui.control_bar_floating, "released at the bottom: docked at the bottom"); + drag_gripper(&mut app, &ctx, docked_grip(true), egui::pos2(400.0, 280.0)); + assert!(app.ui.control_bar_bottom && !app.ui.control_bar_floating, "released at the bottom again: still at the bottom"); + drag_gripper(&mut app, &ctx, docked_grip(true), egui::pos2(400.0, 10.0)); + assert!(!app.ui.control_bar_bottom && !app.ui.control_bar_floating, "released at the top: docked at the top"); + drag_gripper(&mut app, &ctx, docked_grip(false), egui::pos2(400.0, 20.0)); + assert!(!app.ui.control_bar_bottom && !app.ui.control_bar_floating, "released at the top again: still at the top"); } -/// `window.control.dock {edge}` docks the Control bar to the top or the bottom of the window, and -/// the panel menu checks the edge in use; another edge, or none, is an error and changes nothing. +/// Dragging the docked Control bar's gripper away from both edges and releasing it there floats +/// the bar under the pointer, held where the gripper was grabbed: 800 points wide, over the window, +/// with its gripper and panel menu. The bar stays docked until the release. #[test] -fn the_control_bar_dock_command_takes_top_or_bottom() { +fn dragging_the_control_bar_gripper_away_from_both_edges_floats_it() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let from = docked_grip(false); + control_bar_frame(&mut app, &ctx, vec![]); + control_bar_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), press_at(from, true)]); + let to = egui::pos2(400.0, 150.0); + for k in 1..=4 { + control_bar_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, k as f32 / 4.0))]); + } + assert!(!app.ui.control_bar_floating && super::control_bar_moving(&ctx), "still docked while the drag goes on"); + control_bar_frame(&mut app, &ctx, vec![press_at(to, false)]); + assert!(app.ui.control_bar_floating && !super::control_bar_moving(&ctx), "released away from both edges: floating"); + assert_eq!(crate::menus::checked(&app, "window.control.dock", &json!({"edge": "float"})), Some(true)); + assert_eq!(app.ui.control_bar_float_pos, Some([to.x - from.x, to.y - from.y]), "held where the gripper was grabbed"); + control_bar_frame(&mut app, &ctx, vec![]); + let menu = node_center(&control_bar_frame(&mut app, &ctx, vec![]), "Panel menu").unwrap_or_else(|| panic!("the floating bar has a panel menu")); + let left = to.x - from.x; + assert!((menu.y - to.y).abs() < 1.0 && (menu.x - (left + 800.0 - 19.0)).abs() < 1.0, "the panel menu ends the 800-point bar: {menu:?}"); +} + +/// A floating Control bar's gripper moves it, and docks it again at the top or the bottom of the +/// window; from either edge it floats again. +#[test] +fn floating_control_bar_moves_and_redocks_from_each_edge() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("window.control.dock", json!({"edge": "float"})).unwrap(); + let at = super::CONTROL_BAR_FLOAT_AT; + drag_gripper(&mut app, &ctx, floating_grip(at), egui::pos2(300.0, 100.0)); + assert!(app.ui.control_bar_floating, "moved, it still floats"); + let moved = [300.0 - 14.0, 100.0 - 17.0]; + assert_eq!(app.ui.control_bar_float_pos, Some(moved)); + drag_gripper(&mut app, &ctx, floating_grip(moved), egui::pos2(500.0, 290.0)); + assert!(!app.ui.control_bar_floating && app.ui.control_bar_bottom, "released at the bottom: docked there"); + drag_gripper(&mut app, &ctx, docked_grip(true), egui::pos2(500.0, 160.0)); + assert!(app.ui.control_bar_floating, "from the bottom it floats again"); + let [x, y] = app.ui.control_bar_float_pos.unwrap_or_default(); + drag_gripper(&mut app, &ctx, floating_grip([x, y]), egui::pos2(500.0, 8.0)); + assert!(!app.ui.control_bar_floating && !app.ui.control_bar_bottom, "released at the top: docked there"); + drag_gripper(&mut app, &ctx, docked_grip(false), egui::pos2(700.0, 120.0)); + assert!(app.ui.control_bar_floating, "from the top it floats again"); +} + +/// A floating Control bar's panel menu keeps Dock to Top and Dock to Bottom, neither checked, and +/// each docks the bar at its edge. +#[test] +fn floating_control_bar_menu_docks_to_either_edge() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut crate::VectorcraftApp, events| control_bar_frame_in(app, &ctx, MENU_SCREEN, events); + for (item, bottom) in [("Dock to Bottom", true), ("Dock to Top", false)] { + app.run("window.control.dock", json!({"edge": "float"})).unwrap(); + frame(&mut app, vec![]); + let menu = node_center(&frame(&mut app, vec![]), "Panel menu").unwrap_or_else(|| panic!("the floating bar has a panel menu")); + frame(&mut app, vec![egui::Event::PointerMoved(menu), press_at(menu, true)]); + frame(&mut app, vec![press_at(menu, false)]); + let nodes = frame(&mut app, vec![]); + let checked = nodes.iter().filter_map(|n| n.label()).filter(|l| l.starts_with('✓') && l.contains("Dock")).count(); + assert_eq!(checked, 0, "neither edge is checked while the bar floats"); + let at = node_center(&nodes, item).unwrap_or_else(|| panic!("the menu lists {item}")); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + frame(&mut app, vec![press_at(at, false)]); + assert!(!app.ui.control_bar_floating && app.ui.control_bar_bottom == bottom, "{item} docks the bar"); + } +} + +/// Escape during a gripper drag cancels it: a docked bar stays at its edge and a floating one where +/// it floats. +#[test] +fn control_bar_drag_escape_restores_placement() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let escape = + || vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]; + drag_gripper_in(&mut app, &ctx, DOCK_SCREEN, docked_grip(false), egui::pos2(400.0, 150.0), escape()); + assert!(!app.ui.control_bar_floating && !app.ui.control_bar_bottom, "the docked bar stays at the top"); + assert!(!super::control_bar_moving(&ctx), "the drag is over"); + drag_gripper_in(&mut app, &ctx, DOCK_SCREEN, docked_grip(false), egui::pos2(400.0, 290.0), escape()); + assert!(!app.ui.control_bar_bottom, "a canceled drag over the bottom does not dock it there"); + app.run("window.control.dock", json!({"edge": "float"})).unwrap(); + let at = super::CONTROL_BAR_FLOAT_AT; + drag_gripper_in(&mut app, &ctx, DOCK_SCREEN, floating_grip(at), egui::pos2(500.0, 200.0), escape()); + assert!(app.ui.control_bar_floating, "the floating bar still floats"); + assert_eq!(app.ui.control_bar_float_pos, None, "where it floated"); + // A bar hidden in the middle of a drag leaves no drag to take a later Escape once the button + // is released. + let (from, to) = (floating_grip(at), egui::pos2(500.0, 200.0)); + control_bar_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), press_at(from, true)]); + for k in 1..=4 { + control_bar_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, k as f32 / 4.0))]); + } + assert!(super::control_bar_moving(&ctx), "the drag goes on"); + for events in [vec![press_at(to, false)], vec![]] { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(DOCK_SCREEN), ..Default::default() }, |_| {}); + out.textures_delta.clear(); + } + assert!(!super::control_bar_moving(&ctx), "released with the bar hidden, the drag is over"); +} + +/// An Escape in the same frame as the gripper's release is the drag's: the frame's shortcuts, which +/// run before the bar is drawn, still see the drag, and the bar stays where it was. +#[test] +fn control_bar_drag_escape_on_release_frame_is_the_drags() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let (from, to) = (docked_grip(false), egui::pos2(400.0, 150.0)); + control_bar_frame(&mut app, &ctx, vec![]); + control_bar_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), press_at(from, true)]); + for k in 1..=4 { + control_bar_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, k as f32 / 4.0))]); + } + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + let mut moving = None; + let input = egui::RawInput { events: vec![escape, press_at(to, false)], screen_rect: Some(DOCK_SCREEN), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + moving = Some(super::control_bar_moving(ui.ctx())); + super::control_bar(&mut app, ui); + }); + out.textures_delta.clear(); + assert_eq!(moving, Some(true), "the release frame's shortcuts see the drag"); + assert!(!app.ui.control_bar_floating && !app.ui.control_bar_bottom, "the canceled drag leaves the bar at the top"); + control_bar_frame(&mut app, &ctx, vec![]); + assert!(!super::control_bar_moving(&ctx), "the drag is over"); +} + +/// A gripper drag released outside the window leaves the bar where it was. +#[test] +fn control_bar_drag_release_outside_window_keeps_previous_placement() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + drag_gripper(&mut app, &ctx, docked_grip(false), egui::pos2(400.0, DOCK_SCREEN.bottom() + 120.0)); + assert!(!app.ui.control_bar_floating && !app.ui.control_bar_bottom, "the bar stays at the top"); + app.run("window.control.dock", json!({"edge": "float"})).unwrap(); + drag_gripper(&mut app, &ctx, floating_grip(super::CONTROL_BAR_FLOAT_AT), egui::pos2(-50.0, 150.0)); + assert!(app.ui.control_bar_floating && app.ui.control_bar_float_pos.is_none(), "the floating bar stays where it was"); +} + +/// In a window too short for a floating bar between the two docking zones, a release docks the bar +/// at the nearer edge; a floating bar saved on a bigger window is drawn inside a smaller one, its +/// panel menu in reach, without docking it. +#[test] +fn floating_control_bar_stays_reachable_in_tiny_and_resized_windows() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let tiny = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 70.0)); + drag_gripper_in(&mut app, &ctx, tiny, egui::pos2(13.0, 17.0), egui::pos2(300.0, 40.0), vec![]); + assert!(!app.ui.control_bar_floating && app.ui.control_bar_bottom, "released below the middle: docked at the bottom"); + app.run("window.control.dock", json!({"edge": "float"})).unwrap(); + app.ui.control_bar_float_pos = Some([1000.0, 250.0]); + let small = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(500.0, 120.0)); + control_bar_frame_in(&mut app, &ctx, small, vec![]); + let menu = node_center(&control_bar_frame_in(&mut app, &ctx, small, vec![]), "Panel menu") + .unwrap_or_else(|| panic!("the floating bar has a panel menu")); + assert!(small.shrink(1.0).contains(menu), "the panel menu is inside the smaller window: {menu:?}"); + assert!(app.ui.control_bar_floating, "a smaller window does not dock the bar"); + // The gripper too: a drag from where the bar is drawn moves it. + let grip = egui::pos2(small.right() - 500.0 + 14.0, small.bottom() - 34.0 + 17.0); + drag_gripper_in(&mut app, &ctx, small, grip, egui::pos2(200.0, 60.0), vec![]); + assert!(app.ui.control_bar_floating, "moved inside the smaller window"); + assert_eq!(app.ui.control_bar_float_pos, Some([0.0, 43.0]), "kept inside the window, its gripper under the pointer"); +} + +/// `window.control.dock {edge}` docks the Control bar to the top or the bottom of the window, or +/// floats it, and the panel menu checks the edge in use; another edge, or none, is an error and +/// changes nothing. A floating bar floats at the position it last floated at, docked in between +/// or hidden by Tab and shown again. +#[test] +fn the_control_bar_dock_command_takes_top_bottom_or_float() { let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); assert_eq!(app.run("window.control.dock", json!({"edge": "bottom"})).unwrap(), json!({"edge": "bottom"})); assert!(app.ui.control_bar_bottom); assert_eq!(crate::menus::checked(&app, "window.control.dock", &json!({"edge": "bottom"})), Some(true)); assert_eq!(crate::menus::checked(&app, "window.control.dock", &json!({"edge": "top"})), Some(false)); - for p in [json!({"edge": "left"}), json!({"edge": "Bottom"}), json!({"edge": 1}), json!({})] { + for p in [json!({"edge": "left"}), json!({"edge": "Bottom"}), json!({"edge": "Float"}), json!({"edge": 1}), json!({})] { let err = app.run("window.control.dock", p.clone()).unwrap_err(); - assert_eq!(err, "`edge` must be one of top, bottom", "{p}"); - assert!(app.ui.control_bar_bottom, "{p} leaves the bar at the bottom"); + assert_eq!(err, "`edge` must be one of top, bottom, float", "{p}"); + assert!(app.ui.control_bar_bottom && !app.ui.control_bar_floating, "{p} leaves the bar at the bottom"); } + assert_eq!(app.run("window.control.dock", json!({"edge": "float"})).unwrap(), json!({"edge": "float"})); + assert!(app.ui.control_bar_floating && app.ui.control_bar_bottom, "floating, it keeps the edge it docked to last"); + for edge in ["top", "bottom"] { + assert_eq!(crate::menus::checked(&app, "window.control.dock", &json!({ "edge": edge })), Some(false), "{edge}"); + } + assert_eq!(crate::menus::checked(&app, "window.control.dock", &json!({"edge": "float"})), Some(true)); + let err = app.run("window.control.dock", json!({"edge": "side"})).unwrap_err(); + assert_eq!(err, "`edge` must be one of top, bottom, float"); + assert!(app.ui.control_bar_floating, "an error leaves the bar floating"); + app.ui.control_bar_float_pos = Some([240.0, 160.0]); assert_eq!(app.run("window.control.dock", json!({"edge": "top"})).unwrap(), json!({"edge": "top"})); - assert!(!app.ui.control_bar_bottom); + assert!(!app.ui.control_bar_bottom && !app.ui.control_bar_floating); + app.run("window.control.dock", json!({"edge": "float"})).unwrap(); + assert_eq!(app.ui.control_bar_float_pos, Some([240.0, 160.0]), "it floats where it last floated"); + // Tab hides the floating bar, and Tab again shows it floating where it was. + app.ui.control_bar = true; + app.run("window.dock", json!({})).unwrap(); + assert!(!app.ui.control_bar && app.ui.control_bar_floating, "Tab hides the bar"); + app.run("window.dock", json!({})).unwrap(); + assert!(app.ui.control_bar && app.ui.control_bar_floating, "Tab shows it floating again"); + assert_eq!(app.ui.control_bar_float_pos, Some([240.0, 160.0])); } /// The labels of the Control bar panel menu's groups of options, in the menu's order. @@ -2667,6 +2897,10 @@ fn menus_stop_above_a_control_bar_docked_at_the_bottom() { assert_eq!(f, screen.bottom(), "docked at the top: menus stop at the window's bottom"); let f = floor(&mut app, true, true, 0); assert!(f < bar_top - 1.0, "the status and hint bars show above the Control bar: menus stop above them, {f}"); + // Floating after docking at the bottom, the bar is no bottom bar. + app.ui.control_bar_floating = true; + let f = floor(&mut app, false, true, 0); + assert_eq!(f, screen.bottom(), "floating: menus stop at the window's bottom"); } /// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index b40e8c790e..197f8faaaa 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -11,6 +11,7 @@ pub mod action_batch; pub mod action_insert_menu_item; pub mod action_new; pub mod action_playback; +pub mod action_select_object; pub mod action_set_options; pub mod action_stop; pub mod artboard_options; @@ -398,6 +399,7 @@ registry! { ActionStopRecord: [action_stop::RECORD_KIND] => action_stop::RECORD_SPEC, ActionStopMessage: [action_stop::MESSAGE_KIND] => action_stop::MESSAGE_SPEC, ActionInsertMenuItem: [action_insert_menu_item::KIND] => action_insert_menu_item::SPEC, + ActionSelectObject: [action_select_object::KIND] => action_select_object::SPEC, SliceOptions: [slices::OPTIONS] => slices::OPTIONS_SPEC, DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC, EpsOptions: [eps_options::KIND] => eps_options::SPEC, diff --git a/crates/ui-egui/src/dialogs/action_select_object.rs b/crates/ui-egui/src/dialogs/action_select_object.rs new file mode 100644 index 0000000000..455ae61cac --- /dev/null +++ b/crates/ui-egui/src/dialogs/action_select_object.rs @@ -0,0 +1,63 @@ +//! Actions panel menu › Select Object… (`ui.action.insertSelectObject`): Set Selection, which adds a +//! step that selects the objects whose Attributes note matches the note typed. +//! +//! Its fields: `note`, `caseSensitive`, `wholeWord`, and `set`, `action` and `step`, the place of the +//! new step (no `set` and `action`: the recording in progress). OK is off while the note is empty. +//! An invalid note or place is an error, and the dialog stays open. + +use serde_json::{Value, json}; + +use super::DialogSpec; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Set Selection. +pub const KIND: &str = "actionSelectObject"; + +/// The width of the Note label column. +const LABEL_W: f32 = 70.0; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Set Selection").into(), + body, + confirm, + ok_enabled: Some(|_, d| !d.str("note").trim().is_empty()), + min_width: 340.0, + ..DialogSpec::FORM +}; + +/// Opens Set Selection for action `target` as (set, action), after `step`, else for the recording +/// in progress. +pub fn open(app: &mut VectorcraftApp, target: Option<(usize, usize)>, step: Option) { + let mut fields = json!({"note": "", "caseSensitive": false, "wholeWord": false}); + if let Some((set, action)) = target { + fields["set"] = json!(set); + fields["action"] = json!(action); + if let Some(step) = step { + fields["step"] = json!(step); + } + } + app.ui.dialog = Some(Dialog::new(KIND, fields)); +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + widgets::label_row(ui, "Note:", LABEL_W, |ui| { + super::form::text(ui, d, "note", 240.0); + }); + super::form::check(ui, d, "caseSensitive", "Case Sensitive"); + super::form::check(ui, d, "wholeWord", "Whole Word"); + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + // The fields go as they are, so a field of another type is an error rather than a default. + let mut params = json!({}); + for key in ["note", "caseSensitive", "wholeWord", "set", "action", "step"] { + if let Some(value) = d.fields.get(key) { + params[key] = value.clone(); + } + } + let r = app.run(crate::panels::actions::INSERT_SELECT_OBJECT, params)?; + app.ui.dialog = None; + Ok(r) +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 2e277caea8..948b6f990f 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -64,12 +64,16 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// Does this dialog show a Preview checkbox? Grid Repeat Options does: the public page for the /// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does /// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path -/// works the same way (#5532), and so do Image Tools › Remove Background and Cutting Tools › Weed -/// Box and Lines. (Cancel rolls a preview back whichever dialog started it.) +/// works the same way (#5532), and so do Image Tools › Remove Background and Color Mask and +/// Cutting Tools › Weed Box and Lines. (Cancel rolls a preview back whichever dialog started it.) fn previews(d: &Dialog) -> bool { match d.str("__command").as_str() { "object.repeat.options" => d.fields.contains_key("gridType"), - "type.pathOptions" | crate::addons::typetools::RELEASE | crate::addons::image::REMOVE_BACKGROUND | crate::addons::cutting::WEED => true, + "type.pathOptions" + | crate::addons::typetools::RELEASE + | crate::addons::image::REMOVE_BACKGROUND + | crate::addons::image::COLOR_MASK + | crate::addons::cutting::WEED => true, _ => false, } } @@ -134,7 +138,9 @@ fn order(command: &str) -> &'static [&'static str] { "object.pathfinder.trap" => &["thickness", "heightWidth", "tintReduction", "trapsWithProcessColor", "reverseTraps"], "addon.color.printFixes" => &["inkLimit", "excludePureBlack", "removeWhiteOverprint", "overprintBlack", "textOnly", "fill", "stroke"], crate::addons::typetools::RELEASE => &["mode", "keepOriginal"], - crate::addons::image::REMOVE_BACKGROUND => &["background", "colors", "contiguous", "match", "tolerance", "softness"], + crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK => { + &["background", "colors", "contiguous", "match", "tolerance", "softness"] + } crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], _ => &[], } @@ -157,8 +163,8 @@ fn choices(command: &str, key: &str) -> Option { ("graph.setType", "pieLegend") => Some(PIE_LEGEND), ("graph.setType", "piePosition") => Some(PIE_POSITION), ("graph.setType", "pieSort") => Some(PIE_SORT), - (crate::addons::image::REMOVE_BACKGROUND, "background") => Some(crate::addons::image::BACKGROUNDS), - (crate::addons::image::REMOVE_BACKGROUND, "match") => Some(crate::addons::image::MATCHES), + (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "background") => Some(crate::addons::image::BACKGROUNDS), + (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "match") => Some(crate::addons::image::MATCHES), _ => None, } } diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 96e33684bc..cfd6c3b0d3 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -151,11 +151,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { r } -/// Say in the status bar when `file.new`'s result `r` reports a profile it could not read. +/// Say in the status bar when `file.new`'s result `r` reports a profile it could not read, or +/// color profiles its file carries that can't be used. fn report_profile(app: &mut VectorcraftApp, r: &Value) { if let Some(e) = r.get("profileError") { let (name, reason) = (e["profile"].as_str().unwrap_or_default(), e["reason"].as_str().unwrap_or_default()); app.status(format!("The {name} profile could not be read, so the new document has the default settings: {reason}")); + } else if let Some(w) = r["warnings"].as_array().filter(|w| !w.is_empty()) { + app.status(w.iter().filter_map(Value::as_str).collect::>().join("; ")); } } @@ -1592,6 +1595,15 @@ mod tests { } } + /// A color profile in the profile's file that can't be used, which `file.new` reports, shows in + /// the status bar. + #[test] + fn profile_warnings_show_in_the_status_bar() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + super::report_profile(&mut app, &json!({"index": 0, "warnings": ["the color profile X can't be used"]})); + assert_eq!(app.ui.status, "the color profile X can't be used"); + } + /// Manage Profiles lists a row per profile; Reset is off until a profile has been edited, Escape /// closes only the pop-up, and Edit opens the profile as a document and closes New Document. #[test] diff --git a/crates/ui-egui/src/dialogs/rename_artboards.rs b/crates/ui-egui/src/dialogs/rename_artboards.rs index 82761e9284..bd621ebdbe 100644 --- a/crates/ui-egui/src/dialogs/rename_artboards.rs +++ b/crates/ui-egui/src/dialogs/rename_artboards.rs @@ -1,4 +1,5 @@ -//! The Artboard tool's canvas menu › Rename: a name for the selected artboards. OK runs +//! The Artboard tool's canvas menu › Rename, and the Artboards panel's row menu › Rename: a name +//! for the selected artboards. OK runs //! `artboard.rename` as one undo step; with several artboards the name is numbered. //! //! Fields: `name` (the artboard's name with one artboard, empty with several) and `indices` (the diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 01d0d46198..ca25bdf078 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -696,6 +696,10 @@ font-technology Variable Променливи Corner Color Цвят на ъглите Contiguous Съседни Each Channel Всеки канал + Color Mask… Цветова маска… + Color Mask Цветова маска + Remove Color Mask Премахване на цветовата маска + Apply Color Mask Прилагане на цветовата маска Edit Path Редактиране на контура Mask Маска Crop Marks Знаци за изрязване @@ -5982,6 +5986,16 @@ axis Y Axis Y ос @msg Batch cannot play an action with a stop Пакет не може да изпълни действие със спиране Insert Menu Item… Вмъкване на елемент от меню… Insert Menu Item Вмъкване на елемент от меню + Select Object… Избиране на обект… + Select Object Избиране на обект + Set Selection Задаване на селекция + Case Sensitive Различаване на главни и малки букви + Whole Word Цяла дума + Select Object: {note} Избиране на обект: {note} + Select by Note Избиране по забележка +@msg the note is empty забележката е празна +@msg the note is longer than 1,024 bytes забележката е по-дълга от 1024 байта +@msg no object that can be selected has a note matching “{query}” няма обект, който може да бъде избран, със забележка, съответстваща на „{query}“ Menu Item: Елемент от меню: No menu item matches. Няма съвпадащ елемент от меню. Several menu items match. Choose one from the list. Съвпадат няколко елемента от меню. Изберете един от списъка. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index e28bd593b0..69fcb871b9 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -206,6 +206,10 @@ Corner Color Boja uglova Contiguous Susjedni Each Channel Svaki kanal + Color Mask… Maska boja… + Color Mask Maska boja + Remove Color Mask Ukloni masku boja + Apply Color Mask Primijeni masku boja Edit Path Uredi putanju Mask Maska Rasterize… Rasteriziraj… @@ -6024,6 +6028,16 @@ axis Y Axis Y osa @msg Batch cannot play an action with a stop Paketna obrada ne može reprodukovati akciju sa zaustavljanjem Insert Menu Item… Umetni stavku menija… Insert Menu Item Umetni stavku menija + Select Object… Odaberi objekt… + Select Object Odaberi objekt + Set Selection Postavi odabir + Case Sensitive Razlikuj velika i mala slova + Whole Word Cijela riječ + Select Object: {note} Odaberi objekt: {note} + Select by Note Odaberi po napomeni +@msg the note is empty napomena je prazna +@msg the note is longer than 1,024 bytes napomena je duža od 1.024 bajta +@msg no object that can be selected has a note matching “{query}” nijedan objekt koji se može odabrati nema napomenu koja odgovara „{query}” Menu Item: Stavka menija: No menu item matches. Nijedna stavka menija ne odgovara. Several menu items match. Choose one from the list. Odgovara više stavki menija. Izaberite jednu sa liste. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 842aa4a226..33df72c253 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1011,6 +1011,10 @@ antiAlias Sharp Nítid Corner Color Color de les cantonades Contiguous Contigu Each Channel Cada canal + Color Mask… Màscara de color… + Color Mask Màscara de color + Remove Color Mask Elimina la màscara de color + Apply Color Mask Aplica la màscara de color Crop Marks Marques de retall Crop To Retalla fins a Cross Creu @@ -4037,6 +4041,16 @@ digits Malayalam Malaiàlam @msg Batch cannot play an action with a stop Lot no pot reproduir una acció amb una aturada Insert Menu Item… Insereix un element de menú… Insert Menu Item Insereix un element de menú + Select Object… Selecciona un objecte… + Select Object Selecciona un objecte + Set Selection Defineix la selecció + Case Sensitive Distingeix majúscules i minúscules + Whole Word Paraula sencera + Select Object: {note} Selecciona un objecte: {note} + Select by Note Selecciona per nota +@msg the note is empty la nota és buida +@msg the note is longer than 1,024 bytes la nota té més de 1.024 bytes +@msg no object that can be selected has a note matching “{query}” cap objecte que es pugui seleccionar té una nota que coincideixi amb “{query}” Menu Item: Element de menú: No menu item matches. Cap element de menú no coincideix. Several menu items match. Choose one from the list. Coincideixen diversos elements de menú. Trieu-ne un de la llista. @@ -5957,6 +5971,10 @@ digits Malayalam Malaiàlam @msg a CMYK image has no transparency to set una imatge CMYK no té transparència per establir @msg every pixel matches the background: no image would be left cada píxel coincideix amb el fons: no quedaria cap imatge @msg an image of {w} × {h} pixels is too large to change una imatge de {w} × {h} píxels és massa gran per canviar-la +@msg select an image with a color mask selecciona una imatge amb una màscara de color +@msg the color mask's settings are out of range la configuració de la màscara de color és fora de l’interval +@msg a CMYK image can't take a color mask una imatge CMYK no pot tenir una màscara de color +@msg the mask would hide every pixel la màscara amagaria tots els píxels @msg select an Image Trace object selecciona un objecte d’Image Trace @msg select an Intertwine group selecciona un grup Intertwine @msg select an object in perspective selecciona un objecte en perspectiva @@ -6187,6 +6205,7 @@ digits Malayalam Malaiàlam @msg unknown parameter `{path}`; it takes: {keys} paràmetre desconegut `{path}`; admet: {keys} @msg missing `{path}` falta `{path}` @msg `{path}` must be {expected}, not {got} `{path}` ha de ser {expected}, no {got} +@msg `{path}` is nested too deeply `{path}` està imbricat massa profundament @msg unknown preference `{key}` preferència desconeguda `{key}` @msg Preferences imported. S’han importat les preferències. @msg not a preferences file: {e} no és un fitxer de preferències: {e} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 550f2a74c0..ff48f1ecfc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -212,6 +212,10 @@ Corner Color Barva rohů Contiguous Souvislé Each Channel Každý kanál + Color Mask… Barevná maska… + Color Mask Barevná maska + Remove Color Mask Odstranit barevnou masku + Apply Color Mask Použít barevnou masku Edit Path Upravit cestu Mask Maska Rasterize… Rastrovat… @@ -5096,6 +5100,10 @@ imageTrace Outline Obrys @msg a CMYK image has no transparency to set obraz CMYK nemá průhlednost, kterou by bylo možné nastavit @msg every pixel matches the background: no image would be left každý obrazový bod odpovídá pozadí: nezbyl by žádný obraz @msg an image of {w} × {h} pixels is too large to change obraz o velikosti {w} × {h} obrazových bodů je příliš velký na změnu +@msg select an image with a color mask vyberte obraz s barevnou maskou +@msg the color mask's settings are out of range nastavení barevné masky jsou mimo rozsah +@msg a CMYK image can't take a color mask obraz CMYK nemůže mít barevnou masku +@msg the mask would hide every pixel maska by skryla všechny obrazové body @msg select an object in perspective vyberte objekt v perspektivě @msg select artwork (or a colour group) to recolor vyberte kresbu (nebo skupinu barev) k přebarvení @msg Recolor completed; {locked} and {hidden} were left unchanged Přebarvení dokončeno; beze změny: {locked} a {hidden} @@ -5878,6 +5886,7 @@ mark-style Japanese Japonské @msg unknown parameter `{path}`; it takes: {keys} neznámý parametr `{path}`; přijímá: {keys} @msg missing `{path}` chybí `{path}` @msg `{path}` must be {expected}, not {got} `{path}` musí být {expected}, nikoli {got} +@msg `{path}` is nested too deeply `{path}` je vnořený příliš hluboko Load EPS into Clipboard Načíst EPS do schránky @msg an image of {w} × {h} pixels is too large to draw obraz o velikosti {w} × {h} obrazových bodů je příliš velký na vykreslení @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: není obraz PNG, JPEG, WebP, TIFF ani BMP @@ -6423,6 +6432,16 @@ axis Y Axis osa Y @msg Batch cannot play an action with a stop Dávka nemůže přehrát akci se zastavením Insert Menu Item… Vložit položku nabídky… Insert Menu Item Vložit položku nabídky + Select Object… Vybrat objekt… + Select Object Vybrat objekt + Set Selection Nastavit výběr + Case Sensitive Rozlišovat velká a malá písmena + Whole Word Celé slovo + Select Object: {note} Vybrat objekt: {note} + Select by Note Vybrat podle poznámky +@msg the note is empty poznámka je prázdná +@msg the note is longer than 1,024 bytes poznámka je delší než 1 024 bajtů +@msg no object that can be selected has a note matching “{query}” žádný objekt, který lze vybrat, nemá poznámku odpovídající „{query}“ Menu Item: Položka nabídky: No menu item matches. Žádná položka nabídky neodpovídá. Several menu items match. Choose one from the list. Odpovídá několik položek nabídky. Vyberte jednu ze seznamu. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b25d0b7e90..38300ca372 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -199,6 +199,10 @@ Corner Color Hjørnefarve Contiguous Sammenhængende Each Channel Hver kanal + Color Mask… Farvemaske… + Color Mask Farvemaske + Remove Color Mask Fjern farvemaske + Apply Color Mask Anvend farvemaske Edit Path Redigér kurve Mask Maskér Rasterize… Rasterisér… @@ -5999,6 +6003,16 @@ axis Y Axis Y-akse @msg Batch cannot play an action with a stop Batch kan ikke afspille en handling med et stop Insert Menu Item… Indsæt menupunkt… Insert Menu Item Indsæt menupunkt + Select Object… Markér objekt… + Select Object Markér objekt + Set Selection Angiv markering + Case Sensitive Forskel på store og små bogstaver + Whole Word Helt ord + Select Object: {note} Markér objekt: {note} + Select by Note Markér efter note +@msg the note is empty noten er tom +@msg the note is longer than 1,024 bytes noten er længere end 1.024 byte +@msg no object that can be selected has a note matching “{query}” intet objekt, der kan markeres, har en note, der matcher »{query}« Menu Item: Menupunkt: No menu item matches. Intet menupunkt passer. Several menu items match. Choose one from the list. Flere menupunkter passer. Vælg et fra listen. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index eba161428f..1d3b12f63a 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -689,6 +689,10 @@ font-technology Variable Variabel Corner Color Eckfarbe Contiguous Zusammenhängend Each Channel Jeder Kanal + Color Mask… Farbmaske… + Color Mask Farbmaske + Remove Color Mask Farbmaske entfernen + Apply Color Mask Farbmaske anwenden Edit Path Pfad bearbeiten Mask Maske Crop Marks Schnittmarken @@ -4713,6 +4717,10 @@ theme Appearance Erscheinungsbild @msg a CMYK image has no transparency to set ein CMYK-Bild hat keine Transparenz, die festgelegt werden kann @msg every pixel matches the background: no image would be left jedes Pixel entspricht dem Hintergrund: Es würde kein Bild übrig bleiben @msg an image of {w} × {h} pixels is too large to change ein Bild mit {w} × {h} Pixeln ist zu groß, um geändert zu werden +@msg select an image with a color mask wählen Sie ein Bild mit einer Farbmaske aus +@msg the color mask's settings are out of range die Einstellungen der Farbmaske liegen außerhalb des zulässigen Bereichs +@msg a CMYK image can't take a color mask ein CMYK-Bild kann keine Farbmaske erhalten +@msg the mask would hide every pixel die Maske würde jedes Pixel ausblenden @msg select an object in perspective wählen Sie ein Objekt in der Perspektive aus @msg select artwork (or a colour group) to recolor wählen Sie eine Grafik (oder eine Farbgruppe) zum Neufärben aus @msg Recolor completed; {locked} and {hidden} were left unchanged Neufärben abgeschlossen; unverändert: {locked} und {hidden} @@ -5453,6 +5461,7 @@ lighting Light Licht @msg unknown parameter `{path}`; it takes: {keys} unbekannter Parameter `{path}`; akzeptiert werden: {keys} @msg missing `{path}` `{path}` fehlt @msg `{path}` must be {expected}, not {got} `{path}` muss {expected} sein, nicht {got} +@msg `{path}` is nested too deeply `{path}` ist zu tief verschachtelt Load EPS into Clipboard EPS in die Zwischenablage laden @msg an image of {w} × {h} pixels is too large to draw ein Bild mit {w} × {h} Pixeln ist zu groß, um gezeichnet zu werden @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: kein PNG-, JPEG-, WebP-, TIFF- oder BMP-Bild @@ -6014,6 +6023,16 @@ axis Y Axis Y-Achse @msg Batch cannot play an action with a stop Die Stapelverarbeitung kann keine Aktion mit einem Stopp abspielen Insert Menu Item… Menübefehl einfügen… Insert Menu Item Menübefehl einfügen + Select Object… Objekt auswählen… + Select Object Objekt auswählen + Set Selection Auswahl festlegen + Case Sensitive Groß-/Kleinschreibung beachten + Whole Word Ganzes Wort + Select Object: {note} Objekt auswählen: {note} + Select by Note Nach Notiz auswählen +@msg the note is empty die Notiz ist leer +@msg the note is longer than 1,024 bytes die Notiz ist länger als 1.024 Byte +@msg no object that can be selected has a note matching “{query}” kein auswählbares Objekt hat eine Notiz, die „{query}“ entspricht Menu Item: Menübefehl: No menu item matches. Kein Menübefehl passt. Several menu items match. Choose one from the list. Mehrere Menübefehle passen. Wählen Sie einen aus der Liste. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 4fab977d6d..8467b8e831 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -670,6 +670,10 @@ font-technology Variable Μεταβλητές Corner Color Χρώμα γωνιών Contiguous Συνεχόμενα Each Channel Κάθε κανάλι + Color Mask… Μάσκα χρώματος… + Color Mask Μάσκα χρώματος + Remove Color Mask Αφαίρεση μάσκας χρώματος + Apply Color Mask Εφαρμογή μάσκας χρώματος Edit Path Επεξεργασία διαδρομής Mask Μάσκα Crop Marks Σημάδια ξακρίσματος @@ -4735,6 +4739,10 @@ digits Malayalam Μαλαγιάλαμ @msg a CMYK image has no transparency to set μια εικόνα CMYK δεν έχει διαφάνεια για να οριστεί @msg every pixel matches the background: no image would be left κάθε εικονοστοιχείο ταιριάζει με το φόντο: δεν θα έμενε καμία εικόνα @msg an image of {w} × {h} pixels is too large to change η εικόνα {w} × {h} εικονοστοιχείων είναι υπερβολικά μεγάλη για να αλλάξει +@msg select an image with a color mask επιλέξτε εικόνα με μάσκα χρώματος +@msg the color mask's settings are out of range οι ρυθμίσεις της μάσκας χρώματος είναι εκτός εύρους +@msg a CMYK image can't take a color mask μια εικόνα CMYK δεν μπορεί να έχει μάσκα χρώματος +@msg the mask would hide every pixel η μάσκα θα έκρυβε κάθε εικονοστοιχείο @msg select an object in perspective επιλέξτε αντικείμενο σε προοπτική @msg select artwork (or a colour group) to recolor επιλέξτε σχέδιο (ή ομάδα χρωμάτων) για επαναχρωματισμό @msg Recolor completed; {locked} and {hidden} were left unchanged Ο επαναχρωματισμός ολοκληρώθηκε· χωρίς αλλαγή: {locked} και {hidden} @@ -5237,6 +5245,7 @@ digits Malayalam Μαλαγιάλαμ @msg unknown parameter `{path}`; it takes: {keys} άγνωστη παράμετρος `{path}`· δέχεται: {keys} @msg missing `{path}` λείπει το `{path}` @msg `{path}` must be {expected}, not {got} Το `{path}` πρέπει να είναι {expected}, όχι {got} +@msg `{path}` is nested too deeply Το `{path}` έχει υπερβολικά βαθιά ένθεση 1 Layer 1 επίπεδο 1 bit 1 bit 16 Colors 16 χρώματα @@ -6374,6 +6383,16 @@ axis Y Axis Άξονας Y @msg Batch cannot play an action with a stop Η μαζική επεξεργασία δεν μπορεί να αναπαράγει ενέργεια με διακοπή Insert Menu Item… Εισαγωγή στοιχείου μενού… Insert Menu Item Εισαγωγή στοιχείου μενού + Select Object… Επιλογή αντικειμένου… + Select Object Επιλογή αντικειμένου + Set Selection Ορισμός επιλογής + Case Sensitive Διάκριση πεζών-κεφαλαίων + Whole Word Ολόκληρη λέξη + Select Object: {note} Επιλογή αντικειμένου: {note} + Select by Note Επιλογή βάσει σημείωσης +@msg the note is empty η σημείωση είναι κενή +@msg the note is longer than 1,024 bytes η σημείωση υπερβαίνει τα 1.024 byte +@msg no object that can be selected has a note matching “{query}” κανένα αντικείμενο που μπορεί να επιλεγεί δεν έχει σημείωση που να ταιριάζει με «{query}» Menu Item: Στοιχείο μενού: No menu item matches. Κανένα στοιχείο μενού δεν ταιριάζει. Several menu items match. Choose one from the list. Ταιριάζουν πολλά στοιχεία μενού. Επιλέξτε ένα από τη λίστα. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f1a066e241..194ba2c602 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -710,6 +710,10 @@ font-technology Variable Variables Corner Color Color de las esquinas Contiguous Contiguo Each Channel Cada canal + Color Mask… Máscara de color… + Color Mask Máscara de color + Remove Color Mask Quitar máscara de color + Apply Color Mask Aplicar máscara de color Edit Path Editar trazado Mask Máscara Crop Marks Marcas de corte @@ -4788,6 +4792,10 @@ axis Both Ambos @msg a CMYK image has no transparency to set una imagen CMYK no tiene transparencia que establecer @msg every pixel matches the background: no image would be left todos los píxeles coinciden con el fondo: no quedaría ninguna imagen @msg an image of {w} × {h} pixels is too large to change una imagen de {w} × {h} píxeles es demasiado grande para cambiarla +@msg select an image with a color mask selecciona una imagen con una máscara de color +@msg the color mask's settings are out of range los ajustes de la máscara de color están fuera de rango +@msg a CMYK image can't take a color mask una imagen CMYK no puede tener una máscara de color +@msg the mask would hide every pixel la máscara ocultaría todos los píxeles @msg select an object in perspective selecciona un objeto en perspectiva @msg select artwork (or a colour group) to recolor selecciona la ilustración (o un grupo de colores) que quieres volver a colorear @msg Recolor completed; {locked} and {hidden} were left unchanged Recoloreado completado; sin cambios: {locked} y {hidden} @@ -5819,6 +5827,7 @@ mark-style Japanese Japonesas @msg unknown parameter `{path}`; it takes: {keys} parámetro desconocido `{path}`; acepta: {keys} @msg missing `{path}` falta `{path}` @msg `{path}` must be {expected}, not {got} `{path}` debe ser {expected}, no {got} +@msg `{path}` is nested too deeply `{path}` está anidado a demasiada profundidad Load EPS into Clipboard Cargar EPS en el portapapeles @msg an image of {w} × {h} pixels is too large to draw una imagen de {w} × {h} píxeles es demasiado grande para dibujarse @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: no es una imagen PNG, JPEG, WebP, TIFF ni BMP @@ -6365,6 +6374,16 @@ axis Y Axis Eje Y @msg Batch cannot play an action with a stop Lote no puede reproducir una acción con una parada Insert Menu Item… Insertar elemento de menú… Insert Menu Item Insertar elemento de menú + Select Object… Seleccionar objeto… + Select Object Seleccionar objeto + Set Selection Definir selección + Case Sensitive Distinguir mayúsculas y minúsculas + Whole Word Palabra completa + Select Object: {note} Seleccionar objeto: {note} + Select by Note Seleccionar por nota +@msg the note is empty la nota está vacía +@msg the note is longer than 1,024 bytes la nota ocupa más de 1024 bytes +@msg no object that can be selected has a note matching “{query}” ningún objeto que se pueda seleccionar tiene una nota que coincida con “{query}” Menu Item: Elemento de menú: No menu item matches. Ningún elemento de menú coincide. Several menu items match. Choose one from the list. Coinciden varios elementos de menú. Elija uno de la lista. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1e74101057..e36c5e891e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -219,6 +219,10 @@ Corner Color Kulmien väri Contiguous Yhtenäinen Each Channel Jokainen kanava + Color Mask… Värimaski… + Color Mask Värimaski + Remove Color Mask Poista värimaski + Apply Color Mask Käytä värimaskia Edit Path Muokkaa polkua Mask Maski Rasterize… Rasteroi… @@ -4996,6 +5000,10 @@ imageTrace Outline Ääriviiva @msg a CMYK image has no transparency to set CMYK-kuvalla ei ole asetettavaa läpinäkyvyyttä @msg every pixel matches the background: no image would be left jokainen pikseli vastaa taustaa: kuvaa ei jäisi jäljelle @msg an image of {w} × {h} pixels is too large to change kuva, jonka koko on {w} × {h} pikseliä, on liian suuri muutettavaksi +@msg select an image with a color mask valitse kuva, jossa on värimaski +@msg the color mask's settings are out of range värimaskin asetukset ovat sallitun alueen ulkopuolella +@msg a CMYK image can't take a color mask CMYK-kuvalla ei voi olla värimaskia +@msg the mask would hide every pixel maski piilottaisi jokaisen pikselin @msg select an object in perspective valitse perspektiivissä oleva objekti @msg select artwork (or a colour group) to recolor valitse uudelleenväritettävä kuvitus (tai väriryhmä) @msg Recolor completed; {locked} and {hidden} were left unchanged Uudelleenväritys valmis; muuttamatta jäi: {locked} ja {hidden} @@ -5760,6 +5768,7 @@ mark-style Japanese Japanilainen @msg unknown parameter `{path}`; it takes: {keys} tuntematon parametri `{path}`; parametrit: {keys} @msg missing `{path}` `{path}` puuttuu @msg `{path}` must be {expected}, not {got} `{path}` on oltava {expected}, ei {got} +@msg `{path}` is nested too deeply `{path}` on liian syvällä sisäkkäin Load EPS into Clipboard Lataa EPS leikepöydälle @msg an image of {w} × {h} pixels is too large to draw kuva, jonka koko on {w} × {h} pikseliä, on liian suuri piirrettäväksi @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: ei ole PNG-, JPEG-, WebP-, TIFF- tai BMP-kuva @@ -6453,6 +6462,16 @@ axis Y Axis Y-akseli @msg Batch cannot play an action with a stop Erä ei voi toistaa toimintoa, jossa on pysäytys Insert Menu Item… Lisää valikkokohta… Insert Menu Item Lisää valikkokohta + Select Object… Valitse objekti… + Select Object Valitse objekti + Set Selection Määritä valinta + Case Sensitive Kirjainkoko merkitsevä + Whole Word Koko sana + Select Object: {note} Valitse objekti: {note} + Select by Note Valitse huomautuksen mukaan +@msg the note is empty huomautus on tyhjä +@msg the note is longer than 1,024 bytes huomautus on pidempi kuin 1 024 tavua +@msg no object that can be selected has a note matching “{query}” millään valittavissa olevalla objektilla ei ole huomautusta, joka vastaa hakua ”{query}” Menu Item: Valikkokohta: No menu item matches. Mikään valikkokohta ei vastaa hakua. Several menu items match. Choose one from the list. Useampi valikkokohta vastaa hakua. Valitse yksi luettelosta. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 5a9fc45805..067845f493 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -712,6 +712,10 @@ font-technology Variable Variables Corner Color Couleur des angles Contiguous Contigu Each Channel Chaque canal + Color Mask… Masque de couleur… + Color Mask Masque de couleur + Remove Color Mask Supprimer le masque de couleur + Apply Color Mask Appliquer le masque de couleur Edit Path Modifier le tracé Mask Masque Crop Marks Traits de coupe @@ -4777,6 +4781,10 @@ axis Both Les deux @msg a CMYK image has no transparency to set une image CMJN n’a pas de transparence à définir @msg every pixel matches the background: no image would be left chaque pixel correspond à l’arrière-plan : il ne resterait aucune image @msg an image of {w} × {h} pixels is too large to change une image de {w} × {h} pixels est trop grande pour être modifiée +@msg select an image with a color mask sélectionnez une image avec un masque de couleur +@msg the color mask's settings are out of range les réglages du masque de couleur sont hors limites +@msg a CMYK image can't take a color mask une image CMJN ne peut pas recevoir de masque de couleur +@msg the mask would hide every pixel le masque cacherait tous les pixels @msg select an object in perspective sélectionnez un objet en perspective @msg select artwork (or a colour group) to recolor sélectionnez l’illustration (ou un groupe de couleurs) dont redéfinir les couleurs @msg Recolor completed; {locked} and {hidden} were left unchanged Recoloration terminée ; sans changement : {locked} et {hidden} @@ -5448,6 +5456,7 @@ lighting Light Lumière @msg unknown parameter `{path}`; it takes: {keys} paramètre inconnu `{path}` ; il accepte : {keys} @msg missing `{path}` `{path}` manquant @msg `{path}` must be {expected}, not {got} `{path}` doit être {expected}, pas {got} +@msg `{path}` is nested too deeply `{path}` est imbriqué trop profondément 1 Layer 1 calque 1 bit 1 bit 16 Colors 16 couleurs @@ -6418,6 +6427,16 @@ axis Y Axis Axe Y @msg Batch cannot play an action with a stop Le traitement par lots ne peut pas exécuter un script comportant un arrêt Insert Menu Item… Insérer une commande de menu… Insert Menu Item Insérer une commande de menu + Select Object… Sélectionner un objet… + Select Object Sélectionner un objet + Set Selection Définir la sélection + Case Sensitive Respecter la casse + Whole Word Mot entier + Select Object: {note} Sélectionner un objet : {note} + Select by Note Sélectionner par remarque +@msg the note is empty la remarque est vide +@msg the note is longer than 1,024 bytes la remarque dépasse 1 024 octets +@msg no object that can be selected has a note matching “{query}” aucun objet sélectionnable n’a de remarque correspondant à « {query} » Menu Item: Commande de menu : No menu item matches. Aucune commande de menu ne correspond. Several menu items match. Choose one from the list. Plusieurs commandes de menu correspondent. Choisissez-en une dans la liste. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 70a93fb517..165e04ae7d 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1129,6 +1129,10 @@ antiAlias Sharp शार्प Corner Color कोनों का रंग Contiguous सन्निहित Each Channel प्रत्येक चैनल + Color Mask… रंग मास्क… + Color Mask रंग मास्क + Remove Color Mask रंग मास्क हटाएँ + Apply Color Mask रंग मास्क लागू करें Crop Marks क्रॉप मार्क Crop To करने के लिए फसल Cross क्रॉस @@ -3466,6 +3470,16 @@ antiAlias Sharp शार्प @msg Batch cannot play an action with a stop बैच स्टॉप वाला एक्शन नहीं चला सकता Insert Menu Item… मेनू आइटम जोड़ें… Insert Menu Item मेनू आइटम जोड़ें + Select Object… ऑब्जेक्ट सिलेक्ट करें… + Select Object ऑब्जेक्ट सिलेक्ट करें + Set Selection सिलेक्शन सेट करें + Case Sensitive केस सेंसिटिव + Whole Word पूरा शब्द + Select Object: {note} ऑब्जेक्ट सिलेक्ट करें: {note} + Select by Note नोट द्वारा चुनें +@msg the note is empty नोट खाली है +@msg the note is longer than 1,024 bytes नोट 1,024 बाइट से लंबा है +@msg no object that can be selected has a note matching “{query}” सिलेक्ट किए जा सकने वाले किसी भी ऑब्जेक्ट का नोट “{query}” से मेल नहीं खाता Menu Item: मेनू आइटम: No menu item matches. कोई मेनू आइटम मेल नहीं खाता। Several menu items match. Choose one from the list. कई मेनू आइटम मेल खाते हैं। सूची से एक चुनें। @@ -7655,6 +7669,10 @@ antiAlias Sharp शार्प @msg a CMYK image has no transparency to set CMYK इमेज में सेट करने के लिए कोई पारदर्शिता नहीं है @msg every pixel matches the background: no image would be left हर पिक्सेल पृष्ठभूमि से मेल खाता है: कोई इमेज नहीं बचेगी @msg an image of {w} × {h} pixels is too large to change {w} × {h} पिक्सेल की इमेज बदलने के लिए बहुत बड़ी है +@msg select an image with a color mask रंग मास्क वाली एक इमेज चुनें +@msg the color mask's settings are out of range रंग मास्क की सेटिंग सीमा से बाहर हैं +@msg a CMYK image can't take a color mask CMYK इमेज पर रंग मास्क नहीं लगाया जा सकता +@msg the mask would hide every pixel मास्क हर पिक्सेल को छिपा देगा @msg select an image (or an Image Trace group) एक इमेज सिलेक्ट करें (या एक इमेज ट्रेस समूह) @msg select an Image Trace object एक इमेज ट्रेस ऑब्जेक्ट चुनें @msg select an image, or pass id एक इमेज सिलेक्ट करें, या आईडी पास करें @@ -8228,6 +8246,7 @@ antiAlias Sharp शार्प @msg unknown parameter `{path}`; it takes: {keys} अज्ञात पैरामीटर `{path}`; यह लेता है: {keys} @msg missing `{path}` लापता `{path}` @msg `{path}` must be {expected}, not {got} `{path}` {expected} होना चाहिए, {got} नहीं +@msg `{path}` is nested too deeply `{path}` बहुत गहराई तक नेस्ट किया गया है @msg unknown PDF preset `{name}` (presets: {_1}) अज्ञात PDF प्रीसेट `{name}` (presets: {_1}) @msg unknown pieLegend `{v}` (none, standard or wedges) अज्ञात pieLegend `{v}` (one, मानक या wedges) @msg unknown piePosition `{v}` (even, ratio or stacked) अज्ञात piePosition `{v}` (यहां तक कि अनुपात या स्टैक्ड) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 33047b6c3d..2ccf9d57bc 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -911,6 +911,10 @@ font-technology Variable Változó Corner Color Sarokszín Contiguous Összefüggő Each Channel Minden csatorna + Color Mask… Színmaszk… + Color Mask Színmaszk + Remove Color Mask Színmaszk eltávolítása + Apply Color Mask Színmaszk alkalmazása Edit Path Útvonal szerkesztése Crop Marks Vágójelek Crop To Körülvágás @@ -5539,6 +5543,10 @@ imageTrace Outline Körvonal @msg a CMYK image has no transparency to set a CMYK képnek nincs beállítható átlátszósága @msg every pixel matches the background: no image would be left minden képpont egyezik a háttérrel: nem maradna kép @msg an image of {w} × {h} pixels is too large to change egy {w} × {h} pixeles kép túl nagy a módosításhoz +@msg select an image with a color mask jelölj ki egy színmaszkos képet +@msg the color mask's settings are out of range a színmaszk beállításai a tartományon kívül esnek +@msg a CMYK image can't take a color mask CMYK képre nem tehető színmaszk +@msg the mask would hide every pixel a maszk minden képpontot elrejtene @msg select an Image Trace object jelölj ki egy képvektorizálási objektumot @msg select an object in perspective jelölj ki egy perspektivikus objektumot @msg select artwork (or a colour group) to recolor jelölj ki átszínezendő grafikát (vagy színcsoportot) @@ -5861,6 +5869,7 @@ imageTrace Outline Körvonal @msg unknown parameter `{path}`; it takes: {keys} ismeretlen paraméter: `{path}`; ezeket fogadja el: {keys} @msg missing `{path}` hiányzik: `{path}` @msg `{path}` must be {expected}, not {got} `{path}`: {expected} kell, nem ez: {got} +@msg `{path}` is nested too deeply `{path}` túl mélyen van egymásba ágyazva Load EPS into Clipboard EPS betöltése a vágólapra @msg an image of {w} × {h} pixels is too large to draw egy {w} × {h} pixeles kép túl nagy a kirajzoláshoz @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: nem PNG, JPEG, WebP, TIFF vagy BMP kép @@ -6406,6 +6415,16 @@ axis Y Axis Y tengely @msg Batch cannot play an action with a stop A kötegelt feldolgozás nem játszhat le megállást tartalmazó műveletet Insert Menu Item… Menüelem beszúrása… Insert Menu Item Menüelem beszúrása + Select Object… Objektum kijelölése… + Select Object Objektum kijelölése + Set Selection Kijelölés beállítása + Case Sensitive Kis- és nagybetűk megkülönböztetése + Whole Word Teljes szó + Select Object: {note} Objektum kijelölése: {note} + Select by Note Kijelölés megjegyzés szerint +@msg the note is empty a megjegyzés üres +@msg the note is longer than 1,024 bytes a megjegyzés hosszabb 1024 bájtnál +@msg no object that can be selected has a note matching “{query}” egyetlen kijelölhető objektum megjegyzése sem egyezik ezzel: „{query}” Menu Item: Menüelem: No menu item matches. Egy menüelem sem egyezik. Several menu items match. Choose one from the list. Több menüelem is egyezik. Válasszon egyet a listából. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 60d630e34e..16303f38f5 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -199,6 +199,10 @@ Corner Color Warna sudut Contiguous Bersambung Each Channel Setiap kanal + Color Mask… Masker warna… + Color Mask Masker warna + Remove Color Mask Hapus masker warna + Apply Color Mask Terapkan masker warna Edit Path Edit jalur Mask Masker Rasterize… Rasterisasi… @@ -5999,6 +6003,16 @@ axis Y Axis Sumbu Y @msg Batch cannot play an action with a stop Batch tidak dapat memutar tindakan dengan titik henti Insert Menu Item… Sisipkan item menu… Insert Menu Item Sisipkan item menu + Select Object… Pilih objek… + Select Object Pilih objek + Set Selection Atur seleksi + Case Sensitive Peka huruf besar/kecil + Whole Word Seluruh kata + Select Object: {note} Pilih objek: {note} + Select by Note Pilih berdasarkan catatan +@msg the note is empty catatan kosong +@msg the note is longer than 1,024 bytes catatan lebih panjang dari 1.024 byte +@msg no object that can be selected has a note matching “{query}” tidak ada objek yang dapat dipilih dengan catatan yang cocok dengan “{query}” Menu Item: Item menu: No menu item matches. Tidak ada item menu yang cocok. Several menu items match. Choose one from the list. Beberapa item menu cocok. Pilih salah satu dari daftar. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b4cb483859..be83d78b43 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -710,6 +710,10 @@ font-technology Variable Variabili Corner Color Colore degli angoli Contiguous Contiguo Each Channel Ogni canale + Color Mask… Maschera colore… + Color Mask Maschera colore + Remove Color Mask Rimuovi maschera colore + Apply Color Mask Applica maschera colore Edit Path Modifica tracciato Mask Maschera Crop Marks Segni di ritaglio @@ -4839,6 +4843,10 @@ axis Both Entrambi @msg a CMYK image has no transparency to set un'immagine CMYK non ha trasparenza da impostare @msg every pixel matches the background: no image would be left ogni pixel corrisponde allo sfondo: non resterebbe alcuna immagine @msg an image of {w} × {h} pixels is too large to change un'immagine di {w} × {h} pixel è troppo grande per essere modificata +@msg select an image with a color mask seleziona un'immagine con una maschera colore +@msg the color mask's settings are out of range le impostazioni della maschera colore sono fuori intervallo +@msg a CMYK image can't take a color mask un'immagine CMYK non può avere una maschera colore +@msg the mask would hide every pixel la maschera nasconderebbe ogni pixel @msg select an object in perspective seleziona un oggetto in prospettiva @msg select artwork (or a colour group) to recolor seleziona la grafica (o un gruppo colori) da ricolorare @msg Recolor completed; {locked} and {hidden} were left unchanged Ricolorazione completata; senza modifiche: {locked} e {hidden} @@ -5495,6 +5503,7 @@ lighting Light Luce @msg unknown parameter `{path}`; it takes: {keys} parametro sconosciuto `{path}`; accetta: {keys} @msg missing `{path}` manca `{path}` @msg `{path}` must be {expected}, not {got} `{path}` deve essere {expected}, non {got} +@msg `{path}` is nested too deeply `{path}` è annidato troppo in profondità Load EPS into Clipboard Carica EPS negli appunti @msg an image of {w} × {h} pixels is too large to draw un'immagine di {w} × {h} pixel è troppo grande per essere disegnata @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: non è un'immagine PNG, JPEG, WebP, TIFF o BMP @@ -6048,6 +6057,16 @@ axis Y Axis Asse Y @msg Batch cannot play an action with a stop L'elaborazione batch non può eseguire un'azione con un'interruzione Insert Menu Item… Inserisci voce di menu… Insert Menu Item Inserisci voce di menu + Select Object… Seleziona oggetto… + Select Object Seleziona oggetto + Set Selection Imposta selezione + Case Sensitive Maiuscole/minuscole + Whole Word Parola intera + Select Object: {note} Seleziona oggetto: {note} + Select by Note Seleziona per nota +@msg the note is empty la nota è vuota +@msg the note is longer than 1,024 bytes la nota supera 1.024 byte +@msg no object that can be selected has a note matching “{query}” nessun oggetto selezionabile ha una nota corrispondente a “{query}” Menu Item: Voce di menu: No menu item matches. Nessuna voce di menu corrisponde. Several menu items match. Choose one from the list. Corrispondono più voci di menu. Sceglierne una dall’elenco. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index a744839d5a..b27c6d2698 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -243,6 +243,10 @@ digits Malayalam マラヤーラム数字 Corner Color 角の色 Contiguous 隣接 Each Channel 各チャンネル + Color Mask… カラーマスク… + Color Mask カラーマスク + Remove Color Mask カラーマスクを削除 + Apply Color Mask カラーマスクを適用 Edit Path パスを編集 Mask マスク Rasterize… ラスタライズ… @@ -4963,6 +4967,10 @@ swatch Bright Violet ビビッドバイオレット @msg a CMYK image has no transparency to set CMYK 画像には設定できる透明部分がありません @msg every pixel matches the background: no image would be left すべてのピクセルが背景に一致します: 画像が残りません @msg an image of {w} × {h} pixels is too large to change {w} × {h} ピクセルの画像は大きすぎて変更できません +@msg select an image with a color mask カラーマスクのある画像を選択してください +@msg the color mask's settings are out of range カラーマスクの設定が範囲外です +@msg a CMYK image can't take a color mask CMYK 画像にはカラーマスクを設定できません +@msg the mask would hide every pixel マスクがすべてのピクセルを隠してしまいます @msg the document has no artboards ドキュメントにアートボードがありません @msg tool (a tool id) is required tool (ツール ID) を指定してください @msg unknown tool `{t}` `{t}` は不明なツールです @@ -5537,6 +5545,7 @@ lighting Light ライト @msg unknown parameter `{path}`; it takes: {keys} `{path}` は不明なパラメーターです。使えるパラメーター: {keys} @msg missing `{path}` `{path}` が指定されていません @msg `{path}` must be {expected}, not {got} `{path}` は {expected} にしてください ({got} は使えません) +@msg `{path}` is nested too deeply `{path}` の入れ子が深すぎます Load EPS into Clipboard EPS をクリップボードに読み込む @msg an image of {w} × {h} pixels is too large to draw {w} × {h} ピクセルの画像は大きすぎて描画できません @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: PNG、JPEG、WebP、TIFF、BMP のいずれの画像でもありません @@ -6113,6 +6122,16 @@ axis Y Axis Y 軸 @msg Batch cannot play an action with a stop バッチでは停止を含むアクションを再生できません Insert Menu Item… メニュー項目を挿入… Insert Menu Item メニュー項目を挿入 + Select Object… オブジェクトを選択… + Select Object オブジェクトを選択 + Set Selection 選択範囲を設定 + Case Sensitive 大文字と小文字を区別 + Whole Word 単語単位 + Select Object: {note} オブジェクトを選択: {note} + Select by Note メモで選択 +@msg the note is empty メモが空です +@msg the note is longer than 1,024 bytes メモが 1,024 バイトを超えています +@msg no object that can be selected has a note matching “{query}” 「{query}」に一致するメモを持つ選択可能なオブジェクトはありません Menu Item: メニュー項目: No menu item matches. 一致するメニュー項目がありません。 Several menu items match. Choose one from the list. 複数のメニュー項目が一致します。リストから 1 つ選択してください。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 944416e1ac..4ba40baab0 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -171,6 +171,10 @@ Corner Color კუთხეების ფერი Contiguous მომიჯნავე Each Channel თითოეული არხი + Color Mask… ფერის ნიღაბი… + Color Mask ფერის ნიღაბი + Remove Color Mask ფერის ნიღბის მოშორება + Apply Color Mask ფერის ნიღბის გამოყენება Mask ნიღაბი Rasterize… რასტრირება… Create Gradient Mesh… გრადიენტული ბადის შექმნა… @@ -4454,6 +4458,10 @@ font-technology Variable ცვლადი @msg a CMYK image has no transparency to set CMYK გამოსახულებას არ აქვს დასაყენებელი გამჭვირვალობა @msg every pixel matches the background: no image would be left ყველა პიქსელი ემთხვევა ფონს: გამოსახულება აღარ დარჩებოდა @msg an image of {w} × {h} pixels is too large to change {w} × {h} პიქსელის გამოსახულება შესაცვლელად ზედმეტად დიდია +@msg select an image with a color mask მონიშნეთ ფერის ნიღბიანი გამოსახულება +@msg the color mask's settings are out of range ფერის ნიღბის პარამეტრები დასაშვებ დიაპაზონს სცდება +@msg a CMYK image can't take a color mask CMYK გამოსახულებას ფერის ნიღაბი ვერ დაედება +@msg the mask would hide every pixel ნიღაბი ყველა პიქსელს დამალავდა @msg select an object in perspective მონიშნეთ ობიექტი პერსპექტივაში @msg select artwork (or a colour group) to recolor მონიშნეთ ხელახლა შესაფერადებელი ნახატი (ან ფერთა ჯგუფი) @msg Recolor completed; {locked} and {hidden} were left unchanged ხელახლა შეფერადება დასრულდა; უცვლელი დარჩა: {locked} და {hidden} @@ -5166,6 +5174,7 @@ font-technology Variable ცვლადი @msg unknown parameter `{path}`; it takes: {keys} უცნობი პარამეტრი `{path}`; იღებს: {keys} @msg missing `{path}` აკლია `{path}` @msg `{path}` must be {expected}, not {got} `{path}` უნდა იყოს {expected} და არა {got} +@msg `{path}` is nested too deeply `{path}` ზედმეტად ღრმადაა ჩადგმული file-filter All readable files ყველა წაკითხვადი ფაილი file-filter All placeable files ყველა განთავსებადი ფაილი file-filter Swatch libraries ფერის ნიმუშების ბიბლიოთეკები @@ -6374,6 +6383,16 @@ axis Y Axis Y ღერძი @msg Batch cannot play an action with a stop პაკეტურ დამუშავებას არ შეუძლია გაჩერების მქონე მოქმედების შესრულება Insert Menu Item… მენიუს ელემენტის ჩასმა… Insert Menu Item მენიუს ელემენტის ჩასმა + Select Object… ობიექტის მონიშვნა… + Select Object ობიექტის მონიშვნა + Set Selection მონიშვნის დაყენება + Case Sensitive რეგისტრის გათვალისწინება + Whole Word მთელი სიტყვა + Select Object: {note} ობიექტის მონიშვნა: {note} + Select by Note მონიშვნა შენიშვნის მიხედვით +@msg the note is empty შენიშვნა ცარიელია +@msg the note is longer than 1,024 bytes შენიშვნა 1024 ბაიტზე გრძელია +@msg no object that can be selected has a note matching “{query}” არცერთ მოსანიშნ ობიექტს არ აქვს შენიშვნა, რომელიც ემთხვევა „{query}“-ს Menu Item: მენიუს ელემენტი: No menu item matches. მენიუს არცერთი ელემენტი არ ემთხვევა. Several menu items match. Choose one from the list. ემთხვევა მენიუს რამდენიმე ელემენტი. აირჩიეთ ერთი სიიდან. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4594e9aceb..c46ce6b4fa 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -236,6 +236,10 @@ digits Malayalam 말라얄람어 Corner Color 모퉁이 색상 Contiguous 인접 Each Channel 각 채널 + Color Mask… 색상 마스크… + Color Mask 색상 마스크 + Remove Color Mask 색상 마스크 제거 + Apply Color Mask 색상 마스크 적용 Edit Path 패스 편집 Mask 마스크 Rasterize… 래스터화… @@ -4890,6 +4894,10 @@ theme Appearance 외관 @msg a CMYK image has no transparency to set CMYK 이미지에는 설정할 투명도가 없습니다 @msg every pixel matches the background: no image would be left 모든 픽셀이 배경과 일치합니다: 남는 이미지가 없습니다 @msg an image of {w} × {h} pixels is too large to change {w} × {h}픽셀 이미지는 너무 커서 변경할 수 없습니다 +@msg select an image with a color mask 색상 마스크가 있는 이미지를 선택하세요 +@msg the color mask's settings are out of range 색상 마스크 설정이 범위를 벗어났습니다 +@msg a CMYK image can't take a color mask CMYK 이미지에는 색상 마스크를 적용할 수 없습니다 +@msg the mask would hide every pixel 마스크가 모든 픽셀을 숨기게 됩니다 @msg the document has no artboards 문서에 아트보드가 없습니다 @msg tool (a tool id) is required 도구(도구 id)가 필요합니다 @msg unknown tool `{t}` 알 수 없는 도구 `{t}` @@ -5456,6 +5464,7 @@ lighting Light 광원 @msg unknown parameter `{path}`; it takes: {keys} 알 수 없는 매개변수 `{path}`: 받는 매개변수: {keys} @msg missing `{path}` `{path}`이(가) 없습니다 @msg `{path}` must be {expected}, not {got} `{path}`은(는) {expected}이어야 합니다({got} 사용 불가) +@msg `{path}` is nested too deeply `{path}`이(가) 너무 깊게 중첩되어 있습니다 Load EPS into Clipboard EPS를 클립보드로 불러오기 @msg an image of {w} × {h} pixels is too large to draw {w} × {h}픽셀 이미지는 너무 커서 그릴 수 없습니다 @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: PNG, JPEG, WebP, TIFF 또는 BMP 이미지가 아닙니다 @@ -6009,6 +6018,16 @@ axis Y Axis Y축 @msg Batch cannot play an action with a stop 일괄 처리에서는 중지가 있는 액션을 재생할 수 없습니다 Insert Menu Item… 메뉴 항목 삽입… Insert Menu Item 메뉴 항목 삽입 + Select Object… 개체 선택… + Select Object 개체 선택 + Set Selection 선택 영역 설정 + Case Sensitive 대/소문자 구분 + Whole Word 전체 단어 + Select Object: {note} 개체 선택: {note} + Select by Note 참고로 선택 +@msg the note is empty 참고가 비어 있습니다 +@msg the note is longer than 1,024 bytes 참고가 1,024바이트보다 깁니다 +@msg no object that can be selected has a note matching “{query}” 선택할 수 있는 개체 중 참고가 “{query}”와(과) 일치하는 개체가 없습니다 Menu Item: 메뉴 항목: No menu item matches. 일치하는 메뉴 항목이 없습니다. Several menu items match. Choose one from the list. 여러 메뉴 항목이 일치합니다. 목록에서 하나를 선택하세요. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 895ac0f317..a19e190ed6 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -213,6 +213,10 @@ Corner Color Hoekkleur Contiguous Aaneengesloten Each Channel Elk kanaal + Color Mask… Kleurmasker… + Color Mask Kleurmasker + Remove Color Mask Kleurmasker verwijderen + Apply Color Mask Kleurmasker toepassen Edit Path Pad bewerken Mask Masker Rasterize… Rasteriseren… @@ -6050,6 +6054,16 @@ axis Y Axis Y-as @msg Batch cannot play an action with a stop Batch kan geen actie met een stop afspelen Insert Menu Item… Menu-item invoegen… Insert Menu Item Menu-item invoegen + Select Object… Object selecteren… + Select Object Object selecteren + Set Selection Selectie instellen + Case Sensitive Hoofdlettergevoelig + Whole Word Heel woord + Select Object: {note} Object selecteren: {note} + Select by Note Selecteren op notitie +@msg the note is empty de notitie is leeg +@msg the note is longer than 1,024 bytes de notitie is langer dan 1024 bytes +@msg no object that can be selected has a note matching “{query}” geen selecteerbaar object heeft een notitie die overeenkomt met „{query}” Menu Item: Menu-item: No menu item matches. Geen menu-item komt overeen. Several menu items match. Choose one from the list. Meerdere menu-items komen overeen. Kies er een uit de lijst. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f16275650f..a232ac4e8d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -176,6 +176,10 @@ Corner Color Kolor narożników Contiguous Ciągły Each Channel Każdy kanał + Color Mask… Maska koloru… + Color Mask Maska koloru + Remove Color Mask Usuń maskę koloru + Apply Color Mask Zastosuj maskę koloru Edit Path Edytuj ścieżkę Mask Maska Rasterize… Rasteryzuj… @@ -4922,6 +4926,10 @@ imageTrace Outline Kontur @msg a CMYK image has no transparency to set obraz CMYK nie ma przezroczystości, którą można ustawić @msg every pixel matches the background: no image would be left każdy piksel pasuje do tła: nie zostałby żaden obraz @msg an image of {w} × {h} pixels is too large to change obraz o wymiarach {w} × {h} pikseli jest zbyt duży, aby go zmienić +@msg select an image with a color mask zaznacz obraz z maską koloru +@msg the color mask's settings are out of range ustawienia maski koloru są poza zakresem +@msg a CMYK image can't take a color mask obraz CMYK nie może mieć maski koloru +@msg the mask would hide every pixel maska ukryłaby każdy piksel @msg select an object in perspective zaznacz obiekt w perspektywie @msg select artwork (or a colour group) to recolor zaznacz kompozycję (lub grupę kolorów), aby zmienić kolory @msg Recolor completed; {locked} and {hidden} were left unchanged Zmiana kolorów zakończona; bez zmian: {locked} i {hidden} @@ -5717,6 +5725,7 @@ mark-style Japanese Japońskie @msg unknown parameter `{path}`; it takes: {keys} nieznany parametr `{path}`; przyjmuje: {keys} @msg missing `{path}` brak `{path}` @msg `{path}` must be {expected}, not {got} `{path}` musi być {expected}, a nie {got} +@msg `{path}` is nested too deeply `{path}` jest zagnieżdżone zbyt głęboko Load EPS into Clipboard Wczytaj EPS do schowka @msg an image of {w} × {h} pixels is too large to draw obraz o wymiarach {w} × {h} pikseli jest zbyt duży, aby go narysować @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: to nie jest obraz PNG, JPEG, WebP, TIFF ani BMP @@ -6277,6 +6286,16 @@ axis Y Axis Oś Y @msg Batch cannot play an action with a stop Przetwarzanie wsadowe nie może odtworzyć operacji z zatrzymaniem Insert Menu Item… Wstaw polecenie menu… Insert Menu Item Wstaw polecenie menu + Select Object… Zaznacz obiekt… + Select Object Zaznacz obiekt + Set Selection Ustaw zaznaczenie + Case Sensitive Uwzględniaj wielkość liter + Whole Word Całe słowo + Select Object: {note} Zaznacz obiekt: {note} + Select by Note Zaznacz według notatki +@msg the note is empty notatka jest pusta +@msg the note is longer than 1,024 bytes notatka jest dłuższa niż 1024 bajty +@msg no object that can be selected has a note matching “{query}” żaden obiekt, który można zaznaczyć, nie ma notatki pasującej do „{query}” Menu Item: Polecenie menu: No menu item matches. Żadne polecenie menu nie pasuje. Several menu items match. Choose one from the list. Pasuje kilka poleceń menu. Wybierz jedno z listy. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index ab7ff88ff2..68a225625d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -636,6 +636,10 @@ antiAlias Sharp Nítido Corner Color Cor dos Cantos Contiguous Contíguo Each Channel Cada Canal + Color Mask… Máscara de Cor… + Color Mask Máscara de Cor + Remove Color Mask Remover Máscara de Cor + Apply Color Mask Aplicar Máscara de Cor Edit Path Editar caminho Mask Máscara Crop Marks Marcas de Corte @@ -4244,6 +4248,10 @@ axis Both Ambos @msg a CMYK image has no transparency to set uma imagem CMYK não tem transparência para definir @msg every pixel matches the background: no image would be left todos os pixels correspondem ao fundo: nenhuma imagem restaria @msg an image of {w} × {h} pixels is too large to change uma imagem de {w} × {h} pixels é grande demais para ser alterada +@msg select an image with a color mask selecione uma imagem com uma máscara de cor +@msg the color mask's settings are out of range as configurações da máscara de cor estão fora do intervalo +@msg a CMYK image can't take a color mask uma imagem CMYK não pode ter uma máscara de cor +@msg the mask would hide every pixel a máscara ocultaria todos os pixels @msg select an object in perspective selecione um objeto em perspectiva @msg select artwork (or a colour group) to recolor selecione uma arte-final (ou um grupo de cores) para recolorir @msg Recolor completed; {locked} and {hidden} were left unchanged Recoloração concluída; sem alteração: {locked} e {hidden} @@ -4672,6 +4680,7 @@ axis Both Ambos @msg unknown parameter `{path}`; it takes: {keys} parâmetro desconhecido `{path}`; aceita: {keys} @msg missing `{path}` falta `{path}` @msg `{path}` must be {expected}, not {got} `{path}` deve ser {expected}, não {got} +@msg `{path}` is nested too deeply `{path}` está aninhado com profundidade excessiva Load EPS into Clipboard Carregar EPS na Área de Transferência Drawer menu Menu da gaveta Toolbar: Show Controls Barra de ferramentas: Mostrar controles @@ -6338,6 +6347,16 @@ axis Y Axis Eixo Y @msg Batch cannot play an action with a stop Lote não pode reproduzir uma ação com uma parada Insert Menu Item… Inserir Item de Menu… Insert Menu Item Inserir Item de Menu + Select Object… Selecionar Objeto… + Select Object Selecionar Objeto + Set Selection Definir Seleção + Case Sensitive Diferenciar Maiúsculas e Minúsculas + Whole Word Palavra Inteira + Select Object: {note} Selecionar Objeto: {note} + Select by Note Selecionar por Nota +@msg the note is empty a nota está vazia +@msg the note is longer than 1,024 bytes a nota tem mais de 1.024 bytes +@msg no object that can be selected has a note matching “{query}” nenhum objeto que pode ser selecionado tem uma nota correspondente a “{query}” Menu Item: Item de menu: No menu item matches. Nenhum item de menu corresponde. Several menu items match. Choose one from the list. Vários itens de menu correspondem. Escolha um da lista. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 2873141bd8..a54d1eed2c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -708,6 +708,10 @@ font-technology Variable Вариативные Corner Color Цвет углов Contiguous Смежные Each Channel Каждый канал + Color Mask… Цветовая маска… + Color Mask Цветовая маска + Remove Color Mask Удалить цветовую маску + Apply Color Mask Применить цветовую маску Edit Path Редактировать контур Mask Маска Crop Marks Метки обрезки @@ -4825,6 +4829,10 @@ axis Both Оба @msg a CMYK image has no transparency to set у изображения CMYK нет прозрачности, которую можно задать @msg every pixel matches the background: no image would be left каждый пиксель совпадает с фоном: от изображения ничего не осталось бы @msg an image of {w} × {h} pixels is too large to change изображение размером {w} × {h} пикселей слишком велико для изменения +@msg select an image with a color mask выделите изображение с цветовой маской +@msg the color mask's settings are out of range настройки цветовой маски вне допустимого диапазона +@msg a CMYK image can't take a color mask к изображению CMYK нельзя применить цветовую маску +@msg the mask would hide every pixel маска скрыла бы все пиксели @msg select an object in perspective выделите объект в перспективе @msg select artwork (or a colour group) to recolor выделите рисунок (или цветовую группу) для перекрашивания @msg Recolor completed; {locked} and {hidden} were left unchanged Перекрашивание завершено; без изменений: {locked} и {hidden} @@ -5481,6 +5489,7 @@ lighting Light Свет @msg unknown parameter `{path}`; it takes: {keys} неизвестный параметр `{path}`; принимает: {keys} @msg missing `{path}` отсутствует `{path}` @msg `{path}` must be {expected}, not {got} `{path}` должно быть {expected}, а не {got} +@msg `{path}` is nested too deeply `{path}` вложено слишком глубоко Load EPS into Clipboard Загрузить EPS в буфер обмена @msg an image of {w} × {h} pixels is too large to draw изображение размером {w} × {h} пикселей слишком велико для отрисовки @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: это не изображение PNG, JPEG, WebP, TIFF или BMP @@ -6034,6 +6043,16 @@ axis Y Axis Ось Y @msg Batch cannot play an action with a stop Пакет не может воспроизвести действие с остановкой Insert Menu Item… Вставить пункт меню… Insert Menu Item Вставить пункт меню + Select Object… Выделить объект… + Select Object Выделить объект + Set Selection Задать выделение + Case Sensitive С учетом регистра + Whole Word Слово целиком + Select Object: {note} Выделить объект: {note} + Select by Note Выделить по примечанию +@msg the note is empty примечание пустое +@msg the note is longer than 1,024 bytes примечание длиннее 1024 байт +@msg no object that can be selected has a note matching “{query}” ни у одного объекта, который можно выделить, нет примечания, совпадающего с «{query}» Menu Item: Пункт меню: No menu item matches. Нет подходящих пунктов меню. Several menu items match. Choose one from the list. Подходит несколько пунктов меню. Выберите один из списка. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6a3dadae87..d0648b5946 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -698,6 +698,10 @@ font-technology Variable Variabla Corner Color Hörnfärg Contiguous Sammanhängande Each Channel Varje kanal + Color Mask… Färgmask… + Color Mask Färgmask + Remove Color Mask Ta bort färgmask + Apply Color Mask Tillämpa färgmask Edit Path Redigera bana Mask Maskera Crop Marks Skärmärken @@ -4683,6 +4687,10 @@ axis Both Båda @msg a CMYK image has no transparency to set en CMYK-bild har ingen transparens att ställa in @msg every pixel matches the background: no image would be left varje pixel matchar bakgrunden: ingen bild skulle bli kvar @msg an image of {w} × {h} pixels is too large to change en bild på {w} × {h} pixlar är för stor för att ändras +@msg select an image with a color mask markera en bild med en färgmask +@msg the color mask's settings are out of range färgmaskens inställningar ligger utanför intervallet +@msg a CMYK image can't take a color mask en CMYK-bild kan inte ha en färgmask +@msg the mask would hide every pixel masken skulle dölja varje pixel @msg select an object in perspective markera ett objekt i perspektiv @msg select artwork (or a colour group) to recolor markera grafik (eller en färggrupp) att färga om @msg Recolor completed; {locked} and {hidden} were left unchanged Omfärgning klar; utan ändring: {locked} och {hidden} @@ -5349,6 +5357,7 @@ lighting Light Ljus @msg unknown parameter `{path}`; it takes: {keys} okänd parameter `{path}`; den tar: {keys} @msg missing `{path}` `{path}` saknas @msg `{path}` must be {expected}, not {got} `{path}` måste vara {expected}, inte {got} +@msg `{path}` is nested too deeply `{path}` är för djupt kapslat 1 Layer 1 lager 1 bit 1 bit 16 Colors 16 färger @@ -6404,6 +6413,16 @@ axis Y Axis Y-axel @msg Batch cannot play an action with a stop Batch kan inte spela upp en åtgärd med ett stopp Insert Menu Item… Infoga menyalternativ… Insert Menu Item Infoga menyalternativ + Select Object… Markera objekt… + Select Object Markera objekt + Set Selection Ange markering + Case Sensitive Skiftlägeskänslig + Whole Word Helt ord + Select Object: {note} Markera objekt: {note} + Select by Note Markera efter anteckning +@msg the note is empty anteckningen är tom +@msg the note is longer than 1,024 bytes anteckningen är längre än 1 024 byte +@msg no object that can be selected has a note matching “{query}” inget objekt som kan markeras har en anteckning som matchar ”{query}” Menu Item: Menyalternativ: No menu item matches. Inget menyalternativ matchar. Several menu items match. Choose one from the list. Flera menyalternativ matchar. Välj ett i listan. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 1d3384356b..915a244b43 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -690,6 +690,10 @@ font-technology Variable Değişken Corner Color Köşe Rengi Contiguous Bitişik Each Channel Her Kanal + Color Mask… Renk Maskesi… + Color Mask Renk Maskesi + Remove Color Mask Renk Maskesini Kaldır + Apply Color Mask Renk Maskesini Uygula Mask Maske Crop Marks Kırpma İşaretleri Crop To Kırpma Hedefi @@ -4536,6 +4540,10 @@ axis Both Her İkisi @msg a CMYK image has no transparency to set CMYK görüntüsünde ayarlanacak saydamlık yok @msg every pixel matches the background: no image would be left her piksel arka planla eşleşiyor: hiç görüntü kalmaz @msg an image of {w} × {h} pixels is too large to change {w} × {h} piksellik bir görüntü değiştirilemeyecek kadar büyük +@msg select an image with a color mask renk maskesi olan bir resim seç +@msg the color mask's settings are out of range renk maskesinin ayarları izin verilen aralığın dışında +@msg a CMYK image can't take a color mask CMYK görüntüsüne renk maskesi uygulanamaz +@msg the mask would hide every pixel maske her pikseli gizlerdi @msg select an object in perspective perspektifte bir nesne seç @msg select artwork (or a colour group) to recolor yeniden renklendirilecek resmi (veya bir renk grubunu) seçin @msg Recolor completed; {locked} and {hidden} were left unchanged Yeniden renklendirme tamamlandı; değiştirilmeden kalan: {locked} ve {hidden} @@ -5144,6 +5152,7 @@ lighting Light Işık @msg unknown parameter `{path}`; it takes: {keys} bilinmeyen parametre `{path}`; şunları alır: {keys} @msg missing `{path}` `{path}` eksik @msg `{path}` must be {expected}, not {got} `{path}` {expected} olmalıdır, {got} değil +@msg `{path}` is nested too deeply `{path}` çok derin iç içe geçmiş 1 Layer 1 Katman 1 bit 1 bit 16 Colors 16 Renk @@ -6379,6 +6388,16 @@ axis Y Axis Y ekseni @msg Batch cannot play an action with a stop Toplu işlem durak içeren bir eylemi oynatamaz Insert Menu Item… Menü Öğesi Ekle… Insert Menu Item Menü Öğesi Ekle + Select Object… Nesne Seç… + Select Object Nesne Seç + Set Selection Seçimi Ayarla + Case Sensitive Büyük/Küçük Harfe Duyarlı + Whole Word Tam Sözcük + Select Object: {note} Nesne Seç: {note} + Select by Note Nota Göre Seç +@msg the note is empty not boş +@msg the note is longer than 1,024 bytes not 1.024 bayttan uzun +@msg no object that can be selected has a note matching “{query}” seçilebilen hiçbir nesnenin notu “{query}” ile eşleşmiyor Menu Item: Menü öğesi: No menu item matches. Eşleşen menü öğesi yok. Several menu items match. Choose one from the list. Birden çok menü öğesi eşleşiyor. Listeden birini seçin. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 675a7e6e7d..e8b5445a50 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -704,6 +704,10 @@ font-technology Variable Варіативні Corner Color Колір кутів Contiguous Суміжні Each Channel Кожен канал + Color Mask… Колірна маска… + Color Mask Колірна маска + Remove Color Mask Видалити колірну маску + Apply Color Mask Застосувати колірну маску Edit Path Редагувати контур Mask Маска Crop Marks Мітки обрізання @@ -4823,6 +4827,10 @@ axis Both Обидві @msg a CMYK image has no transparency to set зображення CMYK не має прозорості, яку можна задати @msg every pixel matches the background: no image would be left кожен піксель збігається з фоном: від зображення нічого не залишилося б @msg an image of {w} × {h} pixels is too large to change зображення розміром {w} × {h} пікселів завелике для зміни +@msg select an image with a color mask виділіть зображення з колірною маскою +@msg the color mask's settings are out of range параметри колірної маски поза допустимим діапазоном +@msg a CMYK image can't take a color mask до зображення CMYK не можна застосувати колірну маску +@msg the mask would hide every pixel маска приховала б усі пікселі @msg select an object in perspective виділіть об’єкт у перспективі @msg select artwork (or a colour group) to recolor виділіть малюнок (або колірну групу) для перефарбовування @msg Recolor completed; {locked} and {hidden} were left unchanged Перефарбовування завершено; без змін: {locked} і {hidden} @@ -5475,6 +5483,7 @@ lighting Light Світло @msg unknown parameter `{path}`; it takes: {keys} невідомий параметр `{path}`; приймає: {keys} @msg missing `{path}` відсутнє `{path}` @msg `{path}` must be {expected}, not {got} `{path}` має бути {expected}, а не {got} +@msg `{path}` is nested too deeply `{path}` вкладено надто глибоко Load EPS into Clipboard Завантажити EPS у буфер обміну @msg an image of {w} × {h} pixels is too large to draw зображення розміром {w} × {h} пікселів завелике для відображення @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: це не зображення PNG, JPEG, WebP, TIFF чи BMP @@ -6028,6 +6037,16 @@ axis Y Axis Вісь Y @msg Batch cannot play an action with a stop Пакет не може відтворити дію із зупинкою Insert Menu Item… Вставити пункт меню… Insert Menu Item Вставити пункт меню + Select Object… Виділити об’єкт… + Select Object Виділити об’єкт + Set Selection Задати виділення + Case Sensitive З урахуванням регістру + Whole Word Ціле слово + Select Object: {note} Виділити об’єкт: {note} + Select by Note Виділити за приміткою +@msg the note is empty примітка порожня +@msg the note is longer than 1,024 bytes примітка довша за 1024 байти +@msg no object that can be selected has a note matching “{query}” жоден об’єкт, який можна виділити, не має примітки, що збігається з «{query}» Menu Item: Пункт меню: No menu item matches. Немає відповідних пунктів меню. Several menu items match. Choose one from the list. Відповідає кілька пунктів меню. Виберіть один зі списку. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index cfe4dc68b1..51681bfed5 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -811,6 +811,10 @@ font-technology Variable Biến thiên Corner Color Màu góc Contiguous Liền kề Each Channel Từng kênh + Color Mask… Mặt nạ màu… + Color Mask Mặt nạ màu + Remove Color Mask Xóa mặt nạ màu + Apply Color Mask Áp dụng mặt nạ màu Edit Path Sửa đường dẫn Crop Marks Dấu cắt xén Crop To Cắt xén đến @@ -5202,6 +5206,10 @@ theme Appearance Giao diện @msg a CMYK image has no transparency to set ảnh CMYK không có độ trong suốt để đặt @msg every pixel matches the background: no image would be left mọi điểm ảnh đều khớp với nền: sẽ không còn lại ảnh nào @msg an image of {w} × {h} pixels is too large to change ảnh {w} × {h} điểm ảnh quá lớn nên không thể thay đổi +@msg select an image with a color mask hãy chọn ảnh có mặt nạ màu +@msg the color mask's settings are out of range cài đặt của mặt nạ màu nằm ngoài phạm vi cho phép +@msg a CMYK image can't take a color mask ảnh CMYK không thể có mặt nạ màu +@msg the mask would hide every pixel mặt nạ sẽ ẩn mọi điểm ảnh @msg select an Image Trace object hãy chọn đối tượng vector hóa ảnh @msg select an object in perspective hãy chọn đối tượng trong phối cảnh @msg select artwork (or a colour group) to recolor hãy chọn tác phẩm (hoặc nhóm màu) để tô lại @@ -5389,6 +5397,7 @@ theme Appearance Giao diện @msg unknown parameter `{path}`; it takes: {keys} tham số không xác định `{path}`; nhận: {keys} @msg missing `{path}` thiếu `{path}` @msg `{path}` must be {expected}, not {got} `{path}` phải là {expected}, không phải {got} +@msg `{path}` is nested too deeply `{path}` lồng nhau quá sâu @msg unknown preference `{key}` tùy chọn không xác định `{key}` @msg Preferences imported. Đã nhập tùy chọn. @msg not a preferences file: {e} không phải tệp tùy chọn: {e} @@ -6029,6 +6038,16 @@ axis Y Axis Trục Y @msg Batch cannot play an action with a stop Hàng loạt không thể phát hành động có điểm dừng Insert Menu Item… Chèn mục menu… Insert Menu Item Chèn mục menu + Select Object… Chọn đối tượng… + Select Object Chọn đối tượng + Set Selection Đặt vùng chọn + Case Sensitive Phân biệt chữ hoa chữ thường + Whole Word Toàn bộ từ + Select Object: {note} Chọn đối tượng: {note} + Select by Note Chọn theo ghi chú +@msg the note is empty ghi chú trống +@msg the note is longer than 1,024 bytes ghi chú dài hơn 1.024 byte +@msg no object that can be selected has a note matching “{query}” không có đối tượng nào có thể chọn có ghi chú khớp với “{query}” Menu Item: Mục menu: No menu item matches. Không có mục menu nào khớp. Several menu items match. Choose one from the list. Có nhiều mục menu khớp. Hãy chọn một mục trong danh sách. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 81d82417b9..d1e4de6bc6 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -655,6 +655,10 @@ antiAlias Sharp 锐利 Corner Color 转角颜色 Contiguous 连续 Each Channel 每个通道 + Color Mask… 颜色蒙版… + Color Mask 颜色蒙版 + Remove Color Mask 移除颜色蒙版 + Apply Color Mask 应用颜色蒙版 Edit Path 编辑路径 Mask 蒙版 Crop Marks 裁切标记 @@ -4655,6 +4659,10 @@ imageTrace Outline 轮廓 @msg a CMYK image has no transparency to set CMYK 图像没有可设置的透明度 @msg every pixel matches the background: no image would be left 每个像素都与背景匹配:不会留下任何图像 @msg an image of {w} × {h} pixels is too large to change {w} × {h} 像素的图像过大,无法更改 +@msg select an image with a color mask 请选择一个带颜色蒙版的图像 +@msg the color mask's settings are out of range 颜色蒙版的设置超出范围 +@msg a CMYK image can't take a color mask CMYK 图像不能使用颜色蒙版 +@msg the mask would hide every pixel 蒙版会隐藏所有像素 @msg the document has no artboards 文档没有画板 @msg tool (a tool id) is required 需要 tool (工具 id) @msg unknown tool `{t}` 未知工具 `{t}` @@ -5751,6 +5759,7 @@ lighting Light 光源 @msg unknown parameter `{path}`; it takes: {keys} 未知参数 `{path}`;它接受:{keys} @msg missing `{path}` 缺少 `{path}` @msg `{path}` must be {expected}, not {got} `{path}` 必须是 {expected},而不是 {got} +@msg `{path}` is nested too deeply `{path}` 嵌套过深 Load EPS into Clipboard 将 EPS 载入剪贴板 @msg an image of {w} × {h} pixels is too large to draw {w} × {h} 像素的图像过大,无法绘制 @msg the JPEG XL file is cut short JPEG XL 文件不完整 @@ -6261,6 +6270,16 @@ axis Y Axis Y 轴 @msg Batch cannot play an action with a stop 批处理无法播放含有停止的动作 Insert Menu Item… 插入菜单项… Insert Menu Item 插入菜单项 + Select Object… 选择对象… + Select Object 选择对象 + Set Selection 设置选区 + Case Sensitive 区分大小写 + Whole Word 全字匹配 + Select Object: {note} 选择对象:{note} + Select by Note 按注释选择 +@msg the note is empty 注释为空 +@msg the note is longer than 1,024 bytes 注释超过 1,024 字节 +@msg no object that can be selected has a note matching “{query}” 没有可选对象的注释与“{query}”匹配 Menu Item: 菜单项: No menu item matches. 没有匹配的菜单项。 Several menu items match. Choose one from the list. 有多个菜单项匹配。请从列表中选择一个。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3f95d69c0c..8e49ed109a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -672,6 +672,10 @@ font-technology Variable 可變 Corner Color 轉角顏色 Contiguous 連續 Each Channel 每個通道 + Color Mask… 顏色遮色片… + Color Mask 顏色遮色片 + Remove Color Mask 移除顏色遮色片 + Apply Color Mask 套用顏色遮色片 Edit Path 編輯路徑 Mask 遮色片 Crop Marks 裁切標記 @@ -2424,6 +2428,10 @@ file-filter Templates 範本 @msg a CMYK image has no transparency to set CMYK 影像沒有可設定的透明度 @msg every pixel matches the background: no image would be left 每個像素都與背景相符:不會留下任何影像 @msg an image of {w} × {h} pixels is too large to change {w} × {h} 像素的影像過大,無法變更 +@msg select an image with a color mask 請選取帶有顏色遮色片的影像 +@msg the color mask's settings are out of range 顏色遮色片的設定超出範圍 +@msg a CMYK image can't take a color mask CMYK 影像無法使用顏色遮色片 +@msg the mask would hide every pixel 遮色片會隱藏所有像素 @msg the document has no artboards 文件沒有工作區域 @msg tool (a tool id) is required 需要 tool (工具 id) @msg unknown tool `{t}` 未知的工具 `{t}` @@ -5583,6 +5591,7 @@ lighting Light 光源 @msg unknown parameter `{path}`; it takes: {keys} 未知的參數 `{path}`;它接受:{keys} @msg missing `{path}` 未提供 `{path}` @msg `{path}` must be {expected}, not {got} `{path}` 必須是 {expected},而不是 {got} +@msg `{path}` is nested too deeply `{path}` 巢狀層級過深 Load EPS into Clipboard 將 EPS 載入剪貼簿 @msg an image of {w} × {h} pixels is too large to draw {w} × {h} 像素的影像過大,無法繪製 @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}:不是 PNG、JPEG、WebP、TIFF 或 BMP 影像 @@ -6066,6 +6075,16 @@ axis Y Axis Y 軸 @msg Batch cannot play an action with a stop 批次無法播放含有停止的動作 Insert Menu Item… 插入選單項目… Insert Menu Item 插入選單項目 + Select Object… 選取物件… + Select Object 選取物件 + Set Selection 設定選取範圍 + Case Sensitive 區分大小寫 + Whole Word 全字拼寫須相符 + Select Object: {note} 選取物件:{note} + Select by Note 依註解選取 +@msg the note is empty 註解是空的 +@msg the note is longer than 1,024 bytes 註解超過 1,024 位元組 +@msg no object that can be selected has a note matching “{query}” 沒有可選取物件的註解符合「{query}」 Menu Item: 選單項目: No menu item matches. 沒有相符的選單項目。 Several menu items match. Choose one from the list. 有多個選單項目相符。請從清單中選擇一個。 diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index ab530b803c..9d30b2a5b6 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -29,12 +29,13 @@ pub(crate) fn with_held_keys(target: (String, Value), held: egui::Modifiers) -> /// The dialog of command `id` that shows the selection's current values (its query): its heading /// and the queried values it doesn't show. Type on a Path Options leaves the brackets where they -/// are. +/// are. Color Mask opens on the selected image's mask settings (the defaults without one). fn queried_dialog(id: &str) -> Option<(&'static str, &'static [&'static str])> { Some(match id { // Whether the text overflows, and Shrink Text's factor, are read-only facts. "text.areaOptions" => ("Area Type Options", &["overflow", "fitScale"]), "type.pathOptions" => ("Type on a Path Options", &["start", "end"]), + crate::addons::image::COLOR_MASK => ("Color Mask", &["masked"]), _ => return None, }) } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index bf5490e4d8..964be00d61 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -516,13 +516,17 @@ fn run_ui_part5(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option flag(&mut app.ui.control_bar), "window.helpBar" => flag(&mut app.ui.help_bar), - // The Control bar's panel menu and gripper: the edge of the window the bar docks to. + // The Control bar's panel menu and gripper: the edge of the window the bar docks to, or + // floating over the window at the position it last floated at. "window.control.dock" => { let key = "edge"; let edges = crate::chrome::CONTROL_BAR_EDGES; match edges.iter().position(|e| s(key).as_deref() == Some(*e)) { Some(i) => { - app.ui.control_bar_bottom = i == 1; + app.ui.control_bar_floating = i == 2; + if i < 2 { + app.ui.control_bar_bottom = i == 1; + } Ok(json!({ key: edges[i] })) } None => Err(format!("`{key}` must be one of {}", edges.join(", "))), @@ -979,6 +983,7 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::actions::stop(app, p), crate::panels::actions::INSERT_STOP => crate::panels::actions::insert_stop(app, p), crate::panels::actions::INSERT_MENU_ITEM => crate::panels::actions::insert_menu_item(app, p), + crate::panels::actions::INSERT_SELECT_OBJECT => crate::panels::actions::insert_select_object(app, p), crate::panels::actions::CONTINUE_PLAYBACK => crate::panels::actions::continue_playback(app, p), crate::panels::actions::DELETE_STEP => crate::panels::actions::delete_step(app, p), "ui.batchDialog" => { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 20e4ba2a77..4e4da87380 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -63,9 +63,7 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { "view.rotate" => app.view().zip(p.get("angle").and_then(Value::as_f64)).is_some_and(|(view, a)| (view.rotation - a).abs() < 1e-9), "window.control" => app.ui.control_bar, "window.helpBar" => app.ui.help_bar, - "window.control.dock" => { - p.get("edge").and_then(Value::as_str) == Some(crate::chrome::CONTROL_BAR_EDGES[usize::from(app.ui.control_bar_bottom)]) - } + "window.control.dock" => p.get("edge").and_then(Value::as_str) == Some(crate::chrome::control_bar_placement(&app.ui)), "window.control.options" => p .get("group") .and_then(Value::as_str) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5b4d145bf8..08c1bbb4c6 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -470,7 +470,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.control.dock", "Dock Control Bar", "", - "{edge: \"top\"|\"bottom\"} dock the Control bar to the top of the window, under the menu bar, or to its bottom, as the bar's panel menu (Dock to Top, Dock to Bottom) and a drag of its gripper do; kept with the workspace; another edge is an error and changes nothing; returns {edge}", + "{edge: \"top\"|\"bottom\"|\"float\"} dock the Control bar to the top of the window, under the menu bar, or to its bottom, as the bar's panel menu (Dock to Top, Dock to Bottom) and a drag of its gripper do, or float it over the window at the position it last floated at (first: its top-left corner at 60, 80 in window points), as a gripper drag released away from both edges does; kept with the workspace; another edge is an error and changes nothing; returns {edge}", ), ( "window.control.options", @@ -1440,6 +1440,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{set?: index, action?: index, step?: index, command, params?: object} insert the command of a menu item as a step, without running it; the step plays as choosing the item runs it. command and params (default {}) must be those of a menu item that can be a step: one that runs an engine command, whose label does not end with \"…\", outside the VectorCraft, File, Window and Help menus, and that is not Undo, Redo, a Paste, a batch (command.batch), a preference (prefs.*) or action (action.*) command, an Object › Align item, Image Trace's Make or Make and Expand, Pattern's Make or Edit Pattern, a saved selection, saved view or recent font item, or a plug-in's item. The place is as ui.action.insertStop takes it: with set and action, after step, else after the action's last step; without them, the recording in progress. The new step becomes the panel's selected step, and its action and set become the selected ones. A command and params that no such menu item has, a param of another type, params that are not an object, no action and no recording, or a step that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. The panel menu's Insert Menu Item… (dialog `actionInsertMenuItem` with find, command, params, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", ), + ( + crate::panels::actions::INSERT_SELECT_OBJECT, + "Select Object", + "", + "{set?: index, action?: index, step?: index, note, caseSensitive?: bool, wholeWord?: bool} insert a Select Object step, without running it: playback runs select.byNote {note, caseSensitive, wholeWord}, which selects the objects whose Attributes note matches note, and a playback that finds no such object stops there with an error. note loses its leading and trailing spaces and must then be 1 to 1,024 bytes; caseSensitive and wholeWord default to false. The place is as ui.action.insertStop takes it: with set and action, after step, else after the action's last step; without them, the recording in progress. The new step becomes the panel's selected step, and its action and set become the selected ones. A missing or empty note, a param of another type, params that are not an object, no action and no recording, or a step that would give the action more than 10,000 steps or its set's file more than 8 MiB, counting the steps that the recording in progress adds to the set, is an error and changes nothing. The panel menu's Select Object… (dialog `actionSelectObject`, Set Selection, with note, caseSensitive, wholeWord, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", + ), ( crate::panels::actions::CONTINUE_PLAYBACK, "Continue Action", diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index f2426f33ab..fc70693ce8 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -948,6 +948,55 @@ pub fn insert_menu_item(app: &mut VectorcraftApp, p: &Value) -> Result Result<(String, bool, bool), String> { + if !p.is_object() { + return Err("`params` must be an object".into()); + } + let key = "note"; + let note = match p.get(key) { + None | Some(Value::Null) => "", + Some(v) => v.as_str().ok_or_else(|| format!("`{key}` must be a string"))?, + } + .trim(); + if note.is_empty() { + return Err("the note is empty".into()); + } + if note.len() > MAX_SELECT_NOTE { + return Err("the note is longer than 1,024 bytes".into()); + } + let flag = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(false), + Some(v) => v.as_bool().ok_or_else(|| format!("`{key}` must be true or false")), + }; + Ok((note.to_string(), flag("caseSensitive")?, flag("wholeWord")?)) +} + +/// The command that inserts a Select Object step ([`insert_select_object`]). +pub const INSERT_SELECT_OBJECT: &str = "ui.action.insertSelectObject"; + +/// `ui.action.insertSelectObject {set?, action?, step?, note, caseSensitive?, wholeWord?}`: inserts +/// a Select Object step, without running it. Playback selects the objects whose Attributes note +/// matches `note` ([`SELECT_OBJECT_STEP`]); a playback that finds none stops there with an error. +/// The note and options are as [`select_object_params`] reads them. The place is as [`insert_stop`] +/// takes it, and the step is selected as a stop is. Bad params, or a place [`insert_stop`] +/// refuses, is an error, and then nothing changes. Set Selection's OK runs this. → {set, action, +/// step}, or {recording: true} +pub fn insert_select_object(app: &mut VectorcraftApp, p: &Value) -> Result { + let (note, case_sensitive, whole_word) = select_object_params(p)?; + insert(app, p, (SELECT_OBJECT_STEP.to_string(), json!({"note": note, "caseSensitive": case_sensitive, "wholeWord": whole_word}))) +} + /// The journal entry the recording in progress records from. fn recording_start(app: &VectorcraftApp) -> Option { let (_, _, start) = app.ui.recording.as_ref()?; @@ -1256,7 +1305,7 @@ pub const DELETE_STEP: &str = "ui.action.deleteStep"; /// `ui.action.deleteStep {set, action, step}`: deletes step `step`, a stop or a command, of the /// action at index `action` of set `set`. The steps after it keep whether they are excluded, and -/// no step of that action stays selected. A Record Stop or Insert Menu Item dialog open on that step +/// no step of that action stays selected. A Record Stop, Insert Menu Item or Set Selection dialog open on that step /// closes, and one open on a later step of the action follows it up. A missing or invalid index is an error, and /// then nothing changes. Undo does not bring the step back. Delete Selection runs this for the /// selected step. → {set, action, step} @@ -1567,10 +1616,12 @@ fn holds_set(d: &crate::state::Dialog) -> bool { || (d.kind == crate::dialogs::action_set_options::KIND && d.fields.contains_key("set")) } -/// Whether dialog `d` is a Record Stop or Insert Menu Item dialog, which holds the place of a new -/// step in its `set`, `action` and `step` fields. +/// Whether dialog `d` is a Record Stop, Insert Menu Item or Set Selection dialog, which holds the +/// place of a new step in its `set`, `action` and `step` fields. fn holds_step(d: &crate::state::Dialog) -> bool { - d.kind == crate::dialogs::action_stop::RECORD_KIND || d.kind == crate::dialogs::action_insert_menu_item::KIND + d.kind == crate::dialogs::action_stop::RECORD_KIND + || d.kind == crate::dialogs::action_insert_menu_item::KIND + || d.kind == crate::dialogs::action_select_object::KIND } /// The command that duplicates an action or an action set ([`duplicate`]). @@ -1624,8 +1675,8 @@ pub fn duplicate(app: &mut VectorcraftApp, p: &Value) -> Result { edited.actions.insert(a + 1, copy); edit_keeps_set_loadable(app, Some(set), &edited)?; app.ui.action_sets[set] = edited; - // A Batch, Record Stop or Insert Menu Item dialog open on a later action of the set follows it - // down. + // A Batch, Record Stop, Insert Menu Item or Set Selection dialog open on a later action of the + // set follows it down. if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == crate::dialogs::action_batch::KIND || holds_step(d)) && d.fields.get("set").and_then(index) == Some(set) && let Some(da) = d.fields.get("action").and_then(index).filter(|&da| da > a) @@ -1706,6 +1757,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let step = selected_step(app, ui.ctx(), selected); crate::dialogs::action_insert_menu_item::open(app, if recording { None } else { selected }, step); } + if widgets::menu_item(ui, tl!("Select Object…"), recording || has, false) { + let step = selected_step(app, ui.ctx(), selected); + crate::dialogs::action_select_object::open(app, if recording { None } else { selected }, step); + } if widgets::menu_item(ui, tl!("Action Options…"), has, false) && let Some((s, a)) = selected { @@ -1892,10 +1947,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { current = Some(si); sets_selected = vec![si]; } - // A stop's row shows its message; other steps show their command. + // A stop's row shows its message, and a Select Object step's its note; other + // steps show their command. let shown = if command == STOP_STEP { let message = params.get("message").and_then(Value::as_str).and_then(|m| m.lines().next()).unwrap_or_default(); crate::i18n::fmt(tl!("Stop: {message}"), &[("message", message)]) + } else if command == SELECT_OBJECT_STEP { + let note = params.get("note").and_then(Value::as_str).and_then(|m| m.lines().next()).unwrap_or_default(); + crate::i18n::fmt(tl!("Select Object: {note}"), &[("note", note)]) } else { command.clone() }; @@ -3087,7 +3146,7 @@ mod tests { (json!(long.to_string()), "an action in the action set file has more than 10,000 steps"), (json!(" ".repeat(files::MAX_SET_FILE + 1)), "the action set file is larger than 8 MiB"), ( - json!("{\"format\": \"vcactions\", \"version\": 4, \"name\": \"S\", \"actions\": []}"), + json!("{\"format\": \"vcactions\", \"version\": 5, \"name\": \"S\", \"actions\": []}"), "the action set file needs a later version of VectorCraft", ), ] { @@ -5520,7 +5579,7 @@ mod tests { json!({"format": "vcactions", "version": version, "name": "Old", "actions": [{"name": "A", "steps": [{"command": "object.move"}]}]}); assert_eq!(files::read_set(&old.to_string(), "Test").unwrap().actions[0].steps.len(), 1, "version {version}"); } - let later = json!({"format": "vcactions", "version": 4, "name": "New", "actions": []}); + let later = json!({"format": "vcactions", "version": 5, "name": "New", "actions": []}); assert_eq!(files::read_set(&later.to_string(), "Test").unwrap_err(), "the action set file needs a later version of VectorCraft"); for params in [json!({"message": 5}), json!({"allowContinue": "yes"}), json!(42)] { let stop = json!({"command": "action.stop", "params": params}); @@ -5664,4 +5723,182 @@ mod tests { app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); assert_eq!(open_kind(&app), None, "deleting its set closes it"); } + + /// [`app_with_three_moves`] with a second rectangle whose Attributes note is "Badge front" → + /// (the app, the first rectangle's x offset, the second rectangle's x offset). + #[allow(clippy::type_complexity)] + fn app_with_a_noted_rect() -> (VectorcraftApp, Box f64>, Box f64>) { + let (mut app, x) = app_with_three_moves(); + let first = app.session.active().unwrap().selection.objects.clone(); + let id = vectorcraft_doc::NodeId( + app.run("shape.rectangle", json!({"x": 100, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(), + ); + app.run("attributes.set", json!({"ids": [id.0], "note": "Badge front"})).unwrap(); + app.run("select.set", json!({"ids": first.iter().map(|i| i.0).collect::>()})).unwrap(); + let noted = move |app: &VectorcraftApp| app.session.active().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0 - 100.0; + (app, Box::new(x), Box::new(noted)) + } + + /// A Select Object step goes after the given step, or at the action's end, runs nothing when it + /// goes in, and plays as `select.byNote`: the steps after it act on the objects it selects. + #[test] + fn insert_select_object_goes_after_the_given_step_and_plays_as_a_selection_by_note() { + let (mut app, x, noted) = app_with_a_noted_rect(); + let selection = app.session.active().unwrap().selection.clone(); + let r = app.run(INSERT_SELECT_OBJECT, json!({"set": 0, "action": 0, "step": 0, "note": " badge "})).unwrap(); + assert_eq!(r, json!({"set": 0, "action": 0, "step": 1})); + assert_eq!(app.session.active().unwrap().selection, selection, "inserting runs nothing"); + let action = &app.ui.action_sets[0].actions[0]; + assert_eq!(action.steps[1], (SELECT_OBJECT_STEP.to_string(), json!({"note": "badge", "caseSensitive": false, "wholeWord": false}))); + app.run(INSERT_SELECT_OBJECT, json!({"set": 0, "action": 0, "note": "Badge", "caseSensitive": true, "wholeWord": true})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[0].steps[4].1, json!({"note": "Badge", "caseSensitive": true, "wholeWord": true})); + play(&mut app, 0, 0).unwrap(); + assert_eq!((x(&app), noted(&app)), (1.0, 6.0), "the moves after the step move the object with the note"); + let ids = &app.session.active().unwrap().selection.objects; + assert_eq!(ids.len(), 1); + } + + /// A playback whose Select Object step finds no object stops there with the step's error, at + /// every speed, and runs none of the steps after it. + #[test] + fn a_select_object_step_that_finds_nothing_stops_the_playback() { + for speed in ["accelerated", "step"] { + let (mut app, x, noted) = app_with_a_noted_rect(); + app.run(PLAYBACK_OPTIONS, json!({"speed": speed})).unwrap(); + app.ui.action_sets[0].actions[0].insert_step(0, (SELECT_OBJECT_STEP.into(), json!({"note": "missing"}))); + let selection = app.session.active().unwrap().selection.clone(); + let e = play(&mut app, 0, 0).unwrap_err(); + assert!(e.contains("no object that can be selected has a note matching “missing”"), "{speed}: {e}"); + play_out(&mut app); + assert_eq!((x(&app), noted(&app)), (0.0, 0.0), "{speed}: nothing after it runs"); + assert_eq!(app.session.active().unwrap().selection, selection, "{speed}: the selection stays"); + assert!(app.ui.action_playing.is_none(), "{speed}"); + } + } + + #[test] + fn insert_select_object_refuses_bad_params_and_changes_nothing() { + let (mut app, _, _) = app_with_a_noted_rect(); + let place = |extra: Value| { + let mut p = json!({"set": 0, "action": 0}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + p + }; + for (params, want) in [ + (place(json!({})), "the note is empty"), + (place(json!({"note": " \t "})), "the note is empty"), + (place(json!({"note": 5})), "`note` must be a string"), + (place(json!({"note": "x".repeat(1025)})), "the note is longer than 1,024 bytes"), + (place(json!({"note": "x", "caseSensitive": "yes"})), "`caseSensitive` must be true or false"), + (place(json!({"note": "x", "wholeWord": 0})), "`wholeWord` must be true or false"), + (place(json!({"note": "x", "action": 5})), "no such action"), + (place(json!({"note": "x", "step": 9})), "no such action step"), + (json!({"note": "x"}), "no such action"), + (json!(["note"]), "`params` must be an object"), + ] { + assert_eq!(app.run(INSERT_SELECT_OBJECT, params.clone()).unwrap_err(), want, "{params}"); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 3, "{params}"); + } + assert!(app.run(INSERT_SELECT_OBJECT, place(json!({"note": "x".repeat(1024)}))).is_ok(), "1,024 bytes goes in"); + } + + /// A saved Select Object step loads back as it was, in a version 4 file that older builds refuse; + /// a file whose Select Object step has bad params is refused, also inside a recorded batch. + #[test] + fn a_saved_select_object_step_survives_and_bad_ones_are_refused() { + let (mut app, _, _) = app_with_a_noted_rect(); + app.run(INSERT_SELECT_OBJECT, json!({"set": 0, "action": 0, "note": "Badge", "wholeWord": true})).unwrap(); + let saved = files::write_set(&app.ui.action_sets[0]); + let file: Value = serde_json::from_str(&saved).unwrap(); + assert_eq!(file["version"], json!(4), "older builds must refuse a Select Object step"); + assert_eq!( + file["actions"][0]["steps"][3], + json!({"command": "select.byNote", "params": {"note": "Badge", "caseSensitive": false, "wholeWord": true}}) + ); + let loaded = files::read_set(&saved, "Test").unwrap(); + assert_eq!(loaded.actions[0].steps, app.ui.action_sets[0].actions[0].steps); + app.ui.action_sets[0].actions[0].steps.push(("action.stop".into(), json!({"message": ""}))); + let file: Value = serde_json::from_str(&files::write_set(&app.ui.action_sets[0])).unwrap(); + assert_eq!(file["version"], json!(4), "with a stop too"); + for params in [json!({}), json!({"note": " "}), json!({"note": 5}), json!({"note": "a", "caseSensitive": 1}), json!(null), json!(42)] { + let step = json!({"command": "select.byNote", "params": params}); + for step in [step.clone(), json!({"command": "command.batch", "params": {"commands": [step]}})] { + let bad = json!({"format": "vcactions", "version": 4, "name": "Bad", "actions": [{"name": "A", "steps": [step]}]}); + assert_eq!(files::read_set(&bad.to_string(), "Test").unwrap_err(), "not an action set file", "{step}"); + } + } + let nested = json!({"commands": [{"command": "select.byNote", "params": {"note": "Inner"}}]}); + let set = ActionSet::new("Nested", vec![Action::new("A", vec![("command.batch".into(), nested)])]); + assert_eq!(serde_json::from_str::(&files::write_set(&set)).unwrap()["version"], json!(4), "a step in a recorded batch counts"); + } + + /// The panel menu's Select Object… opens Set Selection on the selected step's place, with an + /// empty note and both options off; Cancel inserts nothing, and OK inserts the step after the + /// selected step, whose row shows the note. While recording, the step goes into the recording. + /// With nothing selected and nothing recording, the item is off. + #[test] + fn select_object_in_the_menu_opens_set_selection_and_inserts_on_ok() { + use super::super::tests_appearance::{click, frame_events}; + let (mut app, _, _) = app_with_a_noted_rect(); + app.ui.action_set = Some(0); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let open = |ctx: &egui::Context, app: &mut VectorcraftApp| { + let texts = frame_events(ctx, app, vec![], menu); + let item = texts.iter().find(|(s, _)| s.trim() == "Select Object…").map(|(_, r)| *r).expect("Select Object… in the menu"); + click(ctx, app, item.center(), menu); + }; + open(&ctx, &mut app); + assert_eq!(open_kind(&app), None, "nothing selected and nothing recording: the item is off"); + + click_first_step(&ctx, &mut app); + open(&ctx, &mut app); + let d = app.ui.dialog.as_ref().expect("Select Object… opens Set Selection"); + assert_eq!(d.kind, crate::dialogs::action_select_object::KIND); + assert_eq!((&d.fields["set"], &d.fields["action"], &d.fields["step"]), (&json!(0), &json!(0), &json!(0))); + assert_eq!((d.str("note"), d.bool("caseSensitive"), d.bool("wholeWord")), (String::new(), false, false)); + crate::dialogs::cancel(&mut app); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 3, "Cancel inserts nothing"); + + open(&ctx, &mut app); + // A field of another type (set through ui.dialog.set) is an error, and the dialog stays. + for (key, value) in [("note", json!(5)), ("caseSensitive", json!("yes")), ("wholeWord", json!(1))] { + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("note".into(), json!("Badge")); + d.fields.insert("caseSensitive".into(), json!(false)); + d.fields.insert("wholeWord".into(), json!(false)); + d.fields.insert(key.into(), value.clone()); + } + assert!(crate::dialogs::confirm(&mut app).is_err(), "`{key}`: {value} is an error"); + assert_eq!(open_kind(&app), Some(crate::dialogs::action_select_object::KIND), "`{key}`: the dialog stays open"); + assert_eq!(app.ui.action_sets[0].actions[0].steps.len(), 3, "`{key}`: nothing is inserted"); + } + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("note".into(), json!("Badge")); + d.fields.insert("caseSensitive".into(), json!(true)); + d.fields.insert("wholeWord".into(), json!(false)); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(open_kind(&app), None, "OK closes Set Selection"); + let action = &app.ui.action_sets[0].actions[0]; + assert_eq!(action.steps[1], (SELECT_OBJECT_STEP.to_string(), json!({"note": "Badge", "caseSensitive": true, "wholeWord": false}))); + let texts = frame_events(&ctx, &mut app, vec![], show); + assert!(texts.iter().any(|(s, _)| s == "Select Object: Badge"), "the step's row shows the note: {texts:?}"); + + app.run(START_RECORDING, json!({})).unwrap(); + open(&ctx, &mut app); + assert!(!app.ui.dialog.as_ref().is_some_and(|d| d.fields.contains_key("set")), "while recording it goes into the recording"); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("note".into(), json!("While recording")); + } + crate::dialogs::confirm(&mut app).unwrap(); + app.run(STOP_RECORDING, json!({})).unwrap(); + let recorded = app.ui.action_sets[0].actions.last().unwrap(); + assert_eq!( + recorded.steps, + [(SELECT_OBJECT_STEP.to_string(), json!({"note": "While recording", "caseSensitive": false, "wholeWord": false}))] + ); + } } diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index fd8b40fbd7..ee6304690b 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -1,14 +1,16 @@ //! Action set files: the Actions panel menu's Save Actions… and Load Actions…. //! -//! An action set file (`.vcactions`) is JSON: `{"format": "vcactions", "version": 1, 2 or 3, "name", +//! An action set file (`.vcactions`) is JSON: `{"format": "vcactions", "version": 1 to 4, "name", //! "actions": [{"name", "steps": [{"command", "params", "excluded"?}], "key"?, "color"?}]}`. Each step is a //! command id and its params, as `command.batch` takes them, or a stop: the command `action.stop` -//! with `{"message", "allowContinue"}`. `key` is the action's function key +//! with `{"message", "allowContinue"}`. A Select Object step is the command `select.byNote` with +//! `{"note", "caseSensitive", "wholeWord"}`. `key` is the action's function key //! (`{"key": 1 to 15, "cmd", "shift"}`) and `color` its Button Mode color; an action without them, //! or with a value that is not one, has none. `excluded: true` keeps a step but skips it during //! playback. Sets with exclusions use version 2 so older builds refuse them rather than replay -//! excluded steps, and sets with stops use version 3 so older builds refuse them rather than fail -//! at a stop. Other sets use version 1, and earlier version 1 and 2 files still work. +//! excluded steps, sets with stops use version 3 so older builds refuse them rather than fail at a +//! stop, and sets with Select Object steps use version 4 so older builds refuse them rather than +//! fail at that step. Other sets use version 1, and earlier version 1 to 3 files still work. //! Load Actions… also reads the action sets another app saves as text (`.aia`, through //! `actionSet.read`). @@ -122,14 +124,25 @@ pub(super) fn step_bytes(command: &str, params: &Value) -> usize { /// The params of the stops in a step: a stop's own, or those of the stops a `command.batch` step /// holds, which playback runs as its own steps. fn stops_in<'a>(command: &str, params: &'a Value) -> Vec<&'a Value> { - if command == super::STOP_STEP { + steps_in(super::STOP_STEP, command, params) +} + +/// The params of the Select Object steps in a step, as [`stops_in`] finds stops. +fn select_objects_in<'a>(command: &str, params: &'a Value) -> Vec<&'a Value> { + steps_in(super::SELECT_OBJECT_STEP, command, params) +} + +/// The params of the steps that run command `kind` in a step: the step's own, or those of the +/// steps a `command.batch` step holds, which playback runs as its own steps. +fn steps_in<'a>(kind: &str, command: &str, params: &'a Value) -> Vec<&'a Value> { + if command == kind { return vec![params]; } if command != "command.batch" { return vec![]; } let steps = params.get("commands").and_then(Value::as_array).into_iter().flatten(); - steps.filter(|step| super::is_stop(step)).map(|step| step.get("params").unwrap_or(&Value::Null)).collect() + steps.filter(|step| step.get("command").and_then(Value::as_str) == Some(kind)).map(|step| step.get("params").unwrap_or(&Value::Null)).collect() } /// `set` as the text of an action set file. @@ -149,11 +162,14 @@ pub fn write_set(set: &ActionSet) -> String { color: a.color.clone(), }) .collect(); - let has_stop = set.actions.iter().flat_map(|a| &a.steps).any(|(command, params)| !stops_in(command, params).is_empty()); - let version = match (has_stop, set.actions.iter().any(|a| !a.excluded_steps.is_empty())) { - (true, _) => 3, - (false, true) => 2, - (false, false) => 1, + let steps = || set.actions.iter().flat_map(|a| &a.steps); + let has_select_object = steps().any(|(command, params)| !select_objects_in(command, params).is_empty()); + let has_stop = steps().any(|(command, params)| !stops_in(command, params).is_empty()); + let version = match (has_select_object, has_stop, set.actions.iter().any(|a| !a.excluded_steps.is_empty())) { + (true, ..) => 4, + (false, true, _) => 3, + (false, false, true) => 2, + (false, false, false) => 1, }; let file = SetFile { format: ACTIONS_EXT.into(), version, name: set.name.clone(), actions }; serde_json::to_string_pretty(&file).unwrap_or_default() @@ -168,7 +184,7 @@ pub fn read_set(text: &str, name: &str) -> Result { if f.format != ACTIONS_EXT { return Err("not an action set file".into()); } - if !matches!(f.version, 1..=3) { + if !matches!(f.version, 1..=4) { return Err("the action set file needs a later version of VectorCraft".into()); } if f.actions.len() > MAX_SET_ACTIONS { @@ -181,6 +197,10 @@ pub fn read_set(text: &str, name: &str) -> Result { if stops.any(|p| super::stop_params(p).is_err()) { return Err("not an action set file".into()); } + let mut select_objects = f.actions.iter().flat_map(|a| &a.steps).flat_map(|s| select_objects_in(&s.command, &s.params)); + if select_objects.any(|p| super::select_object_params(p).is_err()) { + return Err("not an action set file".into()); + } let actions = f .actions .into_iter() diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 0b661c8bcf..774002a72d 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -1,5 +1,6 @@ //! Artboards panel: numbered list with inline rename (double-click the name, or the panel menu's -//! Rename; while several artboards are selected, the name typed goes to all of them, numbered), +//! Rename; while several artboards are selected, the name typed goes to all of them, numbered), a +//! row menu (right-click) whose Rename opens the Rename dialog for the selected artboards, //! move up / down (or drag a row above or below another), new //! (Alt-click: Artboard Options for the new artboard first), delete; a row dragged onto New //! Artboard duplicates its artboard (as Duplicate Artboards does, with @@ -541,7 +542,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let scrolled = scroll.show(ui, |ui| { for (i, name) in abs.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click_and_drag()); - if resp.drag_started() { + // Only the primary button drags a row; a right-button drag reorders nothing. + if resp.drag_started_by(egui::PointerButton::Primary) { egui::DragAndDrop::set_payload(ui.ctx(), RowDrag(i)); } if all.contains(&i) { @@ -648,6 +650,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } else if resp.double_clicked() { start_rename(ui.ctx(), app, i); } + // A right-click on a row that isn't selected makes its artboard the active one and + // the only selected one ([`select`] sets the Artboard tool's `active` option, which + // clears the rest of its selection); on a selected row the selection stays. The row + // menu then acts on the selection. + if resp.secondary_clicked() && !picked(app, abs.len()).contains(&i) { + select(app, i); + } + resp.context_menu(|ui| row_menu(app, ui)); // Another row dragged over this one lands above or below it by the pointer's half, // a line showing where. if let Some(from) = resp.dnd_hover_payload::().map(|d| d.0).filter(|from| *from != i) { @@ -707,6 +717,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); } +/// A row's menu: Rename opens the Rename dialog for the selected artboards ([`picked`]), whose OK +/// runs `artboard.rename` in one undo step, numbering the name when there are several. +fn row_menu(app: &mut VectorcraftApp, ui: &mut Ui) { + if menu_item(ui, tl!("Rename"), true, false) { + crate::menus::invoke(app, "artboard.rename", json!({})); + } +} + /// Open Rearrange All Artboards (#681). pub(crate) fn open_rearrange(app: &mut VectorcraftApp) { app.run("ui.menuDialog", json!({ "command": "artboard.rearrange" })).ok(); diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index f2be587642..eae59fd7dc 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -1122,6 +1122,132 @@ fn dragging_a_row_onto_another_row_reorders_the_artboards() { assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"]); } +/// The panel drawn in a 240 × 400 pt window, for the row menu's tests. +struct RowMenuWindow { + ctx: egui::Context, + time: f64, +} + +impl RowMenuWindow { + fn new() -> Self { + RowMenuWindow { ctx: egui::Context::default(), time: 0.0 } + } + + /// One frame of the panel with `events`; the texts drawn and where. + fn frame(&mut self, app: &mut VectorcraftApp, events: Vec) -> Vec<(String, egui::Rect)> { + self.time += 0.5; + let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(240.0, 400.0))); + let raw = egui::RawInput { events, time: Some(self.time), screen_rect: screen, ..Default::default() }; + let mut out = self.ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Text(t) => Some((t.galley.text().trim_start().to_string(), t.visual_bounding_rect())), + _ => None, + }) + .collect() + } + + /// Where the text `label` is drawn now, if it is. + fn find(&mut self, app: &mut VectorcraftApp, label: &str) -> Option { + self.frame(app, vec![]).into_iter().find(|(t, _)| t == label).map(|(_, r)| r.center()) + } + + /// A click with `button` at `at`. + fn click(&mut self, app: &mut VectorcraftApp, at: egui::Pos2, button: egui::PointerButton) { + let b = |pressed| egui::Event::PointerButton { pos: at, button, pressed, modifiers: Default::default() }; + self.frame(app, vec![egui::Event::PointerMoved(at), b(true), b(false)]); + self.frame(app, vec![]); + } + + /// A right-click on the row named `row`, then a click on its menu's Rename. + fn rename_from_row_menu(&mut self, app: &mut VectorcraftApp, row: &str) { + let at = self.find(app, row).expect("the row"); + self.click(app, at, egui::PointerButton::Secondary); + let item = self.find(app, "Rename").expect("the row menu's Rename"); + self.click(app, item, egui::PointerButton::Primary); + } +} + +/// A right-click on an Artboards panel row opens a menu with Rename, which opens the Rename dialog +/// and renames nothing until OK: on a row of the selection, the dialog takes every selected +/// artboard and OK numbers the name in one undo step; on a row that isn't selected, that row's +/// artboard becomes the only selected one and the dialog takes it alone, and Cancel keeps its name. +#[test] +fn the_row_menus_rename_opens_the_rename_dialog_for_the_selected_artboards() { + let mut app = menu_app(4); + select(&mut app, 2); + app.session.set_tool_option("selected", &json!([2, 1])); + let mut window = RowMenuWindow::new(); + let steps = undo_steps(&app); + window.rename_from_row_menu(&mut app, "Artboard 2"); + let d = app.ui.dialog.as_ref().expect("the Rename dialog"); + assert_eq!(d.kind, crate::dialogs::rename_artboards::KIND); + assert_eq!((d.str("name").as_str(), &d.fields["indices"]), ("", &json!([1, 2])), "the dialog takes both selected artboards"); + assert_eq!(picked(&app, 4), [1, 2], "the selection stays"); + assert_eq!(board_names(&app), ["Artboard 1", "Artboard 2", "Artboard 3", "Artboard 4"], "nothing is renamed before OK"); + assert_eq!(undo_steps(&app), steps); + app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!("Page")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(board_names(&app), ["Artboard 1", "Page-1", "Page-2", "Artboard 4"]); + assert_eq!(undo_steps(&app), steps + 1, "one undo step"); + + window.rename_from_row_menu(&mut app, "Artboard 4"); + let d = app.ui.dialog.as_ref().expect("the Rename dialog"); + assert_eq!((d.str("name").as_str(), &d.fields["indices"]), ("Artboard 4", &json!([3])), "the dialog takes the row's artboard alone"); + assert_eq!((picked(&app, 4), selected(&app, 4)), (vec![3], 3), "the row's artboard is the only one selected"); + crate::dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(board_names(&app), ["Artboard 1", "Page-1", "Page-2", "Artboard 4"]); + assert_eq!(undo_steps(&app), steps + 1, "Cancel records no undo step"); +} + +/// Without the Artboard tool the row menu's Rename takes the right-clicked row's artboard, which +/// becomes the active one; a locked artboard can be renamed too. A menu closed without a choice +/// opens no dialog. +#[test] +fn the_row_menu_renames_the_right_clicked_artboard_with_any_tool() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 50, "units": "Points", "artboards": 3})).unwrap(); + app.session.execute("artboard.setProps", &json!({"index": 2, "locked": true})).unwrap(); + select(&mut app, 0); + let mut window = RowMenuWindow::new(); + let at = window.find(&mut app, "Artboard 2").expect("the row"); + window.click(&mut app, at, egui::PointerButton::Secondary); + assert!(window.find(&mut app, "Rename").is_some(), "the row menu is open"); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + window.frame(&mut app, vec![escape]); + window.frame(&mut app, vec![]); + assert!(window.find(&mut app, "Rename").is_none(), "Escape closes the menu"); + assert!(app.ui.dialog.is_none(), "and opens no dialog"); + assert_eq!(selected(&app, 3), 1, "the right-clicked artboard is active"); + + window.rename_from_row_menu(&mut app, "Artboard 3"); + let d = app.ui.dialog.as_ref().expect("the Rename dialog"); + assert_eq!((d.str("name").as_str(), &d.fields["indices"]), ("Artboard 3", &json!([2]))); + app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!("Back")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(board_names(&app), ["Artboard 1", "Artboard 2", "Back"], "the locked artboard is renamed"); +} + +/// A row dragged with the right button reorders nothing; the primary button still drags rows. +#[test] +fn a_right_button_drag_does_not_move_a_row() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + let mut window = RowMenuWindow::new(); + let (first, last) = (window.find(&mut app, "Artboard 1").unwrap(), window.find(&mut app, "Artboard 3").unwrap()); + let below = last + vec2(0.0, 8.0); + let button = |at, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }; + window.frame(&mut app, vec![egui::Event::PointerMoved(first), button(first, true)]); + window.frame(&mut app, vec![egui::Event::PointerMoved(first + vec2(0.0, 12.0))]); + window.frame(&mut app, vec![egui::Event::PointerMoved(below)]); + window.frame(&mut app, vec![button(below, false)]); + window.frame(&mut app, vec![]); + assert_eq!(board_names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"]); +} + /// A click in a row's lock column locks its artboard and shows the lock next to the name, a /// second click unlocks it, and each click is one undo step. Delete Artboard leaves a locked /// artboard. diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 13b6ff1e2b..4e5b7eb218 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -152,11 +152,12 @@ fn guide_row(ui: &mut Ui, view: &View, item: &Row, i: usize, out: &mut Out) { out.actions.push(("guide.select".into(), json!({"indexes": [i], "toggle": m.shift || m.command}))); } // Dragged: the selected guides when this is one of them, else this one, to another layer's row. - if editable && resp.drag_started() { + // Only the primary button drags a guide row. + if editable && resp.drag_started_by(egui::PointerButton::Primary) { let guides = if selected { view.guides.clone() } else { vec![i] }; egui::DragAndDrop::set_payload(ui.ctx(), LayersDrag::Guides(guides)); } - if resp.dragged() { + if resp.dragged_by(egui::PointerButton::Primary) { ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); } // Guides dropped here go to this guide's layer. @@ -363,7 +364,7 @@ pub(super) fn row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) { } let sq_resp = ui.interact(egui::Rect::from_center_size(sq, vec2(18.0, h)), ui.scope_id().with(("selsq", n.id.0)), Sense::click_and_drag()); // Dragging the selected-art square carries the selection to another row. - if (is_sel || child_sel) && sq_resp.drag_started() { + if (is_sel || child_sel) && sq_resp.drag_started_by(egui::PointerButton::Primary) { egui::DragAndDrop::set_payload(ui.ctx(), LayersDrag::Art); } let m = ui.input(|i| i.modifiers); @@ -396,8 +397,9 @@ pub(super) fn row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) { out.actions.push(("assets.add".into(), json!({ "ids": collect_ids.clone(), "multiple": multiple }))); }); }); - // Dragging rows: the highlighted rows when this is one of them, else this row. - if resp.drag_started() && view.column.is_none() { + // Dragging rows: the highlighted rows when this is one of them, else this row. Only the primary + // button drags; the secondary button opens the row menu, and a drag with it moves nothing. + if resp.drag_started_by(egui::PointerButton::Primary) && view.column.is_none() { let ids = if view.rows.contains(&n.id) { view.rows.clone() } else { vec![n.id] }; egui::DragAndDrop::set_payload(ui.ctx(), LayersDrag::Rows(ids)); let grab = resp.interact_pointer_pos().map_or(vec2(h, h / 2.0), |p| p - r.min); @@ -406,7 +408,7 @@ pub(super) fn row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) { d.insert_temp(key("grabbed"), n.id); }); } - if resp.dragged() { + if resp.dragged_by(egui::PointerButton::Primary) { ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); } drop_target(ui, view, n, r, x - 16.0, open, &resp, out); @@ -489,10 +491,10 @@ fn eye_and_lock(ui: &mut Ui, view: &View, n: &Node, r: egui::Rect, out: &mut Out } else if lr.clicked() { out.actions.push(("layer.setProps".into(), json!({"ids": [n.id.0], "locked": !n.locked}))); } - // Dragging down a column gives every row it passes this row's new state. - if er.drag_started() { + // Dragging down a column with the primary button gives every row it passes this row's new state. + if er.drag_started_by(egui::PointerButton::Primary) { out.column = Some(Some(ColumnDrag { eye: true, value: !n.visible, ids: vec![n.id.0] })); - } else if lr.drag_started() { + } else if lr.drag_started_by(egui::PointerButton::Primary) { out.column = Some(Some(ColumnDrag { eye: false, value: !n.locked, ids: vec![n.id.0] })); } else if let Some(c) = out.column.clone().unwrap_or_else(|| view.column.clone()) && !c.ids.contains(&n.id.0) @@ -567,7 +569,10 @@ fn drop_target(ui: &Ui, view: &View, n: &Node, r: egui::Rect, indent: f32, open: /// copies it) or the trash. fn target_circle(ui: &mut Ui, n: &Node, c: egui::Pos2, h: f32, targeted: bool, actions: &mut Vec<(String, Value)>, t: &Tokens) -> egui::Response { let resp = ui.interact(egui::Rect::from_center_size(c, vec2(16.0, h)), ui.scope_id().with(("target", n.id.0)), Sense::click_and_drag()); - widgets::drag_source(ui, &resp, || PanelDrag::Appearance(n.id)); + // Only the primary button carries the appearance away. + if resp.drag_started_by(egui::PointerButton::Primary) { + egui::DragAndDrop::set_payload(ui.ctx(), PanelDrag::Appearance(n.id)); + } let held = resp.dnd_hover_payload::().is_some_and(|d| matches!(*d, PanelDrag::Appearance(id) if id != n.id)); if let Some(d) = resp.dnd_release_payload::() && let PanelDrag::Appearance(source) = *d @@ -584,7 +589,7 @@ fn target_circle(ui: &mut Ui, n: &Node, c: egui::Pos2, h: f32, targeted: bool, a if has_styled_target(n) { ui.painter().circle_filled(c, 3.2, t.icon); } - if resp.dragged() { + if resp.dragged_by(egui::PointerButton::Primary) { ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); } resp diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 4b47cbd3fe..0fd8586409 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -94,22 +94,30 @@ fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec } fn button(pos: egui::Pos2, pressed: bool) -> egui::Event { - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } + button_by(pos, pressed, egui::PointerButton::Primary) +} + +/// `pointer` pressed (or released) at `pos`. +fn button_by(pos: egui::Pos2, pressed: bool, pointer: egui::PointerButton) -> egui::Event { + egui::Event::PointerButton { pos, button: pointer, pressed, modifiers: Default::default() } } /// Drag from `a` to `b` over a few frames (Alt held when `alt`). fn drag(app: &mut VectorcraftApp, ctx: &egui::Context, a: egui::Pos2, b: egui::Pos2, alt: bool) { - let steps = [ - vec![egui::Event::PointerMoved(a)], - vec![button(a, true)], - vec![egui::Event::PointerMoved(a + vec2(0.0, 6.0))], - vec![egui::Event::PointerMoved(b)], - vec![button(b, false)], - vec![], - ]; - for e in steps { - frame(app, ctx, e, alt); - } + drag_by(app, ctx, a, b, alt, egui::PointerButton::Primary); +} + +/// Drag from `a` to `b` with `pointer` over a few frames (Alt held when `alt`). Returns whether a +/// drag-and-drop payload was held over `b` before the release. +fn drag_by(app: &mut VectorcraftApp, ctx: &egui::Context, a: egui::Pos2, b: egui::Pos2, alt: bool, pointer: egui::PointerButton) -> bool { + frame(app, ctx, vec![egui::Event::PointerMoved(a)], alt); + frame(app, ctx, vec![button_by(a, true, pointer)], alt); + frame(app, ctx, vec![egui::Event::PointerMoved(a + vec2(0.0, 6.0))], alt); + frame(app, ctx, vec![egui::Event::PointerMoved(b)], alt); + let held = egui::DragAndDrop::has_any_payload(ctx); + frame(app, ctx, vec![button_by(b, false, pointer)], alt); + frame(app, ctx, vec![], alt); + held } #[test] @@ -1290,6 +1298,104 @@ fn the_selected_art_square_drags_the_selection_to_another_layer() { assert_eq!(app.session.active().unwrap().selection.objects.len(), 2, "still selected"); } +/// The undo steps of the active document. +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +/// Drags from `a` to `b` with the secondary and then the middle button, each of which must carry +/// nothing and leave the document and its undo steps as they were (`state` reads what the drag +/// would change); then the same drag with the primary button, which must change `state`. +fn only_the_primary_button_drags( + app: &mut VectorcraftApp, + ctx: &egui::Context, + (a, b): (egui::Pos2, egui::Pos2), + state: impl Fn(&VectorcraftApp) -> S, + what: &str, +) { + let (before, undo) = (state(app), undo_len(app)); + for pointer in [egui::PointerButton::Secondary, egui::PointerButton::Middle] { + let held = drag_by(app, ctx, a, b, false, pointer); + assert!(!held, "{what}: a {pointer:?} drag carries nothing"); + assert_eq!(state(app), before, "{what}: a {pointer:?} drag changes nothing"); + assert_eq!(undo_len(app), undo, "{what}: a {pointer:?} drag records no undo step"); + } + drag_by(app, ctx, a, b, false, egui::PointerButton::Primary); + assert_ne!(state(app), before, "{what}: the primary button drags"); +} + +/// Only the primary button drags in the panel: a drag with the secondary or middle button moves no +/// row, guide or selected art, hides or locks no row and moves no appearance, and records no undo +/// step. The secondary button still opens a row's menu. +#[test] +fn only_the_primary_button_drags_rows_guides_art_columns_and_appearances() { + let node = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().clone(); + let rows = |app: &mut VectorcraftApp, ctx: &egui::Context| frame(app, ctx, vec![], false).0; + + // A row, onto the middle of another layer's row. + let (mut app, [.., a, _]) = nested(); + app.session.execute("layer.new", &json!({"top": true, "name": "Top"})).unwrap(); + let ctx = egui::Context::default(); + let c = rows(&mut app, &ctx); + let parent = |app: &VectorcraftApp| app.session.active().unwrap().doc.parent_of(a); + only_the_primary_button_drags(&mut app, &ctx, (egui::pos2(150.0, c[5].y), egui::pos2(150.0, c[0].y)), parent, "a row"); + + // A guide row, onto another layer's row. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap(); + run(&mut app, "file.new", json!({"width": 200, "height": 200})); + run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})); + run(&mut app, "guide.add", json!({"vertical": true, "pos": 50})); + run(&mut app, "select.none", json!({})); + run(&mut app, "layer.new", json!({})); + expand(&mut app, &json!({})).unwrap(); + let ctx = egui::Context::default(); + let c = rows(&mut app, &ctx); + let guide_row = egui::pos2(150.0, (c[1].y + c[2].y) / 2.0); + let layer = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides()[0].layer; + only_the_primary_button_drags(&mut app, &ctx, (guide_row, egui::pos2(150.0, c[0].y)), layer, "a guide row"); + + // The selected-art square, onto the layer's row. + let (mut app, [_, _, g, _, a, _]) = nested(); + app.session.execute("select.set", &json!({"ids": [a.0, g.0]})).unwrap(); + let ctx = egui::Context::default(); + let c = rows(&mut app, &ctx); + let kids = |app: &VectorcraftApp| { + let d = &app.session.active().unwrap().doc; + d.node(d.layers[0].id).unwrap().children().unwrap().iter().map(|n| n.id).collect::>() + }; + let square = c[1] + vec2(TARGET_X - SQUARE_X, 0.0); + only_the_primary_button_drags(&mut app, &ctx, (square, egui::pos2(150.0, c[0].y)), kids, "the selected-art square"); + + // Down the eye and the lock columns, from the group's row to a rectangle's. + for (x, what) in [(12.0, "the eye column"), (37.0, "the lock column")] { + let (mut app, [_, _, g, b, a, _]) = nested(); + let ctx = egui::Context::default(); + let c = rows(&mut app, &ctx); + let marks = move |app: &VectorcraftApp| [g, b, a].map(|id| (node(app, id).visible, node(app, id).locked)); + only_the_primary_button_drags(&mut app, &ctx, (egui::pos2(x, c[2].y), egui::pos2(x, c[4].y)), marks, what); + } + + // A target circle, onto another row's circle. + let (mut app, _, [a, b]) = two_rects(); + app.session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap(); + let ctx = egui::Context::default(); + let c = rows(&mut app, &ctx); + let opacities = move |app: &VectorcraftApp| [a, b].map(|id| node(app, id).opacity); + only_the_primary_button_drags(&mut app, &ctx, (c[2], c[1]), opacities, "a target circle"); + + // A secondary click on a row opens its menu. + let (mut app, _, _) = two_rects(); + let ctx = egui::Context::default(); + let c = frame(&mut app, &ctx, vec![], false).0; + let at = egui::pos2(150.0, c[0].y); + let right = egui::PointerButton::Secondary; + for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] { + frame(&mut app, &ctx, vec![e], false); + } + assert_eq!(texts(&mut app, &ctx, vec![], "Collect for Export"), 1, "the row menu is open"); +} + #[test] fn the_panel_menu_lists_every_operation() { let (mut app, _) = nested(); diff --git a/crates/ui-egui/src/panels/swatches/body.rs b/crates/ui-egui/src/panels/swatches/body.rs index b97b10ab90..ef830c8c43 100644 --- a/crates/ui-egui/src/panels/swatches/body.rs +++ b/crates/ui-egui/src/panels/swatches/body.rs @@ -51,9 +51,17 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) { let lit = app.session.active().map(|st| highlighted(&st.doc, sel)).unwrap_or_default(); let is_sel = |name: &str| lit.contains(&name); let mut ev = TileEvents::default(); + // In a sized panel the list fills the space above the footer (#1638), as the Artboards list + // does; elsewhere it keeps its 150 pt (200 pt for large thumbnails). + let fixed = widgets::panel_footer_bottom(ui).is_some(); + let list_height = widgets::panel_list_height(ui, if view == View::LargeThumb { 200.0 } else { 150.0 }, 2.0 + ui.spacing().item_spacing.y); widgets::list_box(ui, |ui| { - let max_height = if view == View::LargeThumb { 200.0 } else { 150.0 }; - let out = egui::ScrollArea::vertical().id_salt("swatch-scroll").max_height(max_height).show(ui, |ui| { + let scroll = egui::ScrollArea::vertical() + .id_salt("swatch-scroll") + .max_height(list_height) + .min_scrolled_height(list_height.min(64.0)) + .auto_shrink([false, !fixed]); + let out = scroll.show(ui, |ui| { ui.set_width(ui.available_width()); if view.is_list() { for e in &items { diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 719262f451..0776b6296b 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -959,3 +959,33 @@ fn show_recent_colors_hides_and_shows_the_swatches_row() { }; assert_eq!((saved(json!(false)), saved(json!(true)), saved(json!("no"))), (false, true, true)); } + +/// In a panel made taller the swatch list fills the space above the panel's footer instead of +/// scrolling inside 150 or 200 pt (#1638); outside a sized panel it keeps those heights. +#[test] +fn the_list_fills_a_tall_panel_above_its_footer() { + let mut app = app(); + for i in 0..60 { + app.run("swatch.new", json!({"name": format!("Tone {i:02}"), "color": format!("#{:02x}3060", i * 4)})).unwrap(); + } + let ctx = context(); + set_pstate(&ctx, "swatch-view", View::SmallList); + // The clip rect of the first swatch row's name: the list's visible area. + let mut list = |bottom: Option| { + let mut clip = None; + for _ in 0..3 { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(280.0, 760.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + let info = egui::UiStackInfo::default().with_tag_value(widgets::PANEL_FOOTER, bottom); + ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| show(&mut app, ui)); + }); + out.textures_delta.clear(); + clip = out.shapes.iter().find(|c| matches!(&c.shape, egui::Shape::Text(t) if t.galley.text() == "Tone 00")).map(|c| c.clip_rect); + } + clip.expect("the first new swatch's row is drawn") + }; + let tall = list(Some(700.0)); + assert!(tall.height() > 400.0 && tall.bottom() <= 700.0 - 31.0, "the list fills the panel above its footer: {tall:?}"); + let loose = list(None); + assert!(loose.height() <= 150.5, "unsized, the list keeps its height: {loose:?}"); +} diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index db262870ab..0b5794b615 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -487,20 +487,22 @@ fn hold_back_key(app: &VectorcraftApp, ctx: &egui::Context, key: Key) { ctx.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Key { key: k, pressed: true, .. } if *k == key))); } -/// The key of the mark that the Escape held down ended a ruler-origin drag or a floating Tools move. +/// The key of the mark that the Escape held down ended a ruler-origin drag, a floating Tools move +/// or a Control bar gripper drag. fn escape_ended_gesture_id() -> egui::Id { egui::Id::unique("escape-ended-gesture") } -/// Does this frame's Escape end a ruler-origin drag or a floating Tools move? The repeats of an -/// Escape that ended one do too, up to the frame that releases Escape or presses it again. +/// Does this frame's Escape end a ruler-origin drag, a floating Tools move or a Control bar gripper +/// drag? The repeats of an Escape that ended one do too, up to the frame that releases Escape or +/// presses it again. fn escape_ended_gesture(ctx: &egui::Context) -> bool { let (down, pressed, repeated) = ctx.input(|i| { let escape = |repeat: bool| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: Key::Escape, pressed: true, repeat: r, .. } if *r == repeat)); (i.key_down(Key::Escape), escape(false), escape(true)) }); - if crate::canvas::ruler_origin_dragging(ctx) || crate::tools_float::escape_cancelled_move(ctx) { + if crate::canvas::ruler_origin_dragging(ctx) || crate::tools_float::escape_cancelled_move(ctx) || crate::chrome::control_bar_moving(ctx) { if down { ctx.data_mut(|d| d.insert_temp(escape_ended_gesture_id(), true)); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e2a8eb415b..f2728fe994 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -428,6 +428,15 @@ pub struct UiState { /// The Control bar is docked to the bottom of the window instead of the top /// (`window.control.dock`). pub control_bar_bottom: bool, + /// The Control bar floats over the window at `control_bar_float_pos` instead of docking to an + /// edge (`window.control.dock {edge: "float"}`); `control_bar_bottom` keeps the edge it last + /// docked to. + #[serde(default)] + pub control_bar_floating: bool, + /// The top-left corner of the floating Control bar in window points, kept while the bar is + /// docked; none: `chrome::CONTROL_BAR_FLOAT_AT`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub control_bar_float_pos: Option<[f32; 2]>, /// The groups of the Control bar's options (`chrome::CONTROL_BAR_GROUPS`) that its panel menu /// has off (`window.control.options`); none: every group shows. #[serde(deserialize_with = "crate::chrome::read_hidden_groups")] @@ -1003,7 +1012,8 @@ pub struct FloatingPanels { pub docked: Option, } -/// Drop a Tools panel position that isn't a number (a hand-edited preferences file or workspace). +/// Drop a floating position of the Tools panel or the Control bar that isn't a number (a +/// hand-edited preferences file or workspace). pub fn sanitize_toolbar_pos(toolbar_pos: &mut Option<[f32; 2]>) { if toolbar_pos.is_some_and(|p| !p.iter().all(|v| v.is_finite())) { *toolbar_pos = None; @@ -1027,6 +1037,7 @@ impl UiState { } FloatingFlyout::sanitize(&mut self.floating_flyouts); sanitize_toolbar_pos(&mut self.toolbar_pos); + sanitize_toolbar_pos(&mut self.control_bar_float_pos); crate::edit_toolbar::sanitize(&mut self.toolbar_edits); // `read_preferences` converted the file's older layouts already; this covers a state read // any other way. What it reports lost was dropped there. @@ -1076,6 +1087,8 @@ impl Default for UiState { learn_locate: None, control_bar: false, control_bar_bottom: false, + control_bar_floating: false, + control_bar_float_pos: None, control_bar_hidden_groups: Default::default(), toolbar: true, toolbar_double: false, diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index 3466f78f4b..2a764a6968 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -24,6 +24,13 @@ pub struct Workspace { /// The Control bar is docked to the bottom of the window (built-in workspaces, and workspaces /// saved without this field: the top). pub control_bar_bottom: bool, + /// The Control bar floats at `control_bar_float_pos` (built-in workspaces, and workspaces saved + /// without this field: docked at the edge `control_bar_bottom` names). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub control_bar_floating: bool, + /// Where the Control bar floats, or last floated (built-in workspaces: none, the first position). + #[serde(skip_serializing_if = "Option::is_none")] + pub control_bar_float_pos: Option<[f32; 2]>, /// The groups of the Control bar's options its panel menu has off (built-in workspaces, and /// workspaces saved without this field: none). #[serde(skip_serializing_if = "std::collections::BTreeSet::is_empty", deserialize_with = "crate::chrome::read_hidden_groups")] @@ -190,6 +197,8 @@ pub fn capture(ui: &UiState, name: &str) -> Workspace { name: name.into(), control_bar: ui.control_bar, control_bar_bottom: ui.control_bar_bottom, + control_bar_floating: ui.control_bar_floating, + control_bar_float_pos: ui.control_bar_float_pos, control_bar_hidden_groups: ui.control_bar_hidden_groups.clone(), rulers: ui.view.rulers, toolbar: ui.toolbar, @@ -221,6 +230,13 @@ pub fn capture(ui: &UiState, name: &str) -> Workspace { pub fn apply(ui: &mut UiState, w: &Workspace) { ui.control_bar = w.control_bar; ui.control_bar_bottom = w.control_bar_bottom; + ui.control_bar_floating = w.control_bar_floating; + // A floating workspace floats the bar where it was saved (none: the first position); a docked + // one without a floating position keeps the one the bar last floated at. + if w.control_bar_floating || w.control_bar_float_pos.is_some() { + ui.control_bar_float_pos = w.control_bar_float_pos; + crate::state::sanitize_toolbar_pos(&mut ui.control_bar_float_pos); + } ui.control_bar_hidden_groups = w.control_bar_hidden_groups.clone(); ui.view.rulers = w.rulers; ui.toolbar = w.toolbar; @@ -813,6 +829,43 @@ mod tests { assert!(ui.control_bar && !ui.control_bar_bottom, "an older workspace docks the bar at the top"); } + /// A workspace keeps a floating Control bar and where it floats, through the preferences' JSON + /// too; switching to a docked workspace docks it and keeps that position for the next float. + /// Reset floats the bar where the workspace was saved floating. A workspace or preferences saved + /// before floating keep their top or bottom edge, and a position that is not a number is + /// dropped. + #[test] + fn saved_workspaces_restore_floating_control_bar_position() { + let mut ui = UiState { control_bar: true, control_bar_floating: true, control_bar_float_pos: Some([220.0, 140.0]), ..Default::default() }; + save_as(&mut ui, "Floating").unwrap(); + switch(&mut ui, ESSENTIALS).unwrap(); + assert!(!ui.control_bar_floating && !ui.control_bar_bottom, "Essentials docks the bar at the top"); + assert_eq!(ui.control_bar_float_pos, Some([220.0, 140.0]), "the last floating position is kept while docked"); + switch(&mut ui, "Floating").unwrap(); + assert!(ui.control_bar_floating, "the saved workspace floats the bar again"); + assert_eq!(ui.control_bar_float_pos, Some([220.0, 140.0])); + let back: UiState = serde_json::from_value(serde_json::to_value(&ui).unwrap()).unwrap(); + assert!(back.control_bar_floating && back.custom_workspaces[0].control_bar_floating, "both survive the preferences' JSON"); + assert_eq!(back.custom_workspaces[0].control_bar_float_pos, Some([220.0, 140.0])); + // Saved before the bar floated: the edge it was docked to, top or bottom. + for bottom in [false, true] { + let old: Workspace = serde_json::from_value(json!({"name": "Old", "controlBar": true, "controlBarBottom": bottom})).unwrap(); + apply(&mut ui, &old); + assert!(!ui.control_bar_floating && ui.control_bar_bottom == bottom, "an older workspace docks the bar at its edge, bottom: {bottom}"); + let old: UiState = serde_json::from_value(json!({"control_bar": true, "control_bar_bottom": bottom})).unwrap(); + assert!(!old.control_bar_floating && old.control_bar_bottom == bottom, "older preferences dock it at their edge, bottom: {bottom}"); + } + // Saved floating at the first position: Reset after a move floats it there again. + let mut ui = UiState { control_bar: true, control_bar_floating: true, ..Default::default() }; + save_as(&mut ui, "First").unwrap(); + ui.control_bar_float_pos = Some([300.0, 90.0]); + reset(&mut ui); + assert!(ui.control_bar_floating, "Reset floats the bar"); + assert_eq!(ui.control_bar_float_pos, None, "at the first position, as the workspace was saved"); + let odd: UiState = serde_json::from_value(json!({"control_bar_floating": true, "control_bar_float_pos": [1e39, 5.0]})).unwrap(); + assert_eq!(odd.sanitized().control_bar_float_pos, None, "a position out of range is dropped"); + } + /// A workspace keeps the groups of Control bar options its panel menu has off: switching /// brings each workspace's back, Reset turns a built-in workspace's on again, and they survive /// the preferences' JSON. A workspace or preferences saved without them, or with groups the bar diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d442b32240..47c389bb56 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (`.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (`.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -59,7 +59,7 @@ private editing data. VectorCraft: and the paragraph's hyphenation options and tab stops. Stroked type keeps its stroke's cap, join and miter limit. Type filled or stroked with a pattern keeps its pattern, placed in the document as a path's pattern fill would be: a character's paint names an art style of one paint, and the pattern is in that style (its colour in the text document is black). A pattern the file - doesn't define, or a style that isn't a pattern, keeps the colour as before. Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one + doesn't define, or a style that isn't a pattern, keeps the colour as before. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one frame whose last lines the file sets but which don't fit here (the fallback font, or a descent past the frame's bottom) may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines, with a warning when it does. RGB in the PDF page's `ICCBased` spaces keeps the file's numbers in a `.ai` (the `uncalibrated_rgb` @@ -323,6 +323,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| | 2026-11-12 | minor | `.ai` and EPS import (#6983): type from the text document is set in an installed face of the PostScript name its font record gives, one of exactly that name first. That face's family is no longer swapped for another family spelled alike but for case and punctuation (`FontDb::find_family`, which picked `SAMPLE INK` for `SampleInk`, the PostScript name of `Sample/Ink`); among the faces `FontDb::postscript_faces` lists for the name, the import takes one whose name matches in case and punctuation before one that matches only without them; and when the family and style alone resolve to another installed copy, the type names the face's version. A font record's key 5, the version string (name ID 5), picks that version among the faces of its PostScript name, also when the record spells the name with other punctuation (`Sample-Slab` for faces named `SampleSlab`); each record is resolved once. Type a PostScript program sets and legacy `.ai` type take the face of their font's name the same way. The `.ai` save writes a static font's version (`/5`) when its PostScript name alone would give the reader another installed copy (another version, or the same name in another family), so two such copies are two fonts of the set, and checks that the type comes back in the same family, style and face, taking the record's version as the reader does (up to 256 bytes): such type round-trips without the type attributes note, and so does a version that isn't installed, which draws in the face the font resolves to anyway. In 224 users' files (used locally, never committed; all PDF-compatible, so the PostScript and legacy paths are not exercised), 16 files set some type in another installed face; 12 render differently against their own page, 10 closer (in one from 2.55% to 0.01% of the page differing) and 2 further by 0.03% of the page (an envelope of type that now opens live, and a copy of the same widths in the version the record names); envelopes of type that open live go from 154 to 159, none fewer in any file; no file opens in another way. The notes of how far a file's layers differ from its page shrink in 2 files and appear in 2 where an envelope of type now opens live, so the file is compared with its page. Two installed copies of one PostScript name, family and style that differ in widths, in files whose records keep no version, still take the copy the family and style resolve to: only the page's widths tell them apart. Tests: `tests_native::type_from_the_text_document_takes_the_face_of_its_exact_postscript_name`, `tests_native::type_from_the_text_document_takes_the_version_its_font_record_keeps`, `tests_fontnames::shown_type_takes_the_face_of_its_exact_postscript_name`, `ai::tests::legacy_type_takes_the_face_of_its_exact_postscript_name`, `ai_editing::tests::type_in_a_font_beside_a_family_spelled_alike_keeps_its_font`, `ai_editing::tests::type_in_another_version_of_a_static_font_keeps_it`, `ai_editing::tests::type_in_a_copy_its_postscript_name_alone_doesnt_give_keeps_it`, `ai_editing::tests::a_version_longer_than_the_reader_takes_is_reported`, `vectorcraft-text` `tests::versions::every_face_of_a_postscript_name_is_found`. Scores unchanged. | +| 2026-11-12 | minor | `.ai` and EPS import: type from the text document keeps its manual kerning (#6899). Key 8 of a story's text holds it as runs of characters (key 1), each with a value (key 0 of key 0, in thousandths of an em) or empty where the automatic kerning applies; a character with a value takes it as its Kerning, the space between it and the next character ([Line and character spacing](https://helpx.adobe.com/illustrator/using/line-character-spacing.html)), of the em as its Horizontal Scale draws it, as tracking. It wasn't read, so type kerned by hand came in spaced by the font alone and drifted from the page from each kerned pair on, and envelopes of such type drew apart from their drawn art and kept it. In users' files, used locally and never committed, 48 stories in 17 of 224 files have it, and the drawn art of envelopes of such type sets each kerned gap wider or narrower by exactly that value (a heading's first pair at -140, the letters of a line at 20 to 220). Measured against each file's own page, 14 of those files draw closer (in 4 the pixels that differ go from 2.7–4.7% to under 0.6%) and 2 a little further, both where an envelope of type now opens live in place of its drawn art; envelopes of type that open live go from 154 to 159 of 203, none fewer in any file, and two notes that the type differs from the page go. A value that can't be read keeps the automatic kerning, a run whose length can't be read ends the runs there, and past 65,536 runs the characters keep the automatic kerning. `.ai` save still leaves kerning out of the editing data, so saving such a file as `.ai` again now gives the note that attributes of type are left out for type with manual kerning. Tests `ate::tests::a_story_keeps_its_manual_kerning`, `tests_native::type_keeps_its_manual_kerning`; scores unchanged | | 2026-11-12 | minor | `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, after the ways it was tried before (its glyphs alone and grown by half its strokes' weight, #6535, on its own warp and on its saved grid), before a grid moved onto its drawn art, and only where that box is another: its glyph outlines with their fills and strokes baked as the envelope bakes them (geometry effects on them applied: a stroke a Transform effect moves counts where it is moved to), each piece measured by its visual bounds, which are exact for miter joins (a tip counts where the miter limit keeps it, not the miter allowance at every corner that the bounds with strokes take) and round joins and an upper bound for bevel joins, miters the limit cuts, width profiles and square-capped dashes; a contour of zero length, which paints nothing, doesn't count. Effects on the type object itself are left out, as VectorCraft applies them after the envelope bends the type. The box is measured only when that try comes and the import has a check left for it, and once for an envelope. Groups round type and other objects in the contents are measured as before. In users' files (used locally, never committed) the drawn art of some stroked type in an envelope maps from that box: where the type has sharp corners at its edges (slanted stems, pointed feet) and miter joins, or a stroke moved by a Transform effect (a drop shadow), its glyphs grown by half the weight gave too small a box and the envelope kept its drawn art; and where a glyph holds a contour of zero length at its edge, the glyphs' box counted it. On 224 of our own files: envelopes of type that open live go from 154 in 45 files to 161 in 50, and no file loses one; no file changes whether it opens from its layers or its PDF part; renders at 40 ppi change in 6 files, by at most 0.94% of their pixels, each where an envelope of type now opens live in place of its drawn art (the page's own art): 1 closer to the file's own page and 5 further; the notes change in the same 6 files: the note on type in an envelope goes where none keeps its drawn art, and a file whose envelopes of type all kept their drawn art, which opened without the page comparison, now opens with it and carries its notes (the share of art or type that differs from the page, type the page has without a text object, the PDF part's note on DeviceN colours). A synthetic file of 256 such envelopes of 2,000 characters each opens in the same time as before (13.3 s in a debug build): the box is measured only when its try comes. Tests `ai::envelope::tests::mitred_type_is_also_tried_mapped_from_what_its_stroke_paints_miter_tips_included`, `type_with_a_mitred_character_stroke_is_also_tried_mapped_from_what_it_paints`, `a_stroke_moved_by_a_transform_effect_counts_where_it_paints`, `round_joined_type_is_not_tried_twice_for_the_same_box`, `a_contour_of_zero_length_paints_nothing`, `a_side_within_the_slack_of_the_geometric_box_is_that_side`, `tests_native::a_warp_of_mitred_type_maps_from_what_its_stroke_paints_where_its_drawn_art_does` (#6824, part of #3179) | | 2026-11-12 | minor | `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern. In the text document a character's fill or stroke is a colour (key 0) and the name of an art style (key 5). In users' files (used locally, never committed) that style is one paint (`/SimpleStyle`): a colour, the one key 0 already has, or a pattern, `(name) … [matrix] p`, whose key 0 is black. Such type came in black, or stroked in black. It now takes the pattern, its matrix in art space as a path's pattern fill has it (the files' PDF parts tile such type with that matrix), placed in the type's text space so that it stays where the document has it. A pattern the file doesn't define or can't place, and a style of any other paint, keep the colour as before. A `.ai` saved again writes such type as its outlines, as it writes all type with pattern paint, with that warning. On 224 of our own files: envelopes of type that open live go from 154 in 45 files to 157 in 46, and no file loses one; no file changes whether it opens from its layers or its PDF part; renders at 40 ppi change in 10 of the 13 files with patterned type, 8 closer to the file's own page (one by under 0.01 points, in a file whose render differs from its page almost everywhere either way), 1 further by 0.03 points of its pixels (an envelope of type there now opens live in place of its drawn art), 1 not compared (its page renders at another size); notes change in 3 files: one loses its type note, one loses the note for type in an envelope and, now compared with its page, gains its type notes, and one that opens from its PDF part names a smaller difference. Tests `ate::tests::a_run_painted_by_a_patterns_art_style_takes_the_pattern`, `a_runs_pattern_stays_where_the_document_has_it`, `tests_native::type_painted_with_a_pattern_takes_it_from_the_art_style_its_paint_names`. Scores and estimates unchanged. (#6856) | | 2026-11-12 | minor | Explicit editing-data import keeps a single artboard beyond a capped 14,400 pt PDF page (#6865), with a warning; automatic mode stays unchanged. Scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index bf159f5f00..2c8afc7aea 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1131,11 +1131,10 @@ page) opens from its editing data alone: its type is made from the file's text d area type and type on a path), and what can't be is left out with a warning. Non-native art (the content of a placed PDF, which Illustrator shows but doesn't edit and keeps as a PDF inside the editing data) is drawn by the PDF importer, as a group named "Non-native art" fitted to the object's box; one whose PDF can't be read is left out with a warning. -Without editing data it says it can't be opened. `pages` that name every page of a file saved without PDF compatibility also open it from its -editing data. -Without editing data it says it can't be opened. `pages` that name every page of such a file also open it from its -editing data. `file.place` reads it from its editing data too and places the art of the layers that show on artboard -`page`, clipped to that artboard unless `crop` is `bounding`. `clipboard.importPdf` takes every object of its editing +Without editing data it says it can't be opened. `pages` that name every page of a file saved without PDF compatibility +also open it from its editing data. `file.place` reads it from its editing data too and places the art of the layers +that show on artboard `page`, clipped to that artboard unless `crop` is `bounding`. `clipboard.importPdf` takes every +object of its editing data. What a PDF holds comes in as editable art: soft masks become opacity masks (an alpha mask as a white copy of its art; the backdrop colour gives Clip, an inverting transfer function Invert), transparency groups keep isolation and knockout, @@ -1795,6 +1794,11 @@ path to a value inside a list or an object, and the document and its undo histor → invalid parameters for `view.saved.edit`: `edits[0].delete` must be true or false, not 1 ``` +A schema nests at most 16 lists and objects. A value that would go past that depth is refused with the same kind of +parameter error, ``invalid parameters for ``: `` is nested too deeply``, where `` is the path to the +value. A schema that is wrong in itself, such as one that nests past 16 levels or puts a list of ids or a point +inside 16 lists, is an internal error in the command, and the command does not run. + An omitted value with a `default` takes it (`rotation` 0 in `view.saved.new`); the journal keeps the params as they were given. Saved steps played from a journal or an action keep a key the schema does not name, unless its value nests more than 16 levels deep, and the values of the parameters it names are checked as in a new call. The schemas of built-in commands belong to API level 3 @@ -2982,13 +2986,14 @@ already walks Image Trace. Short agent entry points: the file at `path`, else a picked one, or the file's text `data`, adds its set after the other sets and returns `{set, name, actions}`. A set named like one already in the panel gets the next free number (`Print 2`), and the other sets and the current set stay as they are. An action set file (`.vcactions`) is JSON: - `{"format": "vcactions", "version": 1, 2 or 3, "name", "actions": [{"name", "steps": [{"command", "params", "excluded"?}]}]}`, each step + `{"format": "vcactions", "version": 1 to 4, "name", "actions": [{"name", "steps": [{"command", "params", "excluded"?}]}]}`, each step a command id and its params as `command.batch` takes them, or a stop: the command `action.stop` with - `{message, allowContinue}`. `excluded: true` preserves a step but omits it from playback; - an absent or false flag includes the step. Files with stops use version 3, and files with excluded steps and no stops - use version 2, so older builds refuse them - instead of playing the excluded steps or failing at a stop; other files use version 1. A file with another `format` or a `version` other than - 1, 2 or 3, a stop whose message is not text or whose `allowContinue` is not true or false, a file larger than 8 MiB, one with more than 1,000 actions and one with an action of more than 10,000 steps are + `{message, allowContinue}`. A Select Object step is the command `select.byNote` with `{note, caseSensitive, + wholeWord}`. `excluded: true` preserves a step but omits it from playback; + an absent or false flag includes the step. Files with Select Object steps use version 4, files with stops and no + Select Object step use version 3, and files with excluded steps and neither use version 2, so older builds refuse them + instead of playing the excluded steps or failing at a stop or a Select Object step; other files use version 1. A file with another `format` or a `version` other than + 1 to 4, a stop whose message is not text or whose `allowContinue` is not true or false, a Select Object step whose params `ui.action.insertSelectObject` would refuse, a file larger than 8 MiB, one with more than 1,000 actions and one with an action of more than 10,000 steps are refused, and no set is added. So is a file whose set `ui.actionSet.save` would write larger than 8 MiB (a file with less white space, a set name that gets a number, or an `.aia` set), with the error `the action set would be larger than 8 MiB`. The Actions panel menu's Save Actions… and Load Actions… run these; Load Actions… is @@ -3081,6 +3086,28 @@ already walks Image Trace. Short agent entry points: `actionInsertMenuItem` dialog (`find`, `command`, `params`, `set`, `action`, `step`): typing in Find and pressing Find picks the one item whose menu path, shown name or command id holds every word typed, or lists the matches, and OK runs this. +- Actions: `ui.action.insertSelectObject {set?, action?, step?, note, caseSensitive?, wholeWord?}` inserts a Select + Object step without running it. The step is `select.byNote {note, caseSensitive, wholeWord}`: during playback it + selects the objects whose Attributes note matches `note`, and the steps after it act on them. `note` loses its + leading and trailing spaces and must then be 1 to 1,024 bytes; `caseSensitive` and `wholeWord` default to false. The + place, the selected step and the result are as `ui.action.insertStop` has them. A missing or empty note, a param of + another type, params that are not an object, an index past the last set, action or step, no action and no + recording, or a step that would give the action more than 10,000 steps or its set's file more than 8 MiB is an + error, and then nothing changes. When the step finds no object, the playback stops there with that error: at + Accelerated the whole batch is undone as for any failing step, and at Step by Step and Pause For the steps already + played stay. The panel's row for the step reads `Select Object: `. The panel menu's Select Object… opens the + `actionSelectObject` dialog, Set Selection (`note`, `caseSensitive`, `wholeWord`, `set`, `action`, `step`), whose OK + runs this; OK is off while the note is empty. The two options, the 1,024-byte limit and stopping when nothing is + found are VectorCraft's own rules. +- Select: `select.byNote {note, caseSensitive?, wholeWord?}` selects the objects whose Attributes note + (`attributes.set {note}`) holds `note` without its leading and trailing spaces, and returns `{count, ids}`. By default + the text may be anywhere in the note and in any letter case. `caseSensitive: true` asks for the same letter case, and + `wholeWord: true` for no letter, digit or `_` right before or after the text. It looks at the objects Select All + takes and the objects inside them, and leaves out hidden and locked objects and art on a locked artboard; in + isolation mode it looks inside the isolated group only. An object whose note matches is selected without the objects + inside it, and a member whose note matches is selected on its own. The objects found replace the selection, in paint + order. The command makes no undo step, and Select › Reselect repeats it. An empty note, a note longer than 1,024 + bytes, a param of another type, or no object found is an error, and then the selection stays as it was. - Actions: `ui.action.continue {}` plays on from the stop the playing action waits at, on the document active now, and closes the stop's message box (`actionStopMessage`). The next step runs at once, or at Accelerated the steps up to the next stop as one undo step. It returns `{results, pending, atStop?}`. With no action waiting at a stop it is an @@ -3678,7 +3705,9 @@ colorize color of an image it applies to and the pixels of other images: at most image, spread evenly, and 1,048,576 pixels of at most 64 images in all, leaving out pixels less than half opaque and images it can't decode; each image is decoded once for all its picks. In a clip group, or under an opacity mask that clips, it reads only what shows inside the clipping path or the mask art, and a blend, envelope or repeat that a -marquee touches is read whole. Hidden or fully transparent objects and fill or stroke items are left out, and locked +marquee touches is read whole. The symbol instances read place at most 16,000,000 objects in all, as on the canvas, +and an instance whose art would pass that is left out. The pixels read inside clip groups are tested against at most +4,000,000 clipping-path elements in all; the picks of an image inside clip groups that would pass that are left out. Hidden or fully transparent objects and fill or stroke items are left out, and locked objects are read. As VectorCraft's own rule, each object read weighs the same, shared among its colors (an image's among its pixels; the vector art a symbol instance places counts as one object, and each image it places counts on its own), and similar colors merge (k-means in Lab) into at most `colors` (1 to 64, default 5), each shown by its @@ -4293,7 +4322,10 @@ document's raster effects resolution (shadows and outer glows under the art; a b the object with the image). Type with a geometry effect (Outline Object included) or with fills and strokes of its own is outlined; type that has no fills or strokes of its own and whose only effects are shadows or outer glows stays type, with the image under it. A group's or layer's own fills and strokes become objects among its members, and its -members are expanded too. The result is `{ids}`; when an image in the art can't be decoded, the images made from +members are expanded too. A symbol instance whose topmost fill or topmost stroke is visible, has an opacity above 0 +and has a geometry effect becomes a group of its art: that fill's effects reshape the filled shapes of the art and that +stroke's effects reshape its stroked shapes, which keep their colors, as the canvas draws them (VectorCraft's own +rule); the instance's other fills and strokes are dropped. The result is `{ids}`; when an image in the art can't be decoded, the images made from raster effects do not show it, and the result also carries the `warning` that Flatten Transparency gives. A path's strokes stay strokes, as the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help @@ -4817,8 +4849,9 @@ the curve at an end), and the neighbours' handles keep their directions (their l moved there: the tool's click-and-drag on a segment). `op: "extend"` with `x`, `y` goes on from the `end` (default) or the `start` of an open subpath (the new end curves into the path unless `corner` is true), and `op: "close"` closes it from that end; `from` says how the old end bends into the new segment: `"keep"` (default) keeps its curve, `"smooth"` curves it through its neighbours (a point the tool -placed), `"corner"` leaves it without handles. Alt-click or double-click toggles a point with `path.convertAnchor`, and -Backspace/Delete removes the current point with `path.removeAnchor`. +placed), `"corner"` leaves it without handles. Double-click, or Alt-click on any point but an end of an open subpath, +toggles a point with `path.convertAnchor`; an Alt-click on an end of an open subpath only makes it the current point +(`select.anchors`), so the next click extends from it. Backspace/Delete removes the current point with `path.removeAnchor`. ```json {"name":"run_command","arguments":{"command":"path.curvatureEdit","params":{"id":12,"op":"move","anchor":2,"x":260,"y":140}}} @@ -5821,11 +5854,18 @@ through the views in tab order and add `view` to their reply for a document with reports `windows` (every window as `[document index, view number]`, in tab order), `currentWindow` and each pane's `view`. Views are not saved. `window.control.dock {edge}` (desktop app) docks the Control bar to the top of the window, under the menu bar -(`edge: "top"`, the default), or to its bottom (`"bottom"`), and returns `{edge}`. The bar's panel menu runs it with -Dock to Top and Dock to Bottom, the edge in use checked, and so does a drag of the bar's gripper, which docks the bar at -the edge the pointer is released nearer and shows a band along that edge while it moves. The edge is kept with the -workspace, and a workspace saved without it docks the bar at the top. Another `edge`, or none, fails with "`edge` must -be one of top, bottom" and leaves the bar where it is. +(`edge: "top"`, the default), or to its bottom (`"bottom"`), or floats it over the window (`"float"`), and returns +`{edge}`. A floating bar floats where it last floated; the first time, its top-left corner is at 60, 80 in window +points. It is 800 points wide, or as wide as the window when that is narrower, takes no room from the canvas, and is +kept inside the window below the menu bar. The bar's panel menu runs the command with Dock to Top and Dock to Bottom, +the edge in use checked and neither while the bar floats. So does a drag of the bar's gripper: released within 24 +points of the top (under the menu bar) or the bottom of the window it docks the bar at that edge, showing a band along +that edge while it moves, and released farther from both edges it floats the bar there, showing the bar's outline while +it moves. In a window too short for a floating bar between those two zones, the release docks the bar at the nearer +edge. Escape cancels the drag, and a release outside the window leaves the bar where it was. The edge, whether the bar +floats and where it floats are kept with the workspace, and a workspace saved without them docks the bar at the edge it +names, or at the top. Another `edge`, or none, fails with "`edge` must be one of top, bottom, float" and leaves the bar +where it is. `window.control.options {group, visible?}` (desktop app) turns a group of the Control bar's options on (`visible: true`), off (`false`) or toggles it (omitted), and returns `{group, visible}`. The groups are `snapping` (the Snapping menu), `anchors` (Convert and Anchors), `toolOptions` (the active tool's options), `objectOptions` (Isolate Selected @@ -5883,8 +5923,11 @@ 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. In -the New Document dialog, Manage Profiles lists the profiles with Edit and Reset buttons. Edit is available only when +`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar. 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 +profile's file until the document is saved. In the New Document dialog, Manage Profiles lists the profiles with Edit and Reset buttons. Edit is available only when there is a profiles folder, and Reset only for a profile that has a file. An unknown profile name is an error that lists the names. @@ -9653,7 +9696,10 @@ right/left/down/up; none stored means the smooth mesh through the points, as old `object.envelope.setMeshPoint {id, index, x, y, handle?}` and `object.mesh.movePoint`, `object.mesh.addLine` and `object.mesh.deletePoint` edit them like a gradient mesh's (one undo step each). On the canvas a selected envelope shows its mesh; the Mesh tool and Direct Selection drag its points and the clicked point's handles, and the Mesh tool -adds a row and a column where it clicks inside. `press_key` Escape during a drag of a point or handle of a mesh +adds a row and a column where it clicks inside. `object.mesh.addLine`, and `object.mesh.create` with `at`, take a point exactly on +the mesh's outline (within a millionth of a point) on any side without `tolerance`; a point outside needs `tolerance`. `object.mesh.addLine` at a point that is already a mesh +point adds no line and records no undo step unless its `color` changes a gradient mesh's point (a mesh envelope's points +have no color). `press_key` Escape during a drag of a point or handle of a mesh envelope or a gradient mesh cancels it: the point goes back and no undo step is added. The Control bar shows Edit Envelope / Edit Contents, the warp's style, orientation, bend and distortions (or the mesh's rows and columns), Reset (an unbent warp, a flat mesh) and Envelope Options. @@ -10521,8 +10567,9 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ## Image Tools add-on -Image Tools is a built-in add-on for placed images: its command is `addon.image.removeBackground`, and in the desktop -app it lives in Object › Plug-ins › Image Tools. It is a VectorCraft addition. +Image Tools is a built-in add-on for placed images: its commands are `addon.image.removeBackground`, +`addon.image.colorMask`, `addon.image.removeColorMask` and `addon.image.applyColorMask`, and in the desktop app it +lives in Object › Plug-ins › Image Tools. It is a VectorCraft addition. ### Remove Background @@ -10569,6 +10616,59 @@ a preview step does not keep them. {"name":"run_command","arguments":{"command":"addon.image.removeBackground","params":{"background":"corners","contiguous":false,"match":"channels","tolerance":12.55,"softness":0}}} ``` +### Color Mask + +`addon.image.colorMask` hides colors of the selected images, or of the images in `ids`, and leaves their pixels as +they are. It takes `background`, `colors`, `contiguous`, `match`, `tolerance` and `softness` with the same values, +defaults and refusals as `addon.image.removeBackground`, and matches colors the same way. The image keeps its own +pixels. The mask is kept with the image object and saved with the document: its settings, and a PNG of the image's +pixels with the hidden colors made clear (16-bit and gray images keep their depth and channels, with the source's color +profile and resolution). PDF's color key masking hides chosen colors of an image in a similar way +([ISO 32000-1 §8.9.6.4](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)). + +- The canvas, printing and separations, PDF (PDF/X-1a and PDF/X-3 flatten the hidden pixels as transparency), SVG, + EPS, the raster formats, DXF, EMF, WMF, the legacy .ai, the .ai editing data, copy and paste, and placing a document + show the masked pixels. A linked image stays linked. An output that refers to linked files instead of embedding them + (SVG with `images: "link"`) writes the masked pixels in place of the link. +- A grayscale image's masked pixels have an alpha channel when the mask hides pixels. A colorize color on such an image + follows the rule for grayscale images with transparency (a spot color, black or white), and Color Mask refuses a mask + that hides pixels of a grayscale image colorized with a process color. A mask that hides no pixels shows the image's + own pixels, so a grayscale image with such a mask takes a process color. Each image is checked on the pixels its new + mask shows, whatever other images in the document hold. Remove Background checks the image's own pixels, which it + clears. +- A click anywhere in the image's frame selects it, hidden pixels included, as it does for an image with clear pixels. + The Eyedropper, Object Mosaic, Create Gradient Mesh, Crop Image's trim and Image Trace read the image's own pixels, + hidden colors included. +- Running the command again on a masked image replaces its mask. All the images change in one undo step. An image whose + mask does not change is left as it is, and when none changes the command adds no undo step and returns `changed: 0`. + `hidden` counts the pixels made fully clear in the images that changed. +- When the image's own pixels are replaced later (Update Link, Relink, Crop Image, a recolor, or a linked file read + again when the document opens), the mask is made again for the new pixels. When the new pixels can't be masked (CMYK + pixels, missing pixels, every pixel would be hidden, or the image is grayscale and colorized with a process color + and the mask would hide some of its pixels), the mask keeps its settings and hides nothing. +- The command refuses, and changes nothing, when an object in `ids` is not an image, an image is CMYK, a linked image + shows its preview (embed or relink it first), an image would need more than the decode allowance, or the mask would + hide every pixel of an image. +- With none of `background`, `colors`, `contiguous`, `match`, `tolerance` and `softness` given, nothing changes, and + the command returns the mask settings of the first image (the defaults when it has no mask) with `masked`. Color + Mask… opens the command's dialog on those settings, with a Preview that works as Remove Background's does. + +→ `{changed, ids, hidden}`, or without settings `{background, colors, contiguous, match, tolerance, softness, masked}` + +`addon.image.removeColorMask` takes the mask off the selected images, or the images in `ids`, in one undo step, and +the images show their own pixels again. `addon.image.applyColorMask` makes each mask part of its image: the masked +pixels become the image's own, embedded as a PNG with an alpha channel (a linked image is embedded), and the mask is +taken off, in one undo step. A mask that hides nothing is only taken off, and the image keeps its pixels and its link. +Images without a mask are left as they are, and an object in `ids` that is not an image is refused. Apply Color Mask +also refuses, and changes nothing, when a mask made again for new pixels would give a grayscale image colorized with a +process color an alpha channel. Both commands are +enabled only when a selected image has a mask. → `{changed, ids}` + +```json +{"name":"run_command","arguments":{"command":"addon.image.colorMask","params":{"background":"colors","colors":"#00ff00","contiguous":false,"tolerance":15,"softness":10}}} +{"name":"run_command","arguments":{"command":"addon.image.applyColorMask","params":{}}} +``` + ## Type Tools add-on Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker` and `addon.type.releasePath`, and diff --git a/docs/roadmap.md b/docs/roadmap.md index 4c78d258c9..5d2a1dc435 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -52,6 +52,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | Swatches: in a panel made taller the swatch list fills the space above the footer instead of scrolling inside 150 or 200 pt (#1638; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/swatches/tests.rs`). Scores and estimates unchanged. | | 2026-11-10 | minor | M13 / G6: MCP catalogue (#6460): headless lists UI commands, eight prompts, 33 tools, effect vs command ids; scores and estimates unchanged. | | 2026-11-08 | minor | Character Styles panel: a double-click on a user style's row opens its Character Style Options (`ui.charStyleOptions`); the dialog keeps a fixed width and scrolls its sections in a shorter window, so OK and Cancel stay on screen. Tests `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options` and `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`. Scores and estimates unchanged. | | 2026-11-08 | minor | #3380, deletion only: preserve gradient placement and exact surviving geometry; consume owned subpaths with a shared original-node snapshot; consolidate status/evidence and document command/helper contracts. Compound behavior and the existing M2 status entry are retained. Endpoint highlighting remains open; scores and estimates unchanged. | @@ -147,7 +148,7 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (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 (#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) | 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, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); 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 | 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, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); 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 | 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) | 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 | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; `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; 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/target-app-parity.md b/docs/target-app-parity.md index d5851d78ce..1ce5c5fda5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (`.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -53,6 +53,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | Swatches: in a panel made taller the swatch list fills the space above the footer instead of scrolling inside 150 or 200 pt (#1638; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/swatches/tests.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Swatches panel: its menu's Show Recent Colors hides and shows the panel's Recent Colors row, checked by default and kept between sessions apart from the Color panel's (#6617); scores unchanged. | | 2026-11-09 | minor | Stroke panel: Line Arrow, a 41st generated arrowhead: 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, a sharp tip and square-cut ends, twice as wide as the other heads; bounds and clicks follow each head's own reach (`stroke.set` `LineArrow`, #5421); scores and estimates unchanged | | 2026-11-09 | minor | Canvas: a 3D effect (Extrude & Bevel, Inflate, Rotate, Revolve) changed on type or a group draws again where its art was and is, measured by that art; the canvas measures through its renderer and draws the part with the art it made to measure it. Exports and Object › Rasterize take the solid of 3D type. Fit to Artwork Bounds and per-artboard SVG export measure every artboard through one renderer, building each solid once. A 3D effect on a fill or stroke that builds nothing (Revolve after Roughen) no longer overflows the stack on the canvas, in Object › Rasterize and in raster and EPS exports: the fill or stroke draws as without it. Tests `tests::changed::a_3d_effect_changed_on_type_or_a_group_changes_where_its_solid_was`, `fx::tests::a_renderer_measures_the_art_on_each_artboard_building_each_solid_once`, `canvas::tests::an_edit_to_a_3d_effect_redraws_with_the_art_measured`, `fx::tests::a_3d_effect_that_builds_nothing_draws_the_item_as_without_it`. Scores and estimates unchanged. | @@ -225,7 +226,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (nine generated libraries including Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Rotate, Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | @@ -249,7 +250,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | -| Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | +| Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | @@ -494,7 +495,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of similar groups, transform nuances (the rotated persistent bounding box is done) | 4–6 | | Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | | Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (nine generated in code including Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | @@ -508,7 +509,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | -| Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Smart Guides' angle and distance readouts while drawing, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812) | 2–4; status-bar X/Y uses the active ruler origin and General units | +| Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812; distance and angle labels while drawing, #2983) | 2–4; status-bar X/Y uses the active ruler origin and General units | | File formats | 6 | 85% | Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), legacy `.ai` files saved without the prolog that defines their operators (their own operator set isn't read yet), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done, as are the Japanese papers in its Media list: JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判, beside the ISO B4/B5 that settings saved before them keep) | 1–2 | @@ -572,6 +573,7 @@ since 2026-10-01. - Window › 3D and Materials panel: `crates/ui-egui/src/panels/three_d.rs` applies a 3D effect by object type (Plane, Extrude, Revolve, Inflate), changes an applied one in place (`effect.setParams` `threeDType`) and edits it with the options dialog's Object, Rotation and Lighting controls, one undo step per change; `crates/engine/src/cmd/effectcmd/three_d_type_tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. No Materials tab. - 3D and Materials › Quick Actions › Expand as Wireframes (#6354): `effect.expandAsWireframes` replaces each selected 3D object with a group of 0.5 pt black stroked paths, the edges of the faces its effect draws, each edge once and joined end to end, curves kept, in one undo step ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs`, `crates/engine/src/cmd/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. +- 3D effects, images a clip hides: an image in a clipping group is left out of the solid when its transformed frame lies wholly outside the area every clipping path around it fills together, holes included, instead of when only the boxes miss; an image the clips show part of is still refused ([the help page](https://helpx.adobe.com/illustrator/using/clipping-masks.html) on clipping paths hiding everything outside their shape; the omission rule is VectorCraft's own). `solids::tests_sources::an_image_inside_a_clips_box_but_outside_its_shape_is_left_out` covers it. Scores and estimates unchanged. - **Status-bar pointer readout (2026-10-18):** uses the same effective ruler origin as the position fields, then formats the relative X/Y in General units. The absolute pointer position, document, selection, Undo/Redo and saved state are preserved. Three `chrome::tests::status_coordinates_*` painted-text regressions cover zero/positive/negative origins, unit conversion, global/artboard mode, active artboard, reset and missing pointer/document. Original headless status-bar captures were reviewed before and after the change. Scores and hours are unchanged. @@ -619,7 +621,7 @@ since 2026-10-01. - **Global Edit Options in the Control bar:** while Select › Start Global Edit can run, the Control bar shows a Global Edit Options dropdown that opens the same options as the Properties panel's (Match: Appearance, Size; On Artboards; Include Objects On Canvas; Result(s)); both set the same options. The dropdown is off while Global Edit is on; it sits after Recolor Artwork, ahead of the X/Y/W/H fields ([Edit similar objects globally](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)). Regression test: `the_control_bar_shows_the_global_edit_options` in `crates/ui-egui/src/chrome/tests.rs`. - **Global Edit's enabled check on large paths:** the check that decides whether Select › Start Global Edit can run on the selected path, compound path or symbol instance (which the Control bar makes every frame) measures the box of its anchors and handles instead of building and normalizing a copy of every anchor, with the same answer. On a 200,000-anchor path the check takes 0.7 ms instead of 2.2 to 3.0 ms. Regression tests: `support_*` in `crates/engine/src/cmd/globaledit.rs`. - **Control bar's inline X, Y, W and H fields fit the bar:** the Control bar shows the inline X, Y, W and H fields only when all four, their labels as drawn in the current language and the W/H link fit inside the bar's margin; otherwise it shows the Transform link alone. This is VectorCraft's own layout rule. Regression test: `the_control_bar_shows_the_inline_transform_fields_only_when_they_fit` in `crates/ui-egui/src/chrome/tests.rs`. -- **Control bar docks to the top or the bottom:** the Control bar's panel menu, at the bar's right end, has Dock to Top and Dock to Bottom, the edge in use checked, and dragging the bar's gripper docks it at the top or the bottom edge of the window, whichever the pointer is released nearer, with a band along that edge while it moves (`window.control.dock {edge}`), as the help page describes ([Control panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/control-panel-overview.html)). Keeping the edge with the workspace, with older workspaces docking the bar at the top, is VectorCraft's own rule. Not done: dragging the gripper away from both edges to float the bar. Regression tests: `the_control_bar_panel_menu_docks_it_to_the_top_or_the_bottom`, `dragging_the_control_bar_gripper_docks_it_at_the_nearer_edge`, `the_control_bar_dock_command_takes_top_or_bottom` and `menus_stop_above_a_control_bar_docked_at_the_bottom` in `crates/ui-egui/src/chrome/tests.rs`, `saved_workspaces_restore_the_control_bar_edge` in `crates/ui-egui/src/workspaces.rs`. +- **Control bar docks to the top or the bottom, or floats:** the Control bar's panel menu, at the bar's right end, has Dock to Top and Dock to Bottom, the edge in use checked and neither while the bar floats. Dragging the bar's gripper and releasing it within 24 points of the top (under the menu bar) or the bottom of the window docks it at that edge, with a band along that edge while it moves; releasing it farther from both edges floats the bar there, with its outline under the pointer while it moves, and a floating bar's gripper moves it or docks it again (`window.control.dock {edge: "top"|"bottom"|"float"}`), as the help page describes ([Control panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/control-panel-overview.html)). Escape cancels a gripper drag. The 24-point zones, the floating bar's 800-point width and first position, a release outside the window leaving the bar where it was, a window too short for a floating bar docking it at the nearer edge, the floating bar staying inside a window that shrinks, and keeping the edge and the floating position with the workspace, with older workspaces docking the bar at their edge, are VectorCraft's own rules. Regression tests: `the_control_bar_panel_menu_docks_it_to_the_top_or_the_bottom`, `dragging_the_control_bar_gripper_docks_it_at_the_nearer_edge`, `dragging_the_control_bar_gripper_away_from_both_edges_floats_it`, `floating_control_bar_moves_and_redocks_from_each_edge`, `floating_control_bar_menu_docks_to_either_edge`, `control_bar_drag_escape_restores_placement`, `control_bar_drag_release_outside_window_keeps_previous_placement`, `floating_control_bar_stays_reachable_in_tiny_and_resized_windows`, `the_control_bar_dock_command_takes_top_bottom_or_float` and `menus_stop_above_a_control_bar_docked_at_the_bottom` in `crates/ui-egui/src/chrome/tests.rs`, `saved_workspaces_restore_the_control_bar_edge` and `saved_workspaces_restore_floating_control_bar_position` in `crates/ui-egui/src/workspaces.rs`. - **Control bar panel menu turns groups of options on or off:** the Control bar's panel menu lists the bar's groups of options (Snapping, Anchor Points, Tool Options, Object Options, Image Options, Fill and Stroke, Opacity, Graphic Style, Character, Paragraph, Vertical Alignment, Align and Distribute, Transform, Artboard Options and Document Options) above Dock to Top and Dock to Bottom, each checked while it is on; a click turns that group off or on (`window.control.options {group, visible?}`), and a group that is off stays out of the bar even while its tool or object is selected, as the help page describes ([Control panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/control-panel-overview.html)). The list of groups and what each holds, every group on to start, a group that is off leaving its room to the groups after it, and keeping the groups with the preferences and the workspace are VectorCraft's own rules. Regression tests: `the_control_bar_panel_menu_turns_each_group_on_or_off`, `the_control_bar_keeps_its_label_and_menu_with_every_group_off`, `the_control_bar_panel_menu_scrolls_in_a_short_window`, `the_control_bar_options_command_turns_a_group_on_or_off`, `groups_that_are_off_leave_their_room_to_the_later_groups`, `the_artboard_tool_s_control_bar_follows_its_two_groups` and `the_anchor_points_group_holds_convert_and_anchors` in `crates/ui-egui/src/chrome/tests.rs`, `the_image_options_group_holds_the_image_and_trace_controls` in `crates/ui-egui/src/tests/place.rs`, `the_character_and_paragraph_groups_hold_the_type_controls` in `crates/ui-egui/src/panels/paragraph/tests.rs`, `saved_workspaces_restore_the_control_bar_groups` in `crates/ui-egui/src/workspaces.rs`. - **Pattern-only backquote drags:** With Selection move, bounding-box scale or rotate, or the Rotate, Reflect, Scale or Shear tool, backquote held at mouse release applies the drag matrix to selected pattern paint while object geometry stays in place. The key may be pressed after mouse press; if released before the mouse button, the drag commits as an ordinary transform. Objects without pattern paint stay still; stroke-only patterns and patterned objects in mixed selections take the same matrix. Regression tests: `backquote_move_uses_release_state_and_one_commit` and `backquote_box_scale_and_rotate_use_pattern_matrix_at_release` in `select/tests.rs`, `backquote_drag_previews_and_commits_pattern_only_for_each_transform_tool` in `xform/transform.rs`, `selection_backquote_drag_changes_pattern_fill_and_stroke_without_moving_mixed_art` and `selection_backquote_drag_changes_stroke_only_pattern` in `tests/pattern.rs`, `egui_backtick_drag_uses_key_state_at_release` in `canvas/tests.rs`, and `synthetic_pointer_backquote_keeps_solid_object_in_place` in `control/tests.rs`. Scores and hours unchanged. - **Existing-guide Escape cancellation (G1):** Escape clears a pending guide press or drag through Selection and Direct/Group Selection, cancelling a begun preview. Eight app-input regressions cover both axes, move/copy, temporary selection-tool borrowing from idle Pen, preselected-guide document/interaction-start selection and Undo/Redo/saved-state preservation, later on-canvas motion/release, Shift-press cancellation, and ordinary-release/Enter/idle controls. Historical focused checks on `8ab574b7` recorded five expected RED failures with three passing controls, then all eight GREEN tests and the Direct Selection Escape control passed. All nine also passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. The original 1280×960 headless app capture from `b076025a` was reviewed for one vertical Selection guide after Escape; source review found its scene unchanged on `a0671777`. Scores and hours unchanged. @@ -719,7 +721,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL and HP-GL, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/tests.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. - **Architecture:** 19+ crates with enforced layering (`cargo xtask layers`). Every action is a command (~400 engine + ~50 UI). Undo is unlimited via structural sharing. `command.batch` runs several commands as one transaction. -- **Parameter schemas:** a command can carry a machine-readable parameter schema (the new `vectorcraft-apischema` crate): each parameter's type, range, unit, whether it is required, its default, whether null counts as left out, and the API levels it was added and deprecated at. `engine.commands` lists the schema in the shape of a JSON Schema 2020-12 object schema, a test keeps the command's `params` text equal to the text the schema writes, and a new call has the params checked against it before the command runs (batch steps before the first step), with an error naming the parameter and no change to the document; saved steps keep a key the schema does not name, and their values are checked. The View commands `view.capsLock`, `view.saved.new`, `view.saved.edit`, `view.saved.list`, `view.transparencyGrid` and `view.snapToGlyph.options` have schemas. The schemas belong to API level 1 (`vectorcraft_engine::schemas::API_VERSION`), and a test fails when a schema changes without a new level. Tests: `crates/apischema/src/tests.rs` (with `conformance.rs`, a separate check of the JSON form against the JSON Schema 2020-12 rules), `schemas::tests` and `cmd::views::tests::each_view_command_refuses_a_bad_value_naming_the_parameter` in `vectorcraft-engine`. +- **Parameter schemas:** a command can carry a machine-readable parameter schema (the new `vectorcraft-apischema` crate): each parameter's type, range, unit, whether it is required, its default, whether null counts as left out, and the API levels it was added and deprecated at. `engine.commands` lists the schema in the shape of a JSON Schema 2020-12 object schema, a test keeps the command's `params` text equal to the text the schema writes, and a new call has the params checked against it before the command runs (batch steps before the first step), with an error naming the parameter and no change to the document (a value nested past the schema's 16 levels is such a parameter error, and only a schema that is wrong in itself is an internal error); saved steps keep a key the schema does not name, and their values are checked. The View commands `view.capsLock`, `view.saved.new`, `view.saved.edit`, `view.saved.list`, `view.transparencyGrid` and `view.snapToGlyph.options` have schemas. The schemas belong to API level 1 (`vectorcraft_engine::schemas::API_VERSION`), and a test fails when a schema changes without a new level. Tests: `crates/apischema/src/tests.rs` (with `conformance.rs`, a separate check of the JSON form against the JSON Schema 2020-12 rules), `schemas::tests` and `cmd::views::tests::each_view_command_refuses_a_bad_value_naming_the_parameter` in `vectorcraft-engine`. - **Input schemas in the command listings:** `engine.commands` and the MCP tools `command_list` and `list_commands` give each command with a parameter schema an `inputSchema` next to `schema`: the same schema with the root `type` `"object"`, the form an MCP tool's input schema takes ([MCP schema reference](https://modelcontextprotocol.io/specification/2026-07-28/schema)). A command without a schema lists neither, and `brief` leaves out both schemas with the `params` text. Tests: `schemas::tests::engine_commands_list_an_input_schema_with_an_object_root` and `schemas::tests::an_input_schema_keeps_deprecation` in `vectorcraft-engine`, and `tests::conventions::command_listings_carry_input_schemas` in `vectorcraft-mcp`, which check every listed input schema against the JSON Schema 2020-12 rules. - **Command API reference:** `engine.apiReference` returns a Markdown reference written from the parameter schemas when it is asked for, and MCP serves the same text as the resource `vectorcraft://commands/reference` (`text/markdown; charset=utf-8`). Each command that has a schema gets a section in registry order with its label, menu path, API levels, what it writes, summary and return, and a table of its parameters (type, range with its ends marked included or not, unit, default, required, levels and description; members of objects as dotted rows). Commands without a schema, plug-in commands included, are left out. Schema text is escaped so it stays plain text in its table cell, the same build always returns the same bytes, and a reference past 1 MiB is an error rather than a cut-short text. The command's own schema raised the API level to 2. This is a VectorCraft documentation feature; no score changes. Tests: `cmd::apiref::tests` and `schemas::tests` in `vectorcraft-engine`, `resources::tests` in `vectorcraft-mcp`. - **Automation:** @@ -742,6 +744,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: the panel menu's Playback Options… sets how actions play: Accelerated (the default) plays every step at once, Step by Step plays one step at a time with the canvas drawn after each, and Pause For waits the given number of seconds between steps ([Specify playback speed](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/specify-playback-speed.html); `ui.action.playbackOptions`). VectorCraft's own rules, which the page does not cover: the pause is a whole number of seconds from 1 to 60, the setting is kept with the UI preferences, a paced playback ends at Stop Playing/Recording or when a step comes due while another document is active, each step of a paced playback is its own undo step, and Batch… plays at full speed. - Actions panel: the panel menu's Insert Stop… opens Record Stop, with a Message box and Allow Continue, and adds a stop to the recording in progress, after the selected command, or at the end of the selected action ([Insert stops in actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-stops-in-actions.html); `ui.action.insertStop`). A playing action waits at the stop and shows the message so the user can do a manual task, and Play Current Selection plays the rest ([Illustrator CS5 help](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=459); `ui.action.continue`). With Allow Continue, the message box also has Continue. VectorCraft's own rules, which the pages do not cover: an empty message still waits, Stop Playing/Recording ends the playback and keeps the steps already played, the rest plays on the document active then, a stop waits at every playback speed, at Accelerated the steps between two stops are one undo step, Batch… refuses an action with an included stop, and Delete Selection on a selected step deletes that step, a stop or a command, without asking (`ui.action.deleteStep`). - Actions panel: the panel menu's Insert Menu Item… adds a menu command to the recording in progress, after the selected step, or at the end of the selected action, without running it, and playback runs it as the menu does ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertMenuItem`). The dialog's Find box picks the one item that matches the words typed, and a click on a listed item picks it. VectorCraft's own rules, which the page does not cover: items that open a dialog, the Object › Align items, Image Trace's Make and Make and Expand, Pattern's Make and Edit Pattern, and the File, Window and Help menu items are not listed, and an action holds at most 10,000 steps and its set file at most 8 MiB, for stops too. + - Actions panel: the panel menu's Select Object… opens Set Selection, where the note typed names the objects to select, and adds a step to the recording in progress, after the selected step, or at the end of the selected action; playback selects the objects whose Attributes note matches it, and the steps after it act on them ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertSelectObject`, `select.byNote`). VectorCraft's own rules, which the page does not cover: the note matches anywhere and in any letter case unless Case Sensitive or Whole Word is checked, hidden and locked objects are left out, the objects found replace the selection, a step that finds none stops the playback with an error, and the note is at most 1,024 bytes. Action sets with the step save as version 4. - Actions panel: Delete Selection deletes the selected action set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. @@ -822,6 +825,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - These dialog sliders, each beside a number field, respond to the keyboard: those of the effect, tool option, brush and transform dialogs, the Perspective Grid, the 3D dialogs, and the flattener options, which the Flattener Preview panel also shows. A click, or Tab, gives a slider the keyboard focus, and an outline shows it. Then → and ↑ step the field's number up to the next whole number and ← and ↓ step it down to the next whole number, Shift with an arrow and Page Up and Page Down step it by ten, and Home and End set the slider's first and last value; no step goes past either end. Screen readers' increment and decrement actions step the slider as → and ← do. The Color panel's, Swatch Options', the Navigator's and the Character panel's sliders, and the Color Picker's channel slider, respond only to the pointer. The keys follow the WAI-ARIA slider pattern (); the reference app's help does not describe keys on a dialog's slider, so the step sizes are VectorCraft's own. - Screen readers get the value of the color and channel sliders that panels and dialogs draw (the Color panel, the Color Picker, Swatch Options, the Navigator's Zoom, the Character panel's variable font axes, the Perspective Grid and flattener options, and the sliders of the effect, tool option and transform dialogs): the number and text of the field beside each one, such as 128 for G or 50% for an opacity, with the slider's range, which extends to include a number past the slider's end. The harmony wheel's Brightness slider, which has no field, reports its brightness in percent. - A layer whose Layer Options › Print is off shows its name italic in the Layers panel, and while its row is dragged, as the reference application shows non-printing layers (#5739); a printing layer stays upright and ticking Print again restores the upright name (`panels::layers` test `a_layer_that_does_not_print_has_its_name_italic`). + - In the Layers panel only the primary mouse button drags. A drag with the right or middle button on a row, a guide row, the selection square, the eye or lock column or a target circle moves, copies, hides, locks and transfers nothing and records no undo step, and a right-click still opens the row's menu (`panels::layers` test `only_the_primary_button_drags_rows_guides_art_columns_and_appearances`). - Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel (in an OS window of its own on the desktop, #4135), and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on a dock group's tabs, which light up under the pointer, its panels join that group, and on the group's upper or lower half they make a new group above or below it (`window.panel.dock {anchor, zone}`); dropped on the icon column they become icons there, the tabbed group's panels too (`window.panel.dock {icon: true}`); dropped anywhere else on the dock, which lights up, they go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating groups stack into sets: dropped on the upper or lower half of another group (a line shows where), a group joins it right above or below it, and the set's groups stack top to bottom, each showing one panel, moving together by the top group's title bar, whose × docks them all; a group dragged by its tab strip leaves the set (`window.panel.float {below, above}`). A double-click on a tab collapses a floating group to its tabs (`collapsed`), and a dock group too, a group below it moving up into the room; a second double-click, or a click on another of its tabs, expands it (`window.panel.collapse`, kept with the preferences and in saved workspaces). Sets dropped on the left edge of the icon column or of another dock column dock as dock columns (a multi-column dock, `window.panel.dock {column}`), whose groups stack, tab and tear out as a floating set's do, and whose top strip floats the column again. Floating panels, their sets and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, reordering tabs by dragging, collapsing a set or dock column to icons, dock columns right of the default dock, resizing floating panels and the groups of a set. - A floating panel's OS window hides while a tool group's flyout or the All Tools drawer is open in the main window, as it does under a modal dialog or a menu, and shows again when the flyout or the drawer closes (#5813; `a_tool_flyout_hides_the_palette_windows_until_it_closes`). - On the desktop a floating panel in an OS window stores the monitor it is on and reopens there at the next launch. When that monitor is no longer connected, the panel opens on the main window's monitor at the same offset (#5582). Outside macOS, a desktop whose monitors have different scale factors keeps opening floating panels on the main window's monitor. Test: `panel_docking::native_tests::a_floating_panel_reopens_on_the_monitor_where_it_was_left`. @@ -994,7 +998,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. 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). - - **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; Alt-click or double-click 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`). 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). + - **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. 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, the drag shows a thin line 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. @@ -1099,7 +1103,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Layer Options for several highlighted rows shows the first row's settings, and OK changes only the settings set in the dialog: each row keeps its own color, Template, Lock, Show, Print, Preview and Dim Images otherwise (`crates/ui-egui/src/dialogs/layer_options.rs` tests). As VectorCraft's own rule, a layer color (`layer.setProps`, `layer.new`, `layer.newSublayer`) or a Live Paint Gap Preview Color (`livePaint.gapOptions`) given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`) is an error and changes nothing, instead of being set without its alpha. Regression tests: `a_layer_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/layers.rs` and `a_gap_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/build.rs`. Panel Options › Locate Selected Objects (beyond Illustrator, off by default): when the last selected object changes on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as Locate Object does, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off. -- **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); with Smart Guides › Spacing Guides, a moved selection that lines up with nothing along an axis lands as far from its neighbour as two other objects of its row or column are apart, or halfway between its two neighbours, the equal gaps marked; with View › Snap to Grid on, a moved selection lands on the grid instead, by whichever of its edges is nearest a gridline on each axis (the center does not snap), #740, #1816; the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; Shift-clicked they join the selected art, and Shift-added art keeps them, so guides and art are selected together in either order, Delete then deleting both in one step; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes. Smart Guides: a point drawn with the Pen or a shape tool, and an anchor dragged with Direct Selection, snaps to where paths and ruler guides cross, labelled "intersect" (#1658, part of #1602; a moved selection's own anchors don't). +- **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); with Smart Guides › Spacing Guides, a moved selection that lines up with nothing along an axis lands as far from its neighbour as two other objects of its row or column are apart, or halfway between its two neighbours, the equal gaps marked; with View › Snap to Grid on, a moved selection lands on the grid instead, by whichever of its edges is nearest a gridline on each axis (the center does not snap), #740, #1816; the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; Shift-clicked they join the selected art, and Shift-added art keeps them, so guides and art are selected together in either order, Delete then deleting both in one step; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes. Smart Guides: a point drawn with the Pen or a shape tool, and an anchor dragged with Direct Selection, snaps to where paths and ruler guides cross, labelled "intersect" (#1658, part of #1602; a moved selection's own anchors don't). With Smart Guides › Measurement Labels on, the Line Segment tool labels the segment being drawn with its distance, angle and X and Y offsets (`D`, `Angle`, `dX`, `dY`), and the Pen, Curvature and Smart Pen tools label their rubber band the same way when Enable Rubber Band is on (#2983). A move that Shift keeps level, upright or diagonal stays on that line when it snaps, with the Selection, Group Selection or Direct Selection tool. It slides along the line until the selection lands on the grid or on whole pixels, lines up with the other objects or is spaced evenly with them, or until the line passes an anchor or crosses a ruler guide near the point the selection was grabbed by. A level or upright move snaps along its own axis only. Snap to Last Location: with Smart Guides on and Preferences › Smart Guides › Snap to Last Location on (off by default, VectorCraft's own choice), a selection moved by dragging with the Selection, Group Selection or Direct Selection tool, Shift too, goes back to where the move began while it is within Snapping Tolerance of it, labeled "last location"; an Alt copy is not pulled back onto its original, and with View › Snap to Grid or Snap to Pixel on the move snaps to the grid or to whole pixels instead (`prefs.set` key `snapToLastLocation`). The public [Smart Guides options](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html) page lists the option as snapping objects back to their previous position; the distance, the label, the copy rule and the grid and pixel rule are VectorCraft's own. Tests: `select::tests::snap_to_last_location_puts_a_move_back_where_it_began`, `select::tests::snap_to_pixel_wins_over_snap_to_last_location`, `direct::tests::snap_to_last_location_puts_a_path_moved_by_its_anchor_back`, `direct::tests::snap_to_pixel_wins_over_snap_to_last_location_for_a_path_moved_by_its_anchor`, `tests_prefs::snap_to_last_location_puts_a_dragged_square_back`. Pixel Preview: with View › Pixel Preview on, the tools use no Smart Guides. Nothing snaps to Smart Guides or shows their guides, and Snap to Point acts as it does with Smart Guides off. View › Smart Guides keeps its setting and applies again when Pixel Preview is turned off. [Work with Smart Guides](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/work-with-smart-guides.html) says Smart Guides cannot be used while Pixel Preview is on. Tests: `tests::smartguides::pixel_preview_turns_smart_guides_off`, `canvas::tests::pixel_preview_stops_smart_guides_snapping_a_move`. @@ -1122,6 +1126,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With the Artboard tool in use, a Shift-click on a row of the Artboards panel selects the artboards from the last row clicked without Shift to the clicked row, and the clicked row's artboard becomes the active one. When the artboard of the last row clicked without Shift is no longer selected, the range starts from the active artboard, and later Shift-clicks start from there too. A Ctrl/Cmd-click still adds or removes one artboard. A Shift-click used to add or remove one artboard as well. The public [Select artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/select-artboards.html) page lists Shift-click in the Artboards panel for selecting several artboards. In the Artboards panel, a click on the active artboard's options icon, or a double-click on another row's icon, opens Artboard Options for that row's artboard, and the panel menu's Artboard Options… opens it for the active artboard (part of #1876). Both used to choose the Artboard tool instead. Opened while another tool is in use, the dialog moves the art with a new X or Y when the Artboard tool's Move Artwork with Artboard option is on. With several artboards selected with the Artboard tool, the Artboards panel menu's Rename opens an empty name field on the active artboard's row (on the first selected row when the active artboard is not selected), and the name typed there goes to every selected artboard, numbered in panel order (abc-1, abc-2, abc-3), in one undo step (`artboard.setProps {artboards}`). A double-click on a name with Shift or Ctrl/Cmd held that leaves several artboards selected opens the same field; a Ctrl/Cmd double-click on an unselected row's name adds its artboard to the selection first. Both used to rename the active artboard only. With one artboard selected, Rename still gives it the name as typed. The public [Rename artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/rename-artboards.html) page numbers the name the same way for several selected artboards. + A right-click on a row of the Artboards panel opens a menu with Rename, as the [help page](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/rename-artboards.html) describes, with any tool. Rename opens the Rename dialog for the selected artboards, and OK names them in one undo step, numbered in panel order when there are several (`artboard.rename`); Cancel or a menu closed without a choice renames nothing, and a locked artboard can be renamed. A right-click on a row that is not selected first makes its artboard the only selected one and the active one, and on a selected row the selection stays; this is VectorCraft's own rule. A drag with the right button no longer moves a row. Artboard Options has X and Y fields beside a reference point locator (#1876), so an artboard's position can be typed as well as its size. X and Y are where the reference point lies, counted from the ruler origin (#1212), as the Transform panel and the Control bar show an artboard's position, and the locator is the one they and Properties share. A typed X or Y moves the artboard so that its reference point lands there, and a new Width or Height keeps the reference point in place; OK applies everything in one undo step. The shape dialogs still keep their X and Y to themselves (the click position). Pointer and key tests in `dialogs/tests.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html) (a reference point in a nine-point grid, then X and Y). Alt-clicking New Artboard in the Artboards panel opens Artboard Options for the new artboard, and OK adds it and makes it the active artboard (`ui.newArtboard`; behavior reference: [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), Use panels). A plain click still adds the artboard at once. With Align to Artboard chosen, the Align panel's Distribute Objects and Distribute Spacing buttons use the active artboard (`object.distribute` and `object.distributeSpacing` with `to: "artboard"` and `artboard`). The first object's left or top edge goes to the artboard's left or top edge, and the last object's right or bottom edge goes to the artboard's right or bottom edge. Distribute Objects spaces the other objects evenly by its button's line, and two objects are enough. Distribute Spacing makes the gaps between the objects equal. With anchor points selected, the buttons space the points among themselves and do not use the artboard. When an action plays, its Distribute Objects and Distribute Spacing steps with Align to Artboard use the artboard that is active then. @@ -1310,6 +1315,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, measured:** `crates/trace/tests/quality` traces drawings made from known vector art with every preset and [`image-trace-quality.md`](image-trace-quality.md) records the numbers against the baseline. Black and White, Grayscale and Color place each edge by the blend of the pixels across it (to a fraction of a pixel on anti-aliased and blurred images; hard-edged images are read as staircases) and fit outlines as Flat Logo does. *Measured* on each preset's own inputs, all sizes and variants: Default's outlines went from 0.31 px off on average to 0.09 (largest 1.51 to 1.02), Black and White Logo's from 0.27 to 0.06 with 0.3 kinks per trace where it had 15, and the gaps between abutting paths from 64 px to 22. On clean curved shapes Black and White Logo is 0.02 px off (the open tracer measured beside it: 0.20). The palette is made of the picture's own colours (blends along edges take none of it, colours that noise made of one colour merge, a blend pixel goes to one of the two colours it lies between; #1504): 16 Colors on flat art, all variants, went from 70 paths to 4.2 and from 5.1 px off to 0.13, with no path left in a colour the art doesn't have (5.9 before). Photos are smoothed within their tones before they are quantised and stacked layers go by lightness (#1516): High Fidelity Photo went from 3,653 paths to 121 with its colour error down from 2.30 to 1.75, and a 16 megapixel photo-like image is traced in 3.5 s where 4 megapixels were refused. Since then, by the same harness: outlines are cut at their junctions and each shared piece is fitted once (#1535: gaps and overlaps between abutting paths 22 to 50 px of area down to under 2); layers are traced within the box of their pixels and a few at a time (#1546: a 16 megapixel photo 3.9 GB to 0.9 GB); black and white are read against the image's own black and the paper near each edge (#1563, for thin lines in blurred and scanned art); Ignore Color and the Auto Color and Outline presets (#1574); Snap Curves To Lines levels lines within 2.5 degrees of level or upright (#1593, the angle our choice); Create: Strokes puts centre lines in the middle of their ink and makes them as wide as it (#1595: Outline 0.295 to 0.052 px from the true centre line, 18.4 to 2.7 anchors a stroke); sharp corners whose pixel is mostly outside the shape stay corners (#1609: Default 69% to 76% kept). Three options, each off unless asked for as the legacy presets have them: Shapes (#1609: 57 to 62% of plain circles, ellipses, rectangles and regular polygons come out as live shapes, rounded rectangles rarely), Auto Grouping (#1618: paths grouped with what lies inside them, the same picture) and Gradients (#1627: linear gradients traced as one gradient-filled path; on gradient inputs 6 Colors' colour error 2.12 to 0.62 with 6.4 to 3.4 paths, none found in flat art). Snap Curves To Lines moves no end of a line by more than 1.6 px, so long lines a degree or two off stay as the image has them (#1647: Technical Drawing's largest distance 4.21 px to 1.46). Flat Logo takes the tones a scan's uneven paper makes of one colour for one colour (#1657: on scans 470 paths and 21 px off to 8.5 paths and 0.09 px). Shapes finds rounded rectangles and shapes in aliased, blurred and scanned art (#1845: 57 to 62% of the plain shapes up to 98 to 100%, no false shape but one line 2 px wide). Stroked lines get square caps where their ink is cut square, and a wide end that turned towards a corner goes back on its line (#1846: Outline's largest distance 2.94 px to 0.88, 14 anchors to 10). Each of the 14 documented presets has an enhanced version with Auto Grouping and, in all but High Fidelity Photo, Shapes (#1847), measured beside its preset: equal or better within 0.005 px and 1% of edge ΔE on every preset's own inputs (Default 0.091 to 0.083 px); Auto Grouping keeps traced order in its groups, which removed a light seam along the counters of letters. Gradients grows a gradient over the pixels noise and soft rims took off it (#1848: blurred and noisy linear gradients 3 to 11 paths beside the gradient down to 0.5 with 6 Colors, 24 to 56 down to 0.5 to 1.5 with High Fidelity Photo). Silhouettes is 0.52 px off because its threshold is 200 (0.11 px at 128). Still weak, by the same numbers: rounded rectangles and other line-and-arc outlines take 12 to 16 anchors (the fitter does not split lines from arcs), blurred and scanned polygons lose corners, hairlines under half a pixel are lost to the threshold, aliased art is about 0.25 px off, a scan's uneven paper splits into tones when more colours are asked for than the art has, stroke junctions stay at their skeleton pixels, a three-stop gradient in a small or scanned disc is not found, radial gradients stay bands (a draft, #1849, traces them; the documented option is for linear ones, so it waits for a decision), near-regular polygons a few dozen pixels across are made regular with Shapes (up to 0.5 px off), and aliased stroked lines are 0.8 px off at worst. - **Gradient mesh from an image:** Object › Create Gradient Mesh (`object.mesh.create`) on an embedded image makes a mesh of 1 to 50 rows and columns over the picture's rectangle, placed with the image's transform; each point takes the alpha-weighted average colour and the opacity of the area around it, and Appearance and Highlight apply. A linked image is refused with a message to embed it (#1676). Scores and hours unchanged. - **Gradient mesh keeps the object's outline (#2752):** Create Gradient Mesh, a Mesh tool click and Expand of a gradient to a mesh lay the mesh's border on the path's outline: each border edge is the piece of the outline between its two points, and where the outline bends through an anchor (a star's points, an L-shape's inner corner, a rounded rectangle's arcs) no single curve follows, the mesh takes a line through that anchor, up to 256 each way. Holes and other subpaths of a compound path are still left out. Public reference: [About mesh objects and Create mesh objects, CS3 user guide, pages 184 to 185](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) (mesh lines carry anchor points as well as mesh points). Tests: `a_mesh_keeps_the_outline_of_every_shape` and `a_mesh_takes_lines_only_where_the_outline_needs_them` in `crates/doc/src/live.rs`, `a_mesh_tool_click_keeps_a_stars_points` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. +- **A point on a mesh's outline is on the mesh:** a point exactly on the outline of a gradient mesh (within a millionth of a point) locates on the edge it lies on, on all four sides alike and with no tolerance, as it already did on the top and left edges, so `object.mesh.addLine` and Create Gradient Mesh `at` a point on the bottom or right edge add their lines there instead of reporting the point outside, and the Eyedropper samples the mesh's color there; a point just outside still needs `tolerance`. Tests: `mesh_locate_takes_a_point_on_any_side_of_the_outline` in `crates/doc/src/live.rs`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Several mesh points at once (#4207, #4208, #4170):** the Mesh tool and Direct Selection pick several points of a gradient mesh or mesh envelope: Shift-click adds a point or takes a picked one away, Direct Selection's marquee picks the points inside it (Shift toggles them) and selects their meshes, and its click on a mesh line picks the line's two ends and one inside a patch the four points around it. The picked points show filled; dragging one moves them all as one undo step and the arrow keys nudge them (`object.mesh.movePoints {id, points, dx, dy}` or `{items, dx, dy}`), and a click on one of several picked points picks it alone. A solid fill colour (`paint.setFill`: Color panel, Swatches, Eyedropper) recolours every picked point, and the Transparency panel's Opacity fades them instead of the object, the panel showing their opacity (blank when it differs); `object.mesh.setPointColor` takes `points` or `items`. Public reference: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (Shift selects multiple mesh points; a fill colour colours the selected point), [Macworld, gradient mesh](https://www.macworld.com/article/202693/gmesh2.html) (Direct Selection: a mesh line selects the points at both ends, a patch the points around it, Shift-click adds or removes points), [Peachpit](https://www.peachpit.com/articles/article.aspx?p=1638270) (each mesh point can have its own colour or transparency). Tests: `shift_clicks_pick_mesh_points_that_drag_and_nudge_together` and `direct_selection_picks_mesh_points_by_marquee_line_and_patch` in `crates/tools/src/meshedit.rs`, `picked_mesh_points_take_the_fill_opacity_and_drag_together` in `crates/engine/src/tests/editcolors.rs`, `mesh_points_move_and_colour_together` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original. - **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. @@ -1424,6 +1430,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Add New Effect popup (Appearance panel, Properties), the Appearance panel's swatch picker, the Gradient panel's gradient swatches menu and the Image Trace button's list of presets stop at the bottom of a short window, and the mouse wheel or the scroll bar reaches their last rows. A list that fits does not scroll (`a_long_swatch_picker_scrolls_inside_a_short_window`). An image's own fills and strokes draw the shape that a Convert to Shape or Outline Object effect on them gives them (the image's box or its frame, reshaped by the effects after it), under or over the image as its Contents row says, on the canvas, in exports and through Expand Appearance; new fills and strokes on an image go under it. Without one of those effects they draw nothing, and Use Preview Bounds measures an image by its frame. A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. + A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page describes effects on one fill or stroke, and the help page describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. The Appearance panel's inline effect editor labels each parameter as the effect dialogs' generic fields do, without the colon ("Max. Radius", "Channel 1", "Create New Fields by"). Roughen's and Zig Zag's Points, Offset Path's Joins, Inner Glow's Source and the menus of Radial Blur, Smart Blur, Sprayed Strokes, Glass, Mezzotint, Halftone Pattern, Grain, Texturizer and De-Interlace are dropdowns with the dialog's labels that send the dialog's values, and a plug-in's choice is a dropdown of the plug-in's values. Revolve's edge, Extrude & Bevel's bevel, every Warp style's orientation, Rasterize's Color Model, Background and Anti-aliasing and the channel of Levels and Curves are dropdowns too, with the labels their own dialogs show. `effect.apply` and `effect.setParams` refuse a Levels or Curves `channel` other than `rgb`, `red`, `green` or `blue` (or `r`, `g` and `b`, in any letter case). Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents. @@ -1698,6 +1705,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Tests and robustness:** ~2,840 automated tests: model-based property tests, a junk-parameter sweep over every command, import fuzzing (SVG, PDF, libraries), golden renders, and MCP end-to-end tests over stdio. Shipped code never panics (workspace lints and a rollback safety net; see `docs/development.md`). Scatter graph data near the largest number is refused with a message instead of hanging the app (#1780). One very long Liquify stroke segment can no longer create an unbounded number of dabs (#1779). A drag whose last preview failed is no longer recorded as a committed command in the journal that actions and scripts read (#1775). Tests: text import fuzzing no longer searches installed fonts (#1785). Tests: render tests that add fonts no longer race the frame cache tests (#1795). - **Raster-effect resolution in PDF:** when the 64 million pixel cap on an effect image renders an object's raster effects below the document's raster effects resolution, PDF export warns once per object with the requested and the lowest achieved ppi (`crates/engine/src/tests/pdfraster.rs`). - **Rasterize effect:** Effect › Rasterize… (`rasterize`) draws an object as an image of square pixels at its own resolution or the document's raster effects resolution, with Object › Rasterize's color model, background, anti-aliasing, clipping mask and room around the object, while its paths stay editable. Expand Appearance and PDF and SVG export of an object whose only raster effect is Rasterize give the image Object › Rasterize gives (`crates/engine/src/tests/rastersettings.rs`, `crates/render/src/tests/rasterize.rs`). Behavior reference: [How to save artwork in Illustrator](https://helpx.adobe.com/illustrator/using/saving-artwork.html), [Work with effects](https://helpx.adobe.com/illustrator/using/effects.html). +- **Rasterize colour models:** Object › Rasterize with the Grayscale colour model makes a grayscale image (a gray PNG, with alpha over a transparent background), and with Bitmap a 1-bit image (a TIFF), or a black-and-white gray PNG with alpha over a transparent background; `image.info` and the Control bar say Grayscale, and a fill color colorizes the image, in RGB and CMYK documents (#6969). Expand Appearance and PDF export of a Rasterize effect make the same images. Regression coverage: `rasterize_to_grayscale_or_bitmap_makes_a_grayscale_image` (`crates/engine/src/tests/rastersettings.rs`) and `gray_and_bilevel_images_store_gray` (`crates/render/src/encode/tests.rs`). Scores and estimates unchanged. - **SVG filters:** Effect › SVG Filters lists the document's own SVG filters below Apply SVG Filter… and Import SVG Filter…, and choosing one applies it to the selection as a live effect in one undo step (`svgFilter.apply`). Apply SVG Filter applies the selected filter, New and Edit open its code, and Delete and Import… remove filters or add those of an SVG file (`svgFilter.define`, `svgFilter.delete`, `svgFilter.import`). VectorCraft ships no default filters. The canvas, raster export and PDF draw the filter at the Document Raster Effects resolution; SVG export writes it as a `` element when it is the object's last effect and otherwise draws the object as an image; SVG import keeps filters the other live effects can't express as this effect instead of leaving them out; the native format keeps the filters (`crates/engine/src/tests/svgfilter.rs`, `crates/effects/src/svg_filter/tests.rs`). Behavior reference: [Apply SVG filter effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-svg-filter-effects.html), [CS5 help, Apply SVG effects](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=402), [SVG 1.1 Filter Effects](https://www.w3.org/TR/SVG11/filters.html). - **Pattern tiles:** the renderer keeps a tile of each pattern for each scale it rasterizes the pattern at, until the tiles fill the tile cache's budget, and then drops the least recently used tiles first. Objects that show one pattern at different scales, such as a pattern scaled to 25% with Transform Pattern Tiles next to the same pattern at 100%, draw from tiles kept between frames. @@ -2067,6 +2075,10 @@ A VectorCraft addition (it replaces a script some users ran), so no area score m A VectorCraft addition, so no area score moves. Object › Plug-ins › Image Tools › Remove Background… (`addon.image.removeBackground`) makes the background of the selected images transparent in their own pixels, in the app with no service or model. The background is the most common edge color (nothing is cleared when the edges hold at least as many clear pixels as pixels of that color), the average of the corners that are not clear, or picked colors. Contiguous (on by default) clears it only where it reaches in from an edge; off, it is cleared everywhere. Tolerance and Softness (0 to 100, 10 by default, VectorCraft's own values) set how near a color is cleared and the band over which pixels fade out, measured as RGB distance or, with Match set to Each Channel, as the largest difference on one channel. The run is one undo step, and none is recorded when no pixel changes. The image stays an image: a PNG with alpha at its own bit depth, gray or color as it was, with its color profile and resolution, and a linked image is embedded. CMYK images, linked images that show their preview, images that would need more than the decode allowance, results with no pixel left and grayscale images colorized with a process color are refused (the result has an alpha channel, and a process color can't colorize a grayscale image with one: [Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"). The dialog's Preview works as Release Type on a Path's does; its preview steps decode an image once, and the decoded pixels are released when the dialog closes. Tests: `cmd::addons::image::tests` in `vectorcraft-engine` (edge, corner and picked colors, contiguous on and off, a second run, tolerance and softness by distance and by channel, 16-bit and gray images, the color profile and resolution kept, an image read at another size, linked images, refusals and bad params, and decoded pixels reused across preview steps and released at OK and Cancel), `addons::image::tests::remove_background_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Image Tools add-on. Since 2026-11-12 a selected image also offers Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar, where the reference app offers it (); a click runs it at once with the defaults, as one undo step (tests `canvas::tests::the_task_bar_removes_a_selected_images_background` and `addons::image::tests::properties_and_the_control_bar_remove_the_background_at_once`). +## Image Tools add-on: Color Mask (2026-11-12) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Image Tools › Color Mask… (`addon.image.colorMask`) hides colors of the selected images while their pixels stay as they are. It matches colors as Remove Background does (edge, corner or picked colors, Contiguous, Match, Tolerance and Softness, VectorCraft's own values). The mask's settings and the masked pixels are kept with the image object and saved with the document. The canvas (clip groups and white-shape opacity masks included), printing and separations, PDF (PDF/X-1a and PDF/X-3 flatten the hidden pixels), SVG, EPS, PNG, DXF, EMF, WMF, the legacy .ai, the .ai editing data, copy and paste, and placing a document show the masked pixels. A linked image stays linked, and outputs that would refer to its file write the masked pixels instead. A masked grayscale image whose mask hides pixels takes only a spot, black or white colorize color; one whose mask hides no pixels takes a process color too. The dialog opens on the image's mask settings. Remove Color Mask takes the mask off, and Apply Color Mask makes it part of the image's pixels. Each is one undo step, and none is recorded when nothing changes. When the image's own pixels are replaced (a link updated or read again on open, the image cropped or recolored), the mask is made again for the new pixels. A click anywhere in the image's frame selects it. Tests: `cmd::addons::image::mask::tests` in `vectorcraft-engine` (hidden colors drawn, pixels kept, edit, report, remove and apply, the outputs listed, save and open, copy and paste, placing a document, a linked image, cropped and replaced pixels, colorize colors, refusals), `color_mask::tests` and `placed_document::tests` in `vectorcraft-doc`, the separations and CMYK soft-mask tests in `vectorcraft-pdf`, and `addons::image::tests::color_mask_previews_keeps_its_settings_and_comes_off` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Image Tools add-on › Color Mask. + ## Color Effects add-on: Find Nearest Swatch (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Color Effects › Find Nearest Swatch… lists each colour of the selection (fills and strokes, as ticked; solid colours and gradient stops, inside groups and type) with the three swatches of the chosen library closest to it by CIEDE2000 difference, with that difference (`addon.color.nearestSwatch`, #4923). The library is the document's swatches, a built-in library, or a library or colour book the user saved or loaded (no colour book data ships with VectorCraft). Apply gives each colour its nearest swatch as one undo step (`addon.color.applyNearestSwatch`): global and spot swatches link, and a library's swatches the colours take are added to the document first, so a spot colour stays spot. Remaining: typing a colour to look up in the dialog (the command takes `color`), and applying a match other than the nearest. Tests: `cmd::addons::color::nearest::tests` (engine), `addons::color::nearest::tests::find_nearest_swatch_lists_the_matches_and_applies_the_nearest` (ui-egui). @@ -2135,6 +2147,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-12 | minor | Object › Rasterize with the Grayscale colour model makes a grayscale image (one gray channel, with alpha over a transparent background), so the Properties panel says Grayscale and a fill color colorizes it; Bitmap makes a 1-bit image (a TIFF), or a black-and-white gray image with alpha over a transparent background, since 1-bit gray with alpha is no format readers take. Both were RGB images of gray pixels (#6969). Scores and estimates unchanged. | | 2026-11-12 | minor | `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints (its strokes' miter tips, and strokes a Transform effect moves, included), after its glyphs grown by half its strokes' weight; `.ai` import evidence updated (#6824); scores and estimates unchanged. | | 2026-11-12 | minor | Explicit editing-data import keeps a single artboard beyond a capped 14,400 pt PDF page (#6865), with a warning; automatic mode stays unchanged. Scores and estimates unchanged. | | 2026-11-12 | minor | Glyphs review (#6084): Entire Font uses the selection's version and variable axes for previews and alternate applicability. The default cell can reset an unlisted glyph choice when GSUB lists no alternates. Encoded Latin and other ordinary characters insert unchanged even if their glyph also has Arabic positional provenance; Arabic presentation forms retain base-letter insertion. Remove a redundant charmap scan from unlisted-glyph checks. Scores and estimates unchanged. | diff --git a/docs/three-d.md b/docs/three-d.md index 2eb3e6c7fe..e4cd4fa76f 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -177,9 +177,13 @@ solids are ([Groups](#groups)), turned about one shared axis. - The objects stay live: editing the clipping path, the blend's keys or the symbol reshapes the solid. - An image is refused, alone or in a group: trace it first with Object › Image Trace › Make. The help page routes images to 3D through Image Trace ([Create 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-vector-artwork.html)). - A hidden image in a group is left out like any hidden member, and so is an image in a clipping group whose bounds - lie wholly outside the clipping path's bounds, when the image has no visible fills or strokes of its own and - neither the image nor a group holding it inside the clipping group has effects. + A hidden image in a group is left out like any hidden member. An image in a clipping group is left out when its + frame, as its transform places it, lies wholly outside the area that every clipping path around it fills together + (holes of an even-odd or compound clipping path included), when the image has no visible fills or strokes of its + own and neither the image nor a group holding it inside the clipping group has effects. A clipping path hides + everything outside its shape ([the help page](https://helpx.adobe.com/illustrator/using/clipping-masks.html)). An + image that the clips show any part of is refused. Resolving one effect's art cuts image frames to clipping paths at + most 1,024 times (VectorCraft's own limit); past that, the art is refused. ## Rotate diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3c35d60339..5f10ea4841 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -51,6 +51,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | Swatches: in a panel made taller the swatch list fills the space above the footer instead of scrolling inside 150 or 200 pt (#1638). Scores unchanged. | | 2026-11-08 | minor | Style panels: a double-click on a user character style's row opens its Character Style Options (`ui.charStyleOptions`), and on a paragraph style's row its Paragraph Style Options (rename); the Character Style Options dialog keeps a fixed width and scrolls its sections in a shorter window, so OK and Cancel stay on screen. Tests `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options` and `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`. Scores and estimates unchanged. | | 2026-11-08 | minor | #3380, deletion only: preserve gradient placement and exact surviving geometry; consume owned subpaths with a shared original-node snapshot; consolidate status/evidence and document command/helper contracts. Compound behavior and the existing M2 status entry are retained. Endpoint highlighting remains open; scores and estimates unchanged. | | 2026-11-07 | minor | #3380 (deletion only): independent surviving path objects; transformed appearance, stacking, selection, cubic handles and Undo/Redo covered by `delete_path_pieces`; compound semantics retained. Endpoint highlighting remains open; scores and estimates unchanged. | @@ -165,6 +166,7 @@ tools, never checked side by side) isn't captured row by row. | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | | Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | | Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | +| Swatches list fills a taller panel (#1638) | done | Docked, floating or in a resized flyout, the swatch list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 150 pt (200 pt for large thumbnails); `the_list_fills_a_tall_panel_above_its_footer` in `panels/swatches/tests.rs` | | Layers panel lists a blend's spine (#4820) | done | an open blend shows a `` row below its key objects, where Release leaves the spine; a click selects the blend (Shift/Cmd toggles it) so Direct Selection edits the spine; a locked blend's row selects nothing; no row while searching or filtering (`a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend`) | | Layers panel: a layer whose Layer Options › Print is off shows its name italic (#5739) | done | the panel row and its drag ghost; a printing layer stays upright, and Print on again restores it; `panels::layers` test `a_layer_that_does_not_print_has_its_name_italic` | | Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | @@ -231,7 +233,7 @@ tools, never checked side by side) isn't captured row by row. | "intersect" label and snapping to path intersections | partial | #1658 (part of #1602): a point drawn with the Pen, the shape tools or the other drawing tools and an anchor dragged with Direct Selection snap to where paths and ruler guides cross; a moved selection's own anchors and the Width tool don't | | Construction guides at preference angles while drawing | done | #506 | | Line extension: the dragged end of a straight segment snaps to the segment's own direction at any angle, past its other end or short of it, with the guide along it | done | #2120; Direct Selection and Curvature, one anchor dragged (with several, the move has no single direction); nearer the horizontal or vertical through the other end, the point lines up with it ("align"), so a nearly level segment can still be straightened | -| Measurement labels while drawing, moving and resizing | partial | sizes and offsets; angle and distance readouts while drawing missing | +| Measurement labels while drawing, moving and resizing | done | sizes and offsets; the segment being drawn is labeled with its distance, angle and offsets by the Line Segment tool, and by the Pen, Curvature and Smart Pen tools with Enable Rubber Band on (#2983) | | Spacing guides (equal distances) | partial | for moves and bounding-box resizes (#394); not while drawing | | Distance Guides: Alt/Option over another object, or an empty part of an artboard, shows the selection's distances to it (Smart Guides › Invoke Distance Guides) | done | Selection tool hover with Smart Guides on: the gap between facing edges, else the offsets of matching edges, to another object; the left, right, top and bottom distances to the artboard; labelled in the General unit. The selection is measured as a whole. Nothing while moving or nudging, which the public pages don't describe. [Use Distance Guides](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html), [Smart Guides options](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html) | | Snapping tolerance preference | done | |