diff --git a/Cargo.lock b/Cargo.lock index b42037f540..0a1689bff7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6476,6 +6476,7 @@ dependencies = [ "vectorcraft-plugins", "vectorcraft-text", "vectorcraft-three-d", + "vectorcraft-trace", ] [[package]] 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/cmyk.rs b/crates/doc/src/cmyk.rs index f94f0ec4a8..ea2c44215e 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -150,7 +150,7 @@ fn planar(d: &mut tiff::decoder::Decoder>) -> bool { /// stores each pixel's samples together or one plane per channel. `None` when they don't decode to /// that many samples, which includes images whose planes together need more than the decoder's /// limit (256 MB of samples). -fn read_samples(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option> { +pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option> { let mut buf = tiff::decoder::DecodingResult::U8(Vec::new()); let layout = d.read_image_to_buffer(&mut buf).ok()?; let data = match buf { 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..15de79660f 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; @@ -61,6 +62,7 @@ pub mod rastersettings; mod reach; pub mod recolor; pub mod selection; +pub mod separated; pub mod setup; pub mod shaper; pub mod slices; 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/ops.rs b/crates/doc/src/node/ops.rs index 415b2946e3..415fc1cad1 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -819,7 +819,8 @@ impl Node { impl Node { /// Whether this object shows any transparency, itself or anything inside it: object, fill or /// stroke opacity below 100%, a blend mode, an opacity mask, effects, transparent gradient - /// stops or a colorized image. Hidden objects show none. + /// stops (characters' fills and strokes included) or a colorized image. Hidden objects show + /// none. pub fn shows_transparency(&self) -> bool { self.shows_transparency_with(&|_| true) } @@ -827,21 +828,31 @@ impl Node { /// [`Self::shows_transparency`], counting a colorized image by itself only when `colorize` /// accepts it, for files that write some colorized images in their colorize paint (EPS). pub fn shows_transparency_with(&self, colorize: &dyn Fn(&Node) -> bool) -> bool { + self.visible && (self.own_transparency(colorize) || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize)))) + } + + /// [`Self::shows_transparency`] of the object alone, what it holds left out. + pub fn shows_own_transparency(&self) -> bool { + self.visible && self.own_transparency(&|_| true) + } + + /// The object's own transparency, as [`Self::shows_transparency_with`] counts it. + fn own_transparency(&self, colorize: &dyn Fn(&Node) -> bool) -> bool { use vectorcraft_color::Paint; let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0)); let effects = |fx: &[crate::Effect]| fx.iter().any(|e| e.visible); - self.visible - && (self.opacity < 1.0 - || self.blend != BlendMode::Normal - || self.extras().mask.as_ref().is_some_and(|m| !m.disabled) - || (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self)) - || effects(&self.appearance.effects) - || self - .appearance - .items - .iter() - .any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects()))) - || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize)))) + self.opacity < 1.0 + || self.blend != BlendMode::Normal + || self.extras().mask.as_ref().is_some_and(|m| !m.disabled) + || (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self)) + || effects(&self.appearance.effects) + || self + .appearance + .items + .iter() + .any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects()))) + // Characters' own fills and strokes, which draw with the object. + || matches!(&self.kind, NodeKind::Text(t) if t.runs.iter().any(|r| see_through(&r.style.fill) || (r.style.stroke_width > 0.0 && see_through(&r.style.stroke)))) } } 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/doc/src/separated.rs b/crates/doc/src/separated.rs new file mode 100644 index 0000000000..8eb7cefe66 --- /dev/null +++ b/crates/doc/src/separated.rs @@ -0,0 +1,533 @@ +//! Separated images: an image whose inks come as one plate each (a DCS file placed linked), kept +//! as a TIFF of several images. The first is the composite, the plates mixed into CMYK +//! ([`Separated::composite`]), which every reader of a CMYK TIFF sees. Each later image is one +//! plate's ink amounts in grayscale (0 is no ink), with its ink's name and CMYK equivalent in its +//! ImageDescription. Print separations take each plate from these ([`Separated::coverage`]). + +use std::io::Cursor; +use std::sync::Arc; + +use vectorcraft_color::cms::PROCESS_PLATES; +use vectorcraft_geom::PathData; + +use crate::ImageBlob; +use crate::cmyk::{Inks, MAX_CMYK_PIXELS}; + +/// Most plates a separated image holds. +pub const MAX_PLATES: usize = 64; +/// Most directories a separated image's TIFF holds: its composite and its plates. +const MAX_DIRECTORIES: usize = MAX_PLATES + 1; +/// Longest ink name kept (bytes). +pub const MAX_NAME: usize = 255; +/// Most ink amounts the plates of one image hold together (512 MB). +pub const MAX_SAMPLES: u64 = 1 << 29; +/// How a plate's ImageDescription starts. +const MARK: &str = "VectorCraft plate "; + +/// How the composite's ImageDescription starts when plates were read from files of their own. +const FILES_MARK: &str = "VectorCraft plate files"; + +/// A plate file of its own that a separated image was read from, as it was then: a change to it +/// changes the image as a change to the DCS file does. +#[derive(Clone, Debug, PartialEq)] +pub struct PlateFile { + /// Its file name, in the DCS file's folder. + pub name: String, + /// Its size (bytes). + pub size: u64, + /// Its modification time (ms since the Unix epoch; 0 when the file system keeps none). + pub modified: u64, +} + +/// `text` in hexadecimal (TIFF text is ASCII). +fn hex(text: &str) -> String { + text.bytes().map(|b| format!("{b:02x}")).collect() +} + +/// The text [`hex`] wrote, of at most `max` bytes. +fn unhex(hex: &str, max: usize) -> Option { + if !hex.len().is_multiple_of(2) || hex.len() > max * 2 { + return None; + } + let bytes: Option> = (0..hex.len()).step_by(2).map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok()).collect(); + String::from_utf8(bytes?).ok() +} + +/// One ink's plate: its ink amounts, one byte a pixel (0 is none, 255 is solid), row by row from +/// the top. +#[derive(Clone, Debug, PartialEq)] +pub struct InkPlate { + /// "Cyan", "Magenta", "Yellow", "Black", or a spot ink's name. + pub name: String, + /// The process inks the ink stands for (C, M, Y, K, 0..1): one process ink at 100% for a + /// process plate. + pub cmyk: [f32; 4], + pub data: Vec, +} + +impl InkPlate { + /// Is it a spot ink's plate (not one of the four process inks)? + pub fn spot(&self) -> bool { + !PROCESS_PLATES.contains(&self.name.as_str()) + } +} + +/// The plates of a separated image, all of one size. +#[derive(Clone, Debug, PartialEq)] +pub struct Separated { + pub width: u32, + pub height: u32, + pub plates: Vec, +} + +impl Separated { + /// `plates` as a `width` × `height` image; `None` when there are none or more than + /// [`MAX_PLATES`], two have the same name, a name is empty or longer than [`MAX_NAME`], a plate + /// doesn't hold that many pixels, an equivalent isn't within 0..1, or the image is empty, has + /// more than [`MAX_CMYK_PIXELS`], or its plates together hold more than [`MAX_SAMPLES`] + /// ([`Self::fits`]). A process plate's equivalent is its own ink. + pub fn new(width: u32, height: u32, mut plates: Vec) -> Option { + let n = u64::from(width) * u64::from(height); + if !Self::fits(width, height, plates.len()) { + return None; + } + for p in plates.iter_mut() { + if p.name.is_empty() || p.name.len() > MAX_NAME || p.data.len() as u64 != n { + return None; + } + if let Some(j) = PROCESS_PLATES.iter().position(|q| *q == p.name) { + p.cmyk = [0.0; 4]; + p.cmyk[j] = 1.0; + } + if !p.cmyk.iter().all(|v| (0.0..=1.0).contains(v)) { + return None; + } + } + let mut names = std::collections::HashSet::new(); + if !plates.iter().all(|p| names.insert(p.name.as_str())) { + return None; + } + Some(Self { width, height, plates }) + } + + /// May an image of `width` × `height` pixels hold `plates` plates? Not when it is empty, has + /// more than [`MAX_CMYK_PIXELS`], has no plate or more than [`MAX_PLATES`], or the plates + /// together would hold more than [`MAX_SAMPLES`]. + pub fn fits(width: u32, height: u32, plates: usize) -> bool { + let n = u64::from(width) * u64::from(height); + n > 0 && n <= MAX_CMYK_PIXELS && (1..=MAX_PLATES).contains(&plates) && n * plates as u64 <= MAX_SAMPLES + } + + /// The plates of spot inks. + pub fn spots(&self) -> impl Iterator { + self.plates.iter().filter(|p| p.spot()) + } + + /// The plates mixed into process inks: each plate's ink amount times its equivalent, the + /// plates over one another as inks print (`1 − (1 − a)(1 − b)` for each process ink). + pub fn composite(&self) -> Inks { + let n = self.data_len(); + let mut data = vec![0u8; n * 4]; + for (i, px) in data.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let mut clear = [1.0f32; 4]; + for p in &self.plates { + let t = f32::from(p.data[i]) / 255.0; + for (c, e) in clear.iter_mut().zip(p.cmyk) { + *c *= 1.0 - t * e; + } + } + for (o, c) in px.iter_mut().zip(clear) { + *o = ((1.0 - c) * 255.0).round() as u8; + } + } + Inks { width: self.width, height: self.height, data } + } + + /// The ink amounts that print on plate `plate` (a process ink's name or a spot ink's), one byte + /// a pixel. A spot plate for which `own` is true prints on its own plate only; every other spot + /// plate (the job prints no plate of that name) prints as its process equivalent, mixed as + /// [`Self::composite`] mixes it. A plate name the image has no plate for, and a spot plate that + /// prints as process, print nothing. + pub fn coverage(&self, plate: &str, own: &dyn Fn(&str) -> bool) -> Vec { + self.coverage_as(plate, own, &|p| p.cmyk) + } + + /// [`Self::coverage`], a spot plate that prints as process printing as the process inks + /// `equivalent` gives it (the document's swatch of its ink, when there is one). + pub fn coverage_as(&self, plate: &str, own: &dyn Fn(&str) -> bool, equivalent: &dyn Fn(&InkPlate) -> [f32; 4]) -> Vec { + let n = self.data_len(); + if let Some(j) = PROCESS_PLATES.iter().position(|q| *q == plate) { + let mixed: Vec<(&InkPlate, f32)> = self + .plates + .iter() + .filter(|p| !p.spot() || !own(&p.name)) + .map(|p| (p, if p.spot() { equivalent(p)[j].clamp(0.0, 1.0) } else { p.cmyk[j] })) + .filter(|(_, e)| *e > 0.0) + .collect(); + return (0..n) + .map(|i| { + let clear = mixed.iter().fold(1.0f32, |c, (p, e)| c * (1.0 - f32::from(p.data[i]) / 255.0 * e)); + ((1.0 - clear) * 255.0).round() as u8 + }) + .collect(); + } + match self.plates.iter().find(|p| p.name == plate && p.spot() && own(&p.name)) { + Some(p) => p.data.clone(), + None => vec![0; n], + } + } + + /// [`Self::coverage_as`] as a grayscale PNG, black for solid ink and white for none, as a plate + /// prints; `None` when it can't be written. + pub fn plate_png(&self, plate: &str, own: &dyn Fn(&str) -> bool, equivalent: &dyn Fn(&InkPlate) -> [f32; 4]) -> Option { + let gray: Vec = self.coverage_as(plate, own, equivalent).into_iter().map(|v| 255 - v).collect(); + let img = image::GrayImage::from_raw(self.width, self.height, gray)?; + let mut png = Vec::new(); + img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + Some(ImageBlob::png(png)) + } + + fn data_len(&self) -> usize { + self.width as usize * self.height as usize + } +} + +/// A plate's ImageDescription: the mark, its equivalent and its name in hexadecimal (TIFF text is +/// ASCII). +fn description(p: &InkPlate) -> String { + let [c, m, y, k] = p.cmyk; + format!("{MARK}{c} {m} {y} {k} {}", hex(&p.name)) +} + +/// A plate's name and equivalent from its ImageDescription; `None` when it isn't one. +fn parse_description(s: &str) -> Option<(String, [f32; 4])> { + let rest = s.strip_prefix(MARK)?; + let mut words = rest.split(' '); + let mut cmyk = [0.0f32; 4]; + for v in &mut cmyk { + *v = words.next()?.parse().ok().filter(|v: &f32| v.is_finite())?; + } + let name = unhex(words.next()?, MAX_NAME)?; + words.next().is_none().then_some((name, cmyk)) +} + +/// Longest plate file name kept (bytes). +const MAX_FILE_NAME: usize = 4096; + +/// The composite's ImageDescription line for `files`: the mark, then each file's name in +/// hexadecimal, its size and its modification time. +fn files_description(files: &[PlateFile]) -> String { + let mut out = String::from(FILES_MARK); + for f in files.iter().take(MAX_PLATES) { + out.push_str(&format!(" {} {} {}", hex(&f.name), f.size, f.modified)); + } + out +} + +/// How the composite's ImageDescription line holding the clipping path starts. +const CLIP_MARK: &str = "VectorCraft clip "; + +/// Longest clipping path kept (bytes of its JSON). +const MAX_CLIP: usize = 16 << 20; + +/// The composite's ImageDescription line for clipping path `clip`: the mark, then the path's JSON +/// in hexadecimal; `None` when it is longer than [`MAX_CLIP`]. +fn clip_description(clip: &PathData) -> Option { + let json = serde_json::to_string(clip).ok().filter(|j| j.len() <= MAX_CLIP)?; + Some(format!("{CLIP_MARK}{}", hex(&json))) +} + +/// The plate files of a composite's ImageDescription; none when it isn't one. +fn parse_files(s: &str) -> Vec { + let Some(rest) = s.lines().find_map(|l| l.strip_prefix(FILES_MARK)) else { return vec![] }; + let words: Vec<&str> = rest.split(' ').filter(|w| !w.is_empty()).collect(); + let file = + |w: &[&str]| Some(PlateFile { name: unhex(w.first()?, MAX_FILE_NAME)?, size: w.get(1)?.parse().ok()?, modified: w.get(2)?.parse().ok()? }); + words.chunks(3).take(MAX_PLATES).filter_map(file).collect() +} + +impl ImageBlob { + /// A TIFF of separated image `s`: its composite in CMYK, then its plates (Deflate-compressed), + /// declaring the resolution `ppi` when it is given and both are finite and above 0, and noting + /// `files`, the plate files of their own the plates were read from ([`Self::plate_files`]); + /// `None` when it can't be written. + pub fn separated_tiff(s: &Separated, ppi: Option<(f64, f64)>, files: &[PlateFile]) -> Option { + Self::separated_tiff_clipped(s, ppi, files, None) + } + + /// [`Self::separated_tiff`], noting `clip` too, the clipping path its file draws it through, in + /// its pixel space ([`Self::separated_clip`]). + pub fn separated_tiff_clipped(s: &Separated, ppi: Option<(f64, f64)>, files: &[PlateFile], clip: Option<&PathData>) -> Option { + use tiff::encoder::{Compression, Rational, TiffEncoder, colortype, compression::DeflateLevel}; + use tiff::tags::{ResolutionUnit, Tag}; + let ppi = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)); + // Ten-thousandths of a pixel per inch. + let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 }; + let mut out = Cursor::new(Vec::new()); + let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced)); + let mut img = enc.new_image::(s.width, s.height).ok()?; + if let Some((x, y)) = ppi { + img.encoder().write_tag(Tag::XResolution, r(x)).ok()?; + img.encoder().write_tag(Tag::YResolution, r(y)).ok()?; + img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?; + } + // One line for the plate files, one for the clipping path. + let lines: Vec = + [(!files.is_empty()).then(|| files_description(files)), clip.and_then(clip_description)].into_iter().flatten().collect(); + if !lines.is_empty() { + img.encoder().write_tag(Tag::ImageDescription, lines.join("\n").as_str()).ok()?; + } + img.write_data(&s.composite().data).ok()?; + for p in &s.plates { + // White is no ink, so a viewer that shows a plate shows it as it prints. + let mut img = enc.new_image::(s.width, s.height).ok()?; + img.encoder().write_tag(Tag::ImageDescription, description(p).as_str()).ok()?; + let inverted: Vec = p.data.iter().map(|v| 255 - v).collect(); + img.write_data(&inverted).ok()?; + } + Some(Self::new("image/tiff", out.into_inner())) + } + + /// Does the image hold plates ([`ImageBlob::separated_tiff`]), at most [`MAX_PLATES`] of them? + /// One with more, or with more directories than its composite and [`MAX_PLATES`] plates, is the + /// CMYK image of its composite only, as [`Self::separated`] refuses it. Reads only the TIFF's + /// directories, at most [`MAX_DIRECTORIES`]. + pub fn is_separated(&self) -> bool { + let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return false }; + let (mut plates, mut directories) = (0usize, 1usize); + while d.more_images() { + directories += 1; + if directories > MAX_DIRECTORIES || d.next_image().is_err() { + return false; + } + if d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().is_some_and(|s| s.starts_with(MARK)) { + plates += 1; + if plates > MAX_PLATES { + return false; + } + } + } + plates > 0 + } + + /// The plate files of their own a separated image was read from, as they were then; none for + /// other images. Reads only the TIFF's first directory. + pub fn plate_files(&self) -> Vec { + let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return vec![] }; + d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().map(parse_files).unwrap_or_default() + } + + /// The clipping path a separated image's file draws it through, in its pixel space, as + /// [`Self::separated_tiff_clipped`] noted it; `None` for other images. Reads only the TIFF's + /// first directory. + pub fn separated_clip(&self) -> Option { + let (_, mut d) = crate::cmyk::tiff(&self.bytes)?; + let text = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok()?; + let json = unhex(text.lines().find_map(|l| l.strip_prefix(CLIP_MARK))?, MAX_CLIP)?; + serde_json::from_str(&json).ok() + } + + /// The spot inks a separated image has plates for, each with its CMYK equivalent; none for + /// other images. Reads only the TIFF's directories. + pub fn spot_plates(&self) -> Vec<(String, [f32; 4])> { + if !self.is_separated() { + return vec![]; + } + let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return vec![] }; + let mut inks = vec![]; + while d.more_images() && inks.len() < MAX_PLATES { + if d.next_image().is_err() { + break; + } + let plate = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().and_then(parse_description); + inks.extend(plate.filter(|(name, _)| !PROCESS_PLATES.contains(&name.as_str()))); + } + inks + } + + /// The plates of a separated image; `None` for other images, and ones whose plates can't be + /// read. The plates of the last image read are kept for the next call (print separates one + /// image plate after plate). + pub fn separated(&self) -> Option> { + thread_local! { + static LAST: std::cell::RefCell)>> = const { std::cell::RefCell::new(None) }; + } + if !self.is_separated() { + return None; + } + let key = self.content_key(); + LAST.with_borrow_mut(|last| match last { + Some((k, s)) if *k == key => Some(s.clone()), + _ => { + let s = Arc::new(read_plates(&self.bytes)?); + *last = Some((key, s.clone())); + Some(s) + } + }) + } +} + +/// The plates of TIFF `bytes`, each the size of its first image. +fn read_plates(bytes: &[u8]) -> Option { + let (_, mut d) = crate::cmyk::tiff(bytes)?; + let (w, h) = d.dimensions().ok()?; + let n = usize::try_from(u64::from(w) * u64::from(h)).ok()?; + let mut plates = vec![]; + // Every plate is read: a file with more than [`MAX_PLATES`] is refused ([`Separated::fits`]), + // not cut short, and so is one with more than [`MAX_DIRECTORIES`] directories. + let mut directories = 1usize; + while d.more_images() { + directories += 1; + if directories > MAX_DIRECTORIES { + return None; + } + d.next_image().ok()?; + let Some((name, cmyk)) = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().and_then(parse_description) else { + continue; + }; + // Checked before the plate is decoded. + if d.dimensions().ok()? != (w, h) || !matches!(d.colortype().ok()?, tiff::ColorType::Gray(8)) || !Separated::fits(w, h, plates.len() + 1) { + return None; + } + let data = crate::cmyk::read_samples(&mut d, n, 1)?.into_iter().map(|v| 255 - v).collect(); + plates.push(InkPlate { name, cmyk, data }); + } + Separated::new(w, h, plates) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn plate(name: &str, cmyk: [f32; 4], data: &[u8]) -> InkPlate { + InkPlate { name: name.into(), cmyk, data: data.to_vec() } + } + + /// Two pixels: cyan 100% and a spot ink at 50% on the first, nothing on the second. + fn two() -> Separated { + let plates = vec![plate("Cyan", [0.0; 4], &[255, 0]), plate("Spot Orange", [0.0, 0.6, 1.0, 0.0], &[128, 0])]; + Separated::new(2, 1, plates).unwrap() + } + + #[test] + fn plates_mix_into_the_composite_as_inks_print() { + let s = two(); + assert_eq!(s.plates[0].cmyk, [1.0, 0.0, 0.0, 0.0], "a process plate stands for its own ink"); + let c = s.composite(); + // Magenta: 0.6 × 128/255; yellow: 128/255. + assert_eq!(&c.data[..4], &[255, 77, 128, 0]); + assert_eq!(&c.data[4..], &[0, 0, 0, 0]); + } + + #[test] + fn a_spot_plate_prints_on_its_own_plate_or_as_process() { + let s = two(); + let own = |_: &str| true; + assert_eq!(s.coverage("Spot Orange", &own), [128, 0]); + assert_eq!(s.coverage("Magenta", &own), [0, 0], "nothing of the spot on a process plate"); + assert_eq!(s.coverage("Cyan", &own), [255, 0]); + assert_eq!(s.coverage("Black", &own), [0, 0]); + let process = |_: &str| false; + assert_eq!(s.coverage("Spot Orange", &process), [0, 0]); + assert_eq!(s.coverage("Magenta", &process), [77, 0]); + assert_eq!(s.coverage("Yellow", &process), [128, 0]); + assert_eq!(s.coverage("Other", &own), [0, 0]); + } + + #[test] + fn the_tiff_keeps_every_plate_and_shows_the_composite() { + let s = two(); + let files = + [PlateFile { name: "pic (1).C".into(), size: 1234, modified: 1_700_000_000_000 }, PlateFile { name: "ü.K".into(), size: 0, modified: 0 }]; + let b = ImageBlob::separated_tiff(&s, Some((300.0, 300.0)), &files).unwrap(); + assert_eq!(b.plate_files(), files); + assert!(ImageBlob::separated_tiff(&s, None, &[]).unwrap().plate_files().is_empty()); + assert!(b.is_separated()); + assert!(b.is_cmyk(), "readers of a CMYK TIFF see the composite"); + assert_eq!(b.cmyk(), Some(s.composite())); + assert_eq!(*b.separated().unwrap(), s); + assert_eq!(b.spot_plates(), [("Spot Orange".to_string(), [0.0, 0.6, 1.0, 0.0])]); + assert!(ImageBlob::cmyk_tiff(&s.composite()).unwrap().spot_plates().is_empty()); + assert!(!ImageBlob::cmyk_tiff(&s.composite()).unwrap().is_separated()); + } + + #[test] + fn the_tiff_keeps_the_clipping_path_beside_the_plate_files() { + let s = two(); + let clip = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 1.5, 1.0)); + let files = [PlateFile { name: "a.C".into(), size: 1, modified: 2 }]; + let b = ImageBlob::separated_tiff_clipped(&s, None, &files, Some(&clip)).unwrap(); + assert_eq!(b.separated_clip(), Some(clip.clone())); + assert_eq!(b.plate_files(), files); + let alone = ImageBlob::separated_tiff_clipped(&s, None, &[], Some(&clip)).unwrap(); + assert_eq!(alone.separated_clip(), Some(clip)); + assert!(alone.plate_files().is_empty()); + assert_eq!(ImageBlob::separated_tiff(&s, None, &files).unwrap().separated_clip(), None); + } + + #[test] + fn a_tiff_with_more_plates_than_are_read_is_refused() { + use tiff::encoder::{TiffEncoder, colortype}; + let tiff = |plates: usize| { + let mut out = Cursor::new(Vec::new()); + let mut enc = TiffEncoder::new(&mut out).unwrap(); + enc.write_image::(1, 1, &[0, 0, 0, 0]).unwrap(); + for i in 0..plates { + let mut img = enc.new_image::(1, 1).unwrap(); + img.encoder().write_tag(tiff::tags::Tag::ImageDescription, description(&plate(&format!("S{i}"), [0.0; 4], &[0])).as_str()).unwrap(); + img.write_data(&[255]).unwrap(); + } + ImageBlob::new("image/tiff", out.into_inner()) + }; + assert_eq!(tiff(MAX_PLATES).separated().map(|s| s.plates.len()), Some(MAX_PLATES)); + let over = tiff(MAX_PLATES + 1); + assert!(over.separated().is_none(), "not cut short to the first {MAX_PLATES}"); + assert!(!over.is_separated() && over.spot_plates().is_empty(), "the CMYK image of its composite only"); + assert!(tiff(MAX_PLATES).is_separated()); + } + + #[test] + fn a_tiff_with_more_directories_than_a_composite_and_its_plates_is_refused() { + use tiff::encoder::{TiffEncoder, colortype}; + let tiff = |others: usize| { + let mut out = Cursor::new(Vec::new()); + let mut enc = TiffEncoder::new(&mut out).unwrap(); + enc.write_image::(1, 1, &[0, 0, 0, 0]).unwrap(); + let mut img = enc.new_image::(1, 1).unwrap(); + img.encoder().write_tag(tiff::tags::Tag::ImageDescription, description(&plate("S", [0.0; 4], &[0])).as_str()).unwrap(); + img.write_data(&[255]).unwrap(); + // Directories that are not plates. + for _ in 0..others { + enc.write_image::(1, 1, &[255]).unwrap(); + } + ImageBlob::new("image/tiff", out.into_inner()) + }; + let most = tiff(MAX_PLATES - 1); + assert!(most.is_separated() && most.separated().is_some()); + let over = tiff(MAX_PLATES); + assert!(!over.is_separated() && over.separated().is_none() && over.spot_plates().is_empty()); + assert!(read_plates(&over.bytes).is_none(), "read_plates stops at the limit too"); + } + + #[test] + fn names_that_are_not_ascii_are_kept() { + let s = Separated::new(1, 1, vec![plate("Grün 100 % (A)", [0.5, 0.0, 1.0, 0.0], &[9])]).unwrap(); + let b = ImageBlob::separated_tiff(&s, None, &[]).unwrap(); + assert_eq!(b.separated().unwrap().plates[0].name, "Grün 100 % (A)"); + } + + #[test] + fn bad_plates_are_refused() { + assert!(Separated::new(2, 1, vec![]).is_none(), "no plates"); + assert!(Separated::new(2, 1, vec![plate("Cyan", [0.0; 4], &[1])]).is_none(), "too few pixels"); + assert!(Separated::new(1, 1, vec![plate("A", [0.0; 4], &[1]), plate("A", [0.0; 4], &[1])]).is_none(), "the same name twice"); + assert!(Separated::new(1, 1, vec![plate("", [0.0; 4], &[1])]).is_none(), "no name"); + assert!(Separated::new(1, 1, vec![plate("A", [2.0, 0.0, 0.0, 0.0], &[1])]).is_none(), "equivalent past 100%"); + assert!(Separated::new(0, 1, vec![plate("A", [0.0; 4], &[])]).is_none(), "empty"); + let many: Vec = (0..=MAX_PLATES).map(|i| plate(&format!("S{i}"), [0.0; 4], &[1])).collect(); + assert!(Separated::new(1, 1, many).is_none(), "too many plates"); + assert!(Separated::fits(1 << 13, 1 << 13, 8), "512 MB of ink amounts"); + assert!(!Separated::fits(1 << 13, 1 << 13, 9), "more than 512 MB together"); + assert!(!Separated::fits(1 << 14, 1 << 13, 1), "more pixels than a CMYK image is decoded with"); + } +} diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 80db3d923a..ba79f7c280 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -5,7 +5,7 @@ //! tint (`Paint::Solid.swatch` / `.tint`, `GradientStop.swatch` / `.tint`); a tint swatch is a //! swatch whose own paint links to its base that way. [`Document::map_solid_paints`] rewrites //! those links (and colours) wherever art and swatches hold them, copying only the nodes that -//! change. +//! change; [`Document::map_paints`] replaces whole paints of any kind in the same places. use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -124,6 +124,52 @@ impl Document { /// ([`Paint::map_links`]). Only nodes holding a changed paint (and the paths to them) are /// copied. Returns the number of changed paints. pub fn map_solid_paints(&mut self, f: &mut LinkFn) -> usize { + let mut n = self.map_art_paints(&mut relink(f)); + for gs in &mut self.graphic_styles { + for it in &mut gs.appearance.items { + n += usize::from(item_paint_mut(it).map_links(f)); + } + } + for w in self.swatches_iter_mut() { + n += usize::from(w.paint.map_links(f)); + } + let mut g = relink(f); + for def in &mut self.char_styles { + for key in ["fill", "stroke"] { + n += usize::from(map_style_paint(&mut def.attrs, key, &mut g)); + } + } + n + } + + /// Visit every paint in the places [`Document::map_solid_paints`] visits (fills, strokes, text + /// runs, image colorize paints, dynamic symbol instances' own paints and graphs' stored series and + /// label paints in the art, opacity masks included, symbol definitions, graph designs, pattern tiles and the tile that pattern + /// editing's Cancel puts back; graphic styles; the swatches; character styles' fill and + /// stroke), whatever its kind. `f(paint)` gives the paint to put in its place, or `None` to keep + /// it. Only nodes holding a changed paint (and the paths to them) are copied. Returns the number + /// of changed paints. + pub fn map_paints(&mut self, f: &mut PaintFn) -> usize { + let mut n = self.map_art_paints(f); + for gs in &mut self.graphic_styles { + for it in &mut gs.appearance.items { + n += usize::from(replace_paint(item_paint_mut(it), f)); + } + } + for w in self.swatches_iter_mut() { + n += usize::from(replace_paint(&mut w.paint, f)); + } + for def in &mut self.char_styles { + for key in ["fill", "stroke"] { + n += usize::from(map_style_paint(&mut def.attrs, key, f)); + } + } + n + } + + /// [`Document::map_paints`] limited to the node trees: the art, symbol definitions, graph + /// designs, pattern tiles and the tile that pattern editing's Cancel puts back. + fn map_art_paints(&mut self, f: &mut PaintFn) -> usize { let mut n = map_trees(&mut self.layers, f); for s in &mut self.symbols { n += map_tree(&mut s.art, f); @@ -134,19 +180,6 @@ impl Document { for p in self.patterns.iter_mut().chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())) { n += map_trees(&mut p.art, f); } - for gs in &mut self.graphic_styles { - for it in &mut gs.appearance.items { - n += usize::from(item_paint_mut(it).map_links(f)); - } - } - for w in self.swatches_iter_mut() { - n += usize::from(w.paint.map_links(f)); - } - for def in &mut self.char_styles { - for key in ["fill", "stroke"] { - n += usize::from(map_style_paint(&mut def.attrs, key, f)); - } - } n } @@ -156,9 +189,10 @@ impl Document { let roots: Vec = ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); let mut n = 0; + let mut g = relink(f); for id in roots { let Some(node) = self.node(id) else { continue }; - if let Some((new, count)) = map_node(node, f) + if let Some((new, count)) = map_node(node, &mut g) && let Some(slot) = self.node_mut(id) { *slot = new; @@ -176,7 +210,7 @@ impl Document { pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) { let mut tree = |n: &Node| { walk_with_masks(n, &mut |m| { - node_paints(m).chain(override_paints(m)).for_each(&mut *f); + node_paints(m).chain(override_paints(m)).chain(graph_paints(m)).for_each(&mut *f); if let NodeKind::Mesh(mesh) = &m.kind { mesh.points.iter().for_each(|p| f(&Paint::solid(p.color))); } @@ -258,14 +292,39 @@ impl FreeSwatchNames { /// true when it changed them. pub type LinkFn<'a> = dyn FnMut(&mut Color, &mut Option, &mut f32) -> bool + 'a; -/// Apply `f` to the paint a character style's attribute `key` holds, as [`Paint::map_links`] -/// does, and store the result in the attribute. True when it changed. -fn map_style_paint(attrs: &mut serde_json::Map, key: &str, f: &mut LinkFn) -> bool { - let Some(value) = attrs.get_mut(key) else { return false }; - let Ok(mut paint) = serde_json::from_value::(value.clone()) else { return false }; - if !paint.map_links(f) { - return false; +/// What [`Document::map_paints`] applies to each paint: the paint to put in its place, or `None` +/// to keep it. +pub type PaintFn<'a> = dyn FnMut(&Paint) -> Option + 'a; + +/// `f` as a [`PaintFn`]: a solid or gradient paint with `f` applied ([`Paint::map_links`]) when +/// `f` changed it, `None` for every other paint. +fn relink<'a>(f: &'a mut LinkFn<'_>) -> impl FnMut(&Paint) -> Option + 'a { + move |p| match p { + Paint::Solid { .. } | Paint::Gradient(_) => { + let mut q = p.clone(); + q.map_links(f).then_some(q) + } + _ => None, } +} + +/// Put `f(p)` in place of `p` when it gives a paint. True when it did. +fn replace_paint(p: &mut Paint, f: &mut PaintFn) -> bool { + match f(p) { + Some(q) => { + *p = q; + true + } + None => false, + } +} + +/// Apply `f` to the paint a character style's attribute `key` holds and store the result in the +/// attribute. An attribute that is not a paint stays as it is. True when it changed. +fn map_style_paint(attrs: &mut serde_json::Map, key: &str, f: &mut PaintFn) -> bool { + let Some(value) = attrs.get_mut(key) else { return false }; + let Ok(paint) = serde_json::from_value::(value.clone()) else { return false }; + let Some(paint) = f(&paint) else { return false }; match serde_json::to_value(&paint) { Ok(changed) => { *value = changed; @@ -323,6 +382,23 @@ pub fn override_paints(n: &Node) -> impl Iterator { n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten() } +/// The paints a graph keeps for its series and its labels ([`crate::graph::GraphSpec`]), which its +/// marks and labels take each time it is drawn again and which [`node_paints`] leaves out. +pub fn graph_paints(n: &Node) -> impl Iterator { + let g = n.extras().graph.as_deref(); + let series = g.into_iter().flat_map(|g| &g.series_paints).flat_map(|s| [s.fill.as_ref(), s.stroke.as_ref()]).flatten(); + let labels = g.into_iter().flat_map(|g| [&g.label_styles.values, &g.label_styles.categories, &g.label_styles.legend]).flatten(); + series.chain(labels.flat_map(|st| [&st.fill, &st.stroke])) +} + +/// Mutable [`graph_paints`] of graph `g`, in the same order. +fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator { + let series = g.series_paints.iter_mut().flat_map(|s| [s.fill.as_mut(), s.stroke.as_mut()]).flatten(); + let l = &mut g.label_styles; + let labels = [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten(); + series.chain(labels.flat_map(|st| [&mut st.fill, &mut st.stroke])) +} + /// Mutable [`node_paints`], in the same order. pub fn node_paints_mut(n: &mut Node) -> impl Iterator { let runs = match &mut n.kind { @@ -333,20 +409,11 @@ pub fn node_paints_mut(n: &mut Node) -> impl Iterator { n.appearance.items.iter_mut().map(item_paint_mut).chain(runs.iter_mut().flat_map(|r| [&mut r.style.fill, &mut r.style.stroke])).chain(colorize) } -/// `n` with `f` applied to its subtree's linkable colours, or `None` when nothing changed (then -/// nothing was copied). Also returns the number of changed paints. -fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> { - // Try each own solid or gradient paint on a scratch copy first, so unchanged nodes are never - // cloned. - let mut changes: Vec<(usize, Paint)> = vec![]; - for (i, p) in node_paints(n).enumerate() { - if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) { - let mut q = p.clone(); - if q.map_links(f) { - changes.push((i, q)); - } - } - } +/// `n` with `f` applied to its subtree's paints, or `None` when nothing changed (then nothing was +/// copied). Also returns the number of changed paints. +fn map_node(n: &Node, f: &mut PaintFn) -> Option<(Node, usize)> { + // `f` gives each own paint's replacement first, so unchanged nodes are never cloned. + let changes: Vec<(usize, Paint)> = node_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect(); let mut count = changes.len(); let mut out: Option = None; if !changes.is_empty() { @@ -366,15 +433,29 @@ fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> { let mut overrides = n.extras().symbol_overrides.clone(); let mut k = 0; for p in overrides.iter_mut().flat_map(|o| [&mut o.fill, &mut o.stroke]).flatten() { - if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) && p.map_links(f) { - k += 1; - } + k += usize::from(replace_paint(p, f)); } if k > 0 { out.get_or_insert_with(|| n.clone()).extras_mut().symbol_overrides = overrides; count += k; } } + // A graph's series and label paints, which its marks and labels take when it is drawn again. + let graph: Vec<(usize, Paint)> = graph_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect(); + if !graph.is_empty() { + count += graph.len(); + let m = out.get_or_insert_with(|| n.clone()); + if let Some(spec) = m.extras_if_any().and_then(|e| e.graph.as_deref_mut()) { + let mut graph = graph.into_iter().peekable(); + for (i, p) in graph_paints_mut(spec).enumerate() { + if graph.peek().is_some_and(|c| c.0 == i) + && let Some((_, q)) = graph.next() + { + *p = q; + } + } + } + } if let Some(ch) = n.children() { for (i, c) in ch.iter().enumerate() { if let Some((new, k)) = map_node(c, f) { @@ -415,6 +496,13 @@ pub fn walk_with_masks<'a>(n: &'a Node, f: &mut dyn FnMut(&'a Node)) { /// brush: `f` applied to the linkable colors of `n` and its subtree (opacity masks included). Only /// the nodes holding a changed paint are copied. Returns the number of changed paints. pub fn map_node_solid_paints(n: &mut Node, f: &mut LinkFn) -> usize { + map_node_paints(n, &mut relink(f)) +} + +/// [`Document::map_paints`] for art a document keeps outside its trees, such as the art of a brush: +/// `f` applied to every paint of `n` and its subtree (opacity masks included). Only the nodes +/// holding a changed paint are copied. Returns the number of changed paints. +pub fn map_node_paints(n: &mut Node, f: &mut PaintFn) -> usize { match map_node(n, f) { Some((new, count)) => { *n = new; @@ -424,7 +512,7 @@ pub fn map_node_solid_paints(n: &mut Node, f: &mut LinkFn) -> usize { } } -fn map_tree(n: &mut Arc, f: &mut LinkFn) -> usize { +fn map_tree(n: &mut Arc, f: &mut PaintFn) -> usize { match map_node(n, f) { Some((new, count)) => { *n = Arc::new(new); @@ -434,7 +522,7 @@ fn map_tree(n: &mut Arc, f: &mut LinkFn) -> usize { } } -fn map_trees(v: &mut [Arc], f: &mut LinkFn) -> usize { +fn map_trees(v: &mut [Arc], f: &mut PaintFn) -> usize { v.iter_mut().map(|n| map_tree(n, f)).sum() } @@ -593,6 +681,35 @@ mod tests { assert_eq!(map_node_solid_paints(&mut loose, &mut to_blue), 0, "nothing left to change"); } + #[test] + fn mapping_reaches_the_series_and_label_paints_a_graph_keeps() { + let (mut d, a, _) = doc(); + let red = linked(Color::rgb(1.0, 0.0, 0.0), "Brand"); + let spec = crate::graph::GraphSpec { + series_paints: vec![crate::SeriesPaint { fill: Some(red.clone()), stroke: Some(red.clone()), ..Default::default() }], + label_styles: crate::graph::LabelStyles { + legend: Some(crate::CharStyle { fill: red.clone(), stroke: Paint::None, ..Default::default() }), + ..Default::default() + }, + ..Default::default() + }; + d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec)); + let mut seen = 0; + d.visit_paints(&mut |p| seen += usize::from(*p == red)); + assert_eq!(seen, 4, "the fill and the graph's series fill, series stroke and legend fill"); + let blue = Color::rgb(0.0, 0.0, 1.0); + let mut to_blue = |c: &mut Color, s: &mut Option, _: &mut f32| s.as_deref() == Some("Brand") && std::mem::replace(c, blue) != blue; + assert_eq!(d.map_solid_paints(&mut to_blue), 4); + let g = d.node(a).unwrap().extras().graph.clone().unwrap(); + assert_eq!(g.series_paints[0].fill, Some(linked(blue, "Brand"))); + assert_eq!(g.series_paints[0].stroke, Some(linked(blue, "Brand"))); + let legend = g.label_styles.legend.unwrap(); + assert_eq!((legend.fill, legend.stroke), (linked(blue, "Brand"), Paint::None)); + let mut cleared = |p: &Paint| (*p == linked(blue, "Brand")).then_some(Paint::None); + assert_eq!(d.map_paints(&mut cleared), 4, "the fill and the graph's three"); + assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none)); + } + #[test] fn mapping_within_ids_visits_each_paint_once() { let (mut d, a, b) = doc(); diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index a2c2a66498..45cf181f18 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -508,6 +508,21 @@ pub enum Mojikumi { /// Consecutive punctuation shares one half-em space (JLREQ 3.1.4), and a closing bracket, /// comma or full stop ending a line is set half width. LineEndHalf, + /// YakumonoHankaku: every opening and closing bracket, comma and full stop is set half width, + /// a middle dot loses a quarter em on each side, and a quarter em separates Japanese and Latin + /// letters or digits. + YakumonoHankaku, + /// GyomatsuYakumonoHankaku: punctuation keeps its full width, except that an opening bracket + /// starting a line is set flush with the line's start, a closing bracket, comma or full stop + /// ending a line is set half width and a middle dot ending a line loses the quarter em after + /// it; a quarter em separates Japanese and Latin letters or digits. + GyomatsuYakumonoHankaku, + /// GyomatsuYakumonoZenkaku: punctuation keeps its full width at a line's end too; a quarter em + /// separates Japanese and Latin letters or digits. + GyomatsuYakumonoZenkaku, + /// YakumonoZenkaku: punctuation keeps its full width, with no added space between Japanese and + /// Latin text. + YakumonoZenkaku, } impl Mojikumi { diff --git a/crates/effects/Cargo.toml b/crates/effects/Cargo.toml index d5821607ec..14f9a0d08f 100644 --- a/crates/effects/Cargo.toml +++ b/crates/effects/Cargo.toml @@ -15,6 +15,7 @@ vectorcraft-doc = { workspace = true } vectorcraft-pathops = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-plugins = { workspace = true } +vectorcraft-trace = { workspace = true } image = { workspace = true } kurbo = { workspace = true } # Effect › SVG Filters draws its filters with resvg (MIT OR Apache-2.0), at the usvg version the 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/catalog.rs b/crates/effects/src/catalog.rs index 9fe7d51f47..dff0bf6f8e 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -296,7 +296,7 @@ pub fn effect_catalog() -> Vec { "path.outlineObject", "Outline Object", PATH, - "{} type is drawn, exported and expanded as its glyph outlines and stays editable, and the effects after it reshape those outlines; paths and images do not change", + "{} type is drawn, exported and expanded as its glyph outlines and stays editable, and the effects after it reshape those outlines; paths and images do not change. On an image's own fill or stroke it gives the outline of the image's pixels that are at least half opaque (VectorCraft's own cutoff), and nothing when no pixel is; it gives the image's frame when the image has no transparency, its pixels can't be read, or the image or its outline is too large to trace", json!({}), ), g( diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 0c980a0c43..c475e86490 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -80,8 +80,8 @@ pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry}; pub use reshape::{ - SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art, - has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape, + SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, + has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape, }; pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 16c271dca0..2bda0aa88f 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -10,12 +10,13 @@ //! inline graphics whose own fills or strokes have geometry effects is outlined too: each of those //! effects reshapes the whole outline that its fill or stroke paints. An image's own fills and //! strokes paint only the shape that a Convert to Shape or Outline Object effect on them gives -//! them ([`image_rows`]). +//! them ([`image_rows`]): Outline Object follows the outline of the image's opaque area +//! ([`opaque_area`]). -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::rc::Rc; -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak}; use vectorcraft_doc::live::Hooks; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, ImageObject, Node, NodeId, NodeKind}; @@ -130,19 +131,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 { @@ -164,8 +288,8 @@ pub fn gives_image_shape(effects: &[Effect]) -> bool { /// The fills and strokes of `items` (an image's own) that paint something ([`shapes_image`]), each /// without the effects before its first Convert to Shape or Outline Object. Convert to Shape sizes -/// its shape from the image's box, and Outline Object gives the image's frame. The others paint -/// nothing. +/// its shape from the image's box, and Outline Object gives the outline of the image's opaque +/// area ([`opaque_area`]), or its frame when it has no transparency. The others paint nothing. fn image_rows(items: &[AppearanceItem]) -> Vec { items .iter() @@ -180,11 +304,109 @@ fn image_rows(items: &[AppearanceItem]) -> Vec { .collect() } +/// Does `item`, one of [`image_rows`], start from the outline of the image's opaque area (is its +/// first effect Outline Object rather than Convert to Shape)? +fn follows_opaque_area(item: &AppearanceItem) -> bool { + item.effects().first().is_some_and(|e| e.id == "path.outlineObject") +} + +/// Is `n` an image with a fill or stroke of its own that follows the outline of the image's opaque +/// area ([`image_rows`], [`opaque_area`])? The shape that fill or stroke paints then changes with +/// the image's pixels in the document while `n` stays the same. +pub fn follows_image_pixels(n: &Node) -> bool { + matches!(n.kind, NodeKind::Image(_)) + && n.appearance + .items + .iter() + .any(|i| shapes_image(i) && i.effects().iter().find(|e| gives_shape(e)).is_some_and(|e| e.id == "path.outlineObject")) +} + +/// The outline of a set of pixels' opaque area, in the pixel space they decode to, with that size +/// ([`traced_opaque_area`]). `None` for pixels that have no transparency or could not be traced. +type Traced = Option<(Arc, (u32, u32))>; + +/// One of [`Outlines`]' entries: the pixels, held weakly, and their outline once it is traced. +type Entry = (Weak>, Arc>); + +/// The outlines [`opaque_area`] has traced, by the address of the pixels each was traced from. +struct Outlines { + /// Each outline with its pixels. An entry does not keep its pixels, and while it is kept no + /// other pixels can take their address. Entries whose pixels are gone are dropped before a + /// new outline is traced and every [`PRUNE_EVERY`] lookups. + kept: BTreeMap, + /// The lookups since the last pruning. + lookups: usize, +} + +static OUTLINES: Mutex = Mutex::new(Outlines { kept: BTreeMap::new(), lookups: 0 }); + +/// How many lookups [`OUTLINES`] takes between two prunings of its entries for pixels that are gone. +const PRUNE_EVERY: usize = 256; + +#[cfg(test)] +thread_local! { + /// The outlines [`traced_opaque_area`] has traced on this thread. + pub(crate) static TRACES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Does [`OUTLINES`] keep an entry for `pixels`? +#[cfg(test)] +pub(crate) fn keeps_outline(pixels: &Weak>) -> bool { + OUTLINES.lock().unwrap_or_else(PoisonError::into_inner).kept.values().any(|(w, _)| w.ptr_eq(pixels)) +} + +/// The outline of the opaque area of the image `im` in the document +/// ([`vectorcraft_trace::opaque_outline`]: its pixels that are at least half opaque, outlined with +/// fitted curves), its pixels taken from `im` itself or from the first of `docs` that holds them. +/// `None` when the image has no transparency, its pixels can't be read or are too large to read +/// ([`vectorcraft_trace::decode_alpha`]), or its outline would be too complex: Outline Object then +/// follows the image's frame. The outline is traced once for each set of pixels and kept while +/// those pixels are: a caller that asks while another thread traces the same pixels waits for that +/// trace. +pub(crate) fn opaque_area(docs: &[Option<&Document>], im: &ImageObject) -> Option { + let blob = im.pixels.as_deref().or_else(|| docs.iter().flatten().find_map(|d| d.images.get(&im.key)))?; + let bytes = &blob.bytes; + let cell = { + let mut o = OUTLINES.lock().unwrap_or_else(PoisonError::into_inner); + o.lookups += 1; + if o.lookups >= PRUNE_EVERY { + o.lookups = 0; + o.kept.retain(|_, (w, _)| w.strong_count() > 0); + } + let key = Arc::as_ptr(bytes).addr(); + match o.kept.get(&key) { + Some((_, cell)) => Arc::clone(cell), + None => { + o.kept.retain(|_, (w, _)| w.strong_count() > 0); + let cell = Arc::new(OnceLock::new()); + o.kept.insert(key, (Arc::downgrade(bytes), Arc::clone(&cell))); + cell + } + } + }; + // Traced without the lock: another image's outline need not wait for this one. + let (path, (w, h)) = cell.get_or_init(|| traced_opaque_area(bytes)).clone()?; + let to_image = Affine::scale_non_uniform(f64::from(im.width) / f64::from(w.max(1)), f64::from(im.height) / f64::from(h.max(1))); + Some(path.transformed(im.xf * to_image)) +} + +/// [`opaque_area`]'s outline of the encoded image `bytes`. An image whose format has no alpha is +/// not decoded. +fn traced_opaque_area(bytes: &[u8]) -> Traced { + #[cfg(test)] + TRACES.with(|t| t.set(t.get() + 1)); + let (w, h, alpha) = vectorcraft_trace::decode_alpha(bytes).ok()??; + let outline = vectorcraft_trace::opaque_outline(w, h, alpha).ok()??; + Some((Arc::new(outline), (w, h))) +} + /// The shapes that the image `n`'s own fills and strokes paint ([`image_rows`]), each with its fill -/// rule and the fill or stroke that paints it: the paths (or compound paths) along its frame that -/// [`reshape`] makes, with each fill's or stroke's geometry effects applied as the renderer applies -/// them. Empty for anything but an image with such fills or strokes. The swatches and patterns that -/// live-effect plug-ins painting their pieces name are looked up in `doc`. +/// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`] +/// makes along its frame or, for those whose first effect is Outline Object, along the outline of +/// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the +/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches +/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and +/// the image's pixels in `doc` when the image does not hold them. pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { return vec![]; @@ -302,7 +524,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 +575,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; @@ -480,9 +707,10 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping /// `n` (see [`needs_outline`]) with its object-level geometry effects and its perspective applied: /// its [`outline_art`] reshaped as one piece, or for an image the image clipped by its reshaped /// frame. Type's own fills and strokes keep their effects on its whole outline. An image's own -/// fills and strokes that paint a shape ([`image_rows`]) become paths along its frame below and -/// above it, reshaped with it, and keep their effects from their first Convert to Shape or Outline -/// Object on. The result is a group with `n`'s id, name, visibility, transparency, opacity mask +/// fills and strokes that paint a shape ([`image_rows`]) become paths below and above it, along +/// its frame or, from Outline Object, along the outline of its opaque area ([`opaque_area`]), +/// reshaped with it, and keep their effects from their first Convert to Shape or Outline Object +/// on. The result is a group with `n`'s id, name, visibility, transparency, opacity mask /// and remaining (raster) effects; `None` when `n` has no visible geometry effect, no perspective /// and is not type or an image with a fill or stroke of its own that [`has_item_geometry`] counts, /// or has no art (a symbol instance without `symbol_art`). A path with [`has_transform_art`] is @@ -497,8 +725,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 +782,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()); @@ -566,15 +797,33 @@ fn as_art_opts( } Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image.clone())], clip: true }) }; - // The fills and strokes that paint a shape, as paths along the frame below and above - // the image. + // The fills and strokes that paint a shape, as paths below and above the image: along + // the frame, or for those whose first effect is Outline Object along the outline of + // the image's opaque area (traced only when one of them needs it). A run of either + // kind is one path; a fill or stroke whose outline is empty (an image with no opaque + // pixel) paints nothing. let (below, above) = n.appearance.split_contents(); let (below, above) = (image_rows(below), image_rows(above)); if below.is_empty() && above.is_empty() { clipped() } else { + let opaque = std::cell::OnceCell::new(); let rows = |items: Vec| { - (!items.is_empty()).then(|| Arc::new(Node::path(n.id, frame.clone(), Appearance { items, ..Default::default() }))) + let mut out = vec![]; + let mut items = items.into_iter().peekable(); + while let Some(first) = items.next() { + let follows = follows_opaque_area(&first); + let mut run = vec![first]; + while let Some(next) = items.next_if(|i| follows_opaque_area(i) == follows) { + run.push(next); + } + let path = if follows { opaque.get_or_init(|| opaque_area(&[symbols, paint_doc], im)).as_ref() } else { None }; + let path = path.unwrap_or(&frame); + if !path.is_empty() { + out.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: run, ..Default::default() }))); + } + } + out }; // Without geometry effects, the image is not clipped. let image = if fx.is_empty() { image.clone() } else { clipped() }; diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 4409b34352..78b8ca583b 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -927,7 +927,8 @@ fn masks_surface(paint: &Paint, colored: bool) -> bool { } /// The graphics of the solids `filled` ([`graphic_art`]), each with the index of the surface it is -/// drawn right after (the last of those solids holding its face) and its face. With `per_member` +/// drawn right after (the last of those solids holding its face) and its face. Solids in a run +/// with the same opacity and blending mode share their graphics. With `per_member` /// (a member's opacity mask or blending mode applies to its surfaces) each member's solids get /// graphics of their own, clipped to that member's caps, so they stay in that member's scopes. /// All the groups share one limit on the path elements drawn: once it is reached, later groups @@ -944,11 +945,12 @@ fn placed_graphics( for f in filled { // Solids whose fills or strokes differ in opacity or blending mode get graphics of their // own, each drawn as its fill or stroke is. A solid whose surface carries an opacity mask - // gets its own too, which takes that mask ([`with_graphics`]). + // gets its own too, which takes that mask ([`with_graphics`]). A solid joins only the + // group of the solid before it, so a graphic is never drawn past a solid painted between. let joins = |first: &Filled| { (!per_member || first.member == f.member) && first.opacity == f.opacity && first.blend == f.blend && !first.masked && !f.masked }; - match groups.iter_mut().find(|g| g.first().is_some_and(|first| joins(first))) { + match groups.last_mut().filter(|g| g.first().is_some_and(|first| joins(first))) { Some(g) => g.push(f), None => groups.push(vec![f]), } 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_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index 64c947a9df..aa73535fc5 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -365,6 +365,41 @@ fn members_with_their_own_blending_get_graphics_of_their_own() { assert_eq!(blended, 1); } +#[test] +fn a_graphic_stays_under_a_solid_painted_after_its_own() { + let d = document(); + let member = |id: u64, r: Rect, color: Color, opacity: f32| { + let mut n = square(id, r, Paint::solid(color)); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.opacity = opacity; + } + Arc::new(n) + }; + let gray = Color::rgb(0.5, 0.5, 0.5); + // A and C share their fill's opacity; B, painted between them, has its own and covers part of A. + let a = member(1, Rect::new(0.0, 0.0, 60.0, 100.0), gray, 1.0); + let b = member(2, Rect::new(40.0, 0.0, 100.0, 100.0), Color::rgb(0.0, 0.0, 1.0), 0.5); + let c = member(4, Rect::new(200.0, 0.0, 260.0, 100.0), gray, 1.0); + let mut group = Node::group(NodeId(3), vec![a, b, c]); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 3000.0}]}); + group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + let art = solid_art_in(Some(&d), &group).unwrap(); + // In drawing order: 'G' for a graphic, 'B' for a face of B's solid. + let mut order = String::new(); + art.walk(&mut |n| { + if matches!(n.kind, NodeKind::Group { clip: true, .. }) && !graphics_in(n).is_empty() { + order.push('G'); + } else if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first() + && f.paint.color().is_some_and(|c| c.to_rgb()[2] > 0.9 && c.to_rgb()[0] < 0.1) + { + order.push('B'); + } + }); + // A's graphic is drawn right after A, under B; C's is drawn after B. + assert_eq!(graphics_in(&art).len(), 3, "{order}"); + assert!(order.starts_with('G'), "{order}"); +} + /// [`document`] with symbol "Dense" too: a red polygon of 30,000 sides, straight or `curved`. fn dense_document(curved: bool) -> Document { let mut d = document(); 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/effects/src/tests.rs b/crates/effects/src/tests.rs index 88300586b3..56f9d40633 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -4,6 +4,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Shape, SubPath, shapes}; use super::*; +mod imageoutline; mod rasterfollow; mod scale; mod transformfx; @@ -886,6 +887,108 @@ fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move() { } } +/// Under a Warp effect a hidden path in a layer that keeps its shape past the budget does not hold +/// the layer's gradient in place either: it moves and scales from the layer's bounds to the warped +/// square's bounds, as the art and inside the art. +#[test] +fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_follow_a_warp() { + use std::sync::Arc; + + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + use vectorcraft_doc::{AppearanceItem, FillLayer, LayerColor, NodeId, NodeKind, color::Paint}; + let stops = vec![GradientStop::new(0.0, vectorcraft_color::Color::BLACK), GradientStop::new(1.0, vectorcraft_color::Color::WHITE)]; + let geom = GradientGeom { start: (0.0, 50.0).into(), end: (100.0, 50.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) })); + let ends = |ap: &Appearance| match ap.fill_paint() { + Paint::Gradient(g) => g.geom.map(|g| (g.start, g.end)), + _ => None, + }; + let oval = || shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + // A layer with a visible square and a hidden circle, both 0..100, and a gradient fill of its own. + let layer = || { + let square = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default())); + let mut circle = Node::path(NodeId(4), oval(), Appearance::default()); + circle.visible = false; + let mut layer = Node::layer(NodeId(2), "Layer 1", LayerColor::Preset(0)); + if let NodeKind::Layer { children, .. } = &mut layer.kind { + *children = vec![square, Arc::new(circle)]; + } + layer.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone()))); + layer + }; + // The box map from the layer's bounds (the square's) to `b`: (0, 50) and (100, 50) go to the + // middles of b's sides. + let near = |got: Option<(Point, Point)>, b: Rect| { + let mid = (b.y0 + b.y1) / 2.0; + got.is_some_and(|(s, e)| s.distance(Point::new(b.x0, mid)) < 1e-6 && e.distance(Point::new(b.x1, mid)) < 1e-6) + }; + for style in ["arc", "inflate", "flag"] { + let warp = fx(&format!("warp.{style}"), json!({"bend": 40.0, "horizontal": 20.0})); + // Room for the warped square beside the circle as it was, and not for the warped circle + // beside the warped square: the paths take the budget in turn, so the circle keeps its shape. + let mut probe = layer(); + crate::reshape::reshape_leaves_within(&mut probe, &[&warp], Budget::EFFECTS, None); + let warped = |k: usize| util::line_estimate(probe.children().unwrap()[k].path_data().unwrap()); + let circle = util::line_estimate(&oval()); + assert!(warped(1) > circle, "warp.{style}: the warped circle is drawn with more lines"); + let budget = Budget { anchors: usize::MAX, lines: warped(0) + circle }; + let mut art = layer(); + let carry = crate::reshape::reshape_leaves_within(&mut art, &[&warp], budget, None); + assert_eq!(art.children().unwrap()[1].path_data(), Some(&oval()), "{}: the hidden circle keeps its shape", warp.id); + let square = art.children().unwrap()[0].geometric_bounds().unwrap(); + assert!(square != Rect::new(0.0, 0.0, 100.0, 100.0), "{}: the square takes the effect: {square:?}", warp.id); + let mut own = Appearance::clone(&art.appearance); + carry.apply(&mut own); + assert!(near(ends(&own), square), "{}: the layer's gradient, as the art: {:?} for {square:?}", warp.id, ends(&own)); + let mut art = Node::group(NodeId(9), vec![Arc::new(layer())]); + crate::reshape::reshape_leaves_within(&mut art, &[&warp], budget, None); + let got = ends(&art.children().unwrap()[0].appearance); + assert!(near(got, square), "{}: the layer's gradient, inside the art: {got:?} for {square:?}", warp.id); + } +} + +/// A freeform gradient whose points were edited moves its points with a Warp effect from the +/// bounds before the warp to the bounds after it, on a path, on a group inside the art and on the +/// art itself, as a placed gradient does. +#[test] +fn edited_freeform_points_follow_a_warp() { + use std::sync::Arc; + + use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint}; + use vectorcraft_doc::{AppearanceItem, FillLayer, NodeId, color::Paint}; + let mut ramp = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Gradient::default() }); + let pt = |x: f64, c| FreeformPoint::new(Point::new(x, 50.0), c); + ramp.set_freeform(Freeform { points: vec![pt(0.0, Color::BLACK), pt(100.0, Color::WHITE)], ..Default::default() }); + assert!(ramp.geom.is_none() && !ramp.is_placed()); + let freeform = Paint::Gradient(Box::new(ramp)); + let points = |ap: &Appearance| match ap.fill_paint() { + Paint::Gradient(g) => g.freeform.as_ref().map(|f| f.points.iter().map(|p| p.at).collect::>()), + _ => None, + }; + let square = |ap: Appearance| Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap)); + // The box map from the square's bounds to `b`: (0, 50) and (100, 50) go to the middles of b's sides. + let near = |got: Option>, b: Rect| { + let mid = (b.y0 + b.y1) / 2.0; + got.is_some_and(|p| p.len() == 2 && p[0].distance(Point::new(b.x0, mid)) < 1e-6 && p[1].distance(Point::new(b.x1, mid)) < 1e-6) + }; + for style in ["arc", "inflate", "rise"] { + let e = fx(&format!("warp.{style}"), json!({"bend": 40.0, "vertical": 20.0})); + let mut inner = Node::group(NodeId(2), vec![square(Appearance::default())]); + inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone()))); + let mut art = Node::group(NodeId(9), vec![square(Appearance::basic(freeform.clone(), Paint::None, 0.0)), Arc::new(inner)]); + art.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone()))); + let carry = crate::reshape::reshape_leaves_within(&mut art, &[&e], Budget::EFFECTS, None); + let b = art.geometric_bounds().unwrap(); + assert!(b != Rect::new(0.0, 0.0, 100.0, 100.0), "{}: the warp changes the bounds: {b:?}", e.id); + let members = art.children().unwrap(); + assert!(near(points(&members[0].appearance), b), "{}: the path's points {:?} for {b:?}", e.id, points(&members[0].appearance)); + assert!(near(points(&members[1].appearance), b), "{}: the inner group's points {:?} for {b:?}", e.id, points(&members[1].appearance)); + let mut own = Appearance::clone(&art.appearance); + carry.apply(&mut own); + assert!(near(points(&own), b), "{}: the art's own points {:?} for {b:?}", e.id, points(&own)); + } +} + /// A freeform gradient whose points were edited (its vector still fitted to the bounds) moves its /// points with a Transform effect and Free Distort, on a path, on a group inside the art and on the /// art itself, as a placed gradient does. diff --git a/crates/effects/src/tests/imageoutline.rs b/crates/effects/src/tests/imageoutline.rs new file mode 100644 index 0000000000..5ef3955254 --- /dev/null +++ b/crates/effects/src/tests/imageoutline.rs @@ -0,0 +1,338 @@ +//! Outline Object on an image's own fill or stroke: the outline of the image's opaque area, for +//! every pixel format with alpha, and the frame for one without. + +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Document, Effect, FillLayer, ImageBlob, ImageObject, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_geom::{Affine, Rect}; + +use crate::*; + +fn fx(id: &str) -> Effect { + Effect { id: id.into(), params: json!({}), visible: true } +} + +/// `img` encoded as `format`. +fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec { + let mut out = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap(); + out +} + +/// A 100×100 RGBA image, transparent but for an opaque disc of radius 30 in its middle. +fn disc() -> image::DynamicImage { + image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(100, 100, |x, y| { + let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0); + image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }]) + })) +} + +/// A document holding the encoded image `bytes` (key "img") and an image object of 100×100 pixels +/// placed at (50, 50) with the appearance items `items`, the image's own row at `contents`. +/// → (document, the image's node). +fn image_doc(bytes: Vec, items: Vec, contents: usize) -> (Document, Node) { + let mut d = Document::new(200.0, 200.0); + d.images.insert("img".into(), ImageBlob::new("image/png", bytes)); + let mut n = Node::new( + NodeId(0), + NodeKind::Image(Box::new(ImageObject { + key: "img".into(), + width: 100, + height: 100, + xf: Affine::translate((50.0, 50.0)), + link: None, + placement: Default::default(), + pixels: None, + })), + ); + n.id = d.alloc_id(); + n.appearance.items = items; + n.appearance.set_contents_at(contents); + let l = d.layers[0].id; + d.insert(Some(l), 0, n.clone()).unwrap(); + (d, n) +} + +/// A PNG of `w × h` pixels with the color type `color` at `depth` bits, the chunks `extra` before +/// its pixels, and the filtered rows `rows` stored without compression. +fn png(w: u32, h: u32, color: u8, depth: u8, extra: &[(&[u8; 4], Vec)], rows: &[u8]) -> Vec { + fn crc(data: &[u8]) -> u32 { + let mut c = !0u32; + for &b in data { + c ^= u32::from(b); + for _ in 0..8 { + c = if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; + } + } + !c + } + let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut chunk = |kind: &[u8; 4], data: &[u8]| { + let mut body = kind.to_vec(); + body.extend_from_slice(data); + out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes()); + out.extend_from_slice(&body); + out.extend_from_slice(&crc(&body).to_be_bytes()); + }; + let mut ihdr = [w.to_be_bytes(), h.to_be_bytes()].concat(); + ihdr.extend([depth, color, 0, 0, 0]); + chunk(b"IHDR", &ihdr); + for (kind, data) in extra { + chunk(kind, data); + } + // A zlib stream of stored blocks. + let mut z = vec![0x78, 0x01]; + let blocks: Vec<&[u8]> = if rows.is_empty() { vec![rows] } else { rows.chunks(65_535).collect() }; + for (i, block) in blocks.iter().enumerate() { + let len = u16::try_from(block.len()).unwrap(); + z.push(u8::from(i + 1 == blocks.len())); + z.extend(len.to_le_bytes()); + z.extend((!len).to_le_bytes()); + z.extend_from_slice(block); + } + let (mut a, mut b) = (1u32, 0u32); + for &byte in rows { + a = (a + u32::from(byte)) % 65_521; + b = (b + a) % 65_521; + } + z.extend(((b << 16) | a).to_be_bytes()); + chunk(b"IDAT", &z); + chunk(b"IEND", &[]); + out +} + +fn stroke(effects: Vec) -> AppearanceItem { + let mut s = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0); + s.effects = effects; + AppearanceItem::Stroke(s) +} + +/// The bounds of the paths the image's own fills and strokes paint, below it first. +fn row_bounds(d: &Document, n: &Node) -> Vec { + let art = reshape::reshape(Some(d), n, None).unwrap(); + let mut out = vec![]; + for c in art.children().unwrap() { + if matches!(c.kind, NodeKind::Path { .. }) { + out.push(c.geometric_bounds().unwrap()); + } + } + out +} + +fn near(r: Rect, want: [f64; 4], tol: f64) -> bool { + [r.x0 - want[0], r.y0 - want[1], r.x1 - want[2], r.y1 - want[3]].iter().all(|d| d.abs() < tol) +} + +#[test] +fn outline_object_follows_the_opaque_area_of_an_image_with_alpha() { + let gray_alpha = image::DynamicImage::ImageLumaA8(disc().to_luma_alpha8()); + let deep = image::DynamicImage::ImageRgba16(disc().to_rgba16()); + for (name, img) in [("rgba", disc()), ("gray and alpha", gray_alpha), ("16 bits a channel", deep)] { + let (d, n) = image_doc(encoded(img, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let rows = row_bounds(&d, &n); + assert_eq!(rows.len(), 1, "{name}"); + // The disc runs from 70 to 130; the frame from 50 to 150. + assert!(near(rows[0], [70.0, 70.0, 130.0, 130.0], 0.5), "{name}: {:?}", rows[0]); + } +} + +#[test] +fn outline_object_follows_the_frame_of_an_image_without_transparency() { + let opaque = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(100, 100, image::Rgb([0, 0, 255]))); + let solid = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 255, 200]))); + let formats = [ + ("jpeg", encoded(opaque.clone(), image::ImageFormat::Jpeg)), + ("rgb png", encoded(opaque, image::ImageFormat::Png)), + ("rgba png, every pixel more than half opaque", encoded(solid, image::ImageFormat::Png)), + ]; + for (name, bytes) in formats { + let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1); + let rows = row_bounds(&d, &n); + assert!(rows.len() == 1 && near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{name}: {rows:?}"); + } + // Pixels that can't be read keep the frame too. + let (d, n) = image_doc(b"not an image".to_vec(), vec![stroke(vec![fx("path.outlineObject")])], 1); + assert!(near(row_bounds(&d, &n)[0], [50.0, 50.0, 150.0, 150.0], 1e-9)); +} + +#[test] +fn convert_to_shape_keeps_the_frame_beside_outline_object() { + // Below the image: a fill with Convert to Shape, then a stroke with Outline Object; above it + // a stroke with Convert to Shape before Outline Object, which starts from the frame. + let rect = Effect { id: "convertToShape.rectangle".into(), params: json!({"relative": true, "extraW": 0, "extraH": 0}), visible: true }; + let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0))); + fill.effects = vec![rect.clone()]; + let items = vec![AppearanceItem::Fill(fill), stroke(vec![fx("path.outlineObject")]), stroke(vec![rect, fx("path.outlineObject")])]; + let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), items, 2); + let rows = row_bounds(&d, &n); + assert_eq!(rows.len(), 3, "{rows:?}"); + assert!(near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}"); + assert!(near(rows[1], [70.0, 70.0, 130.0, 130.0], 0.5), "{rows:?}"); + assert!(near(rows[2], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}"); + // The image keeps its place between them. + let art = reshape::reshape(Some(&d), &n, None).unwrap(); + assert!(matches!(art.children().unwrap()[2].kind, NodeKind::Image(_))); +} + +#[test] +fn a_transparent_image_gives_outline_object_nothing_to_paint() { + let clear = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 0, 100]))); + let (d, n) = image_doc(encoded(clear, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + assert!(row_bounds(&d, &n).is_empty()); + let art = reshape::reshape(Some(&d), &n, None).unwrap(); + assert!(matches!(art.children().unwrap().as_slice(), [only] if matches!(only.kind, NodeKind::Image(_)))); +} + +#[test] +fn the_outline_follows_the_images_own_pixels_and_placement() { + // Pixels kept on the image itself (art made outside a document), placed at half size. + let (_, mut n) = image_doc(vec![], vec![stroke(vec![fx("path.outlineObject")])], 1); + if let NodeKind::Image(im) = &mut n.kind { + im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), image::ImageFormat::Png)))); + im.xf = Affine::translate((10.0, 20.0)) * Affine::scale(0.5); + } + let art = reshape::reshape(None, &n, None).unwrap(); + let b = art.children().unwrap()[0].geometric_bounds().unwrap(); + // The disc runs from 20 to 80 pixels: half that, moved by (10, 20). + assert!(near(b, [20.0, 30.0, 50.0, 60.0], 0.3), "{b:?}"); +} + +#[test] +fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels() { + // A 120×60 image whose opaque area is the rectangle from (12, 6) to (40, 24), its pixels a + // copy at half size (as a linked image's preview is), turned a quarter and reflected. + let half = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(60, 30, |x, y| { + image::Rgba([255, 0, 0, if (6..20).contains(&x) && (3..12).contains(&y) { 255 } else { 0 }]) + })); + let (d, mut n) = image_doc(encoded(half, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let xf = Affine::translate((100.0, 40.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(-1.0, 1.0); + if let NodeKind::Image(im) = &mut n.kind { + (im.width, im.height, im.xf) = (120, 60, xf); + } + let rows = row_bounds(&d, &n); + let want = xf.transform_rect_bbox(Rect::new(12.0, 6.0, 40.0, 24.0)); + // The rectangle runs from (76, 0) to (94, 28); a flip in either direction, or the copy's + // width and height swapped, would move it. + assert!(near(want, [76.0, 0.0, 94.0, 28.0], 1e-9), "{want:?}"); + assert!(rows.len() == 1 && near(rows[0], [want.x0, want.y0, want.x1, want.y1], 0.5), "{rows:?}"); +} + +#[test] +fn an_image_in_a_group_exports_with_its_outline() { + let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let l = d.layers[0].id; + d.remove(n.id).unwrap(); + let g = d.alloc_id(); + d.insert(Some(l), 0, Node::group(g, vec![Arc::new(n)])).unwrap(); + let baked = bake_document(&d).unwrap(); + let mut paths = vec![]; + for layer in &baked.layers { + layer.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { .. }) && (c.appearance.stroke_width() - 4.0).abs() < 1e-9 { + paths.push(c.geometric_bounds().unwrap()); + } + }); + } + assert!(matches!(paths.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{paths:?}"); +} + +/// The bounds of the paths stroked 4 pt in `d` with its effects baked, as exports write it. +fn baked_strokes(d: &Document) -> Vec { + let baked = bake_document(d).unwrap(); + let mut paths = vec![]; + for layer in &baked.layers { + layer.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { .. }) && (c.appearance.stroke_width() - 4.0).abs() < 1e-9 { + paths.push(c.geometric_bounds().unwrap()); + } + }); + } + paths +} + +#[test] +fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outline() { + let disc_outline = |paths: &[Rect]| matches!(paths, [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)); + // Under a clipping mask that covers the whole image. + let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let l = d.layers[0].id; + d.remove(n.id).unwrap(); + let clip = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default()); + let g = d.alloc_id(); + d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(n)], clip: true })).unwrap(); + let paths = baked_strokes(&d); + assert!(disc_outline(&paths), "{paths:?}"); + // With an opacity mask. + let (mut d, mut n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let mut white = Node::path(NodeId(999), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default()); + white.appearance.set_fill(Paint::solid(Color::WHITE)); + n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(998), vec![Arc::new(white)]), true))); + let id = n.id; + *d.node_mut(id).unwrap() = n; + let paths = baked_strokes(&d); + assert!(disc_outline(&paths), "{paths:?}"); +} + +#[test] +fn outline_object_on_a_fill_and_on_an_indexed_image_follows_the_opaque_area() { + let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0))); + fill.effects = vec![fx("path.outlineObject")]; + let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![AppearanceItem::Fill(fill)], 1); + let rows = row_bounds(&d, &n); + assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}"); + // A palette image whose first color is transparent (a tRNS chunk). + let mut rows = vec![]; + for y in 0..100 { + rows.push(0); + for x in 0..100 { + let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0); + rows.push(u8::from(r <= 30.0)); + } + } + let palette = png(100, 100, 3, 8, &[(b"PLTE", vec![0, 0, 0, 255, 0, 0]), (b"tRNS", vec![0, 255])], &rows); + let (d, n) = image_doc(palette, vec![stroke(vec![fx("path.outlineObject")])], 1); + let rows = row_bounds(&d, &n); + assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}"); +} + +#[test] +fn an_image_too_large_or_too_complex_to_outline_keeps_its_frame() { + // 72 megapixels at 8 bits a channel, and 42 at 16: refused before their pixels are read. + for (w, h, depth) in [(9000, 8000, 8), (7000, 6000, 16)] { + let bytes = png(w, h, 6, depth, &[], &[]); + assert!(matches!(vectorcraft_trace::decode_alpha(&bytes), Err(vectorcraft_trace::TraceError::TooLarge { .. })), "{w}×{h}"); + let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1); + assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9)), "{w}×{h}"); + } + // A checkerboard of 2 px squares, whose outline would need more than 100,000 anchor points. + let checker = image::RgbaImage::from_fn(640, 640, |x, y| image::Rgba([0, 0, 0, if (x / 2 + y / 2) % 2 == 0 { 255 } else { 0 }])); + let (d, n) = + image_doc(encoded(image::DynamicImage::ImageRgba8(checker), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9))); +} + +#[test] +fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() { + let traces = || reshape::TRACES.with(std::cell::Cell::get); + let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1); + let NodeKind::Image(im) = &n.kind else { panic!("not an image") }; + let before = traces(); + let first = reshape::opaque_area(&[Some(&d)], im).unwrap(); + assert_eq!(traces(), before + 1); + for _ in 0..3 { + row_bounds(&d, &n); + } + assert_eq!(reshape::opaque_area(&[Some(&d)], im).unwrap(), first); + assert_eq!(traces(), before + 1); + let pixels = Arc::downgrade(&d.images.get(&im.key).unwrap().bytes); + assert!(reshape::keeps_outline(&pixels)); + // Once the document and its pixels are gone, the next trace drops their entry. + drop(d); + assert!(pixels.upgrade().is_none()); + let (other, _) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![], 1); + reshape::opaque_area(&[Some(&other)], im).unwrap(); + assert_eq!(traces(), before + 2); + assert!(!reshape::keeps_outline(&pixels)); +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 9f07d05e5a..4df9daad34 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -83,7 +83,7 @@ pub mod rasterfx; mod recolor; pub mod recovery; pub mod scripts; -mod select; +pub(crate) mod select; pub(crate) mod shaper; pub mod shortcutset; pub(crate) mod slices; @@ -779,7 +779,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/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 18d4e26704..16990fc2ea 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -397,7 +397,9 @@ pub(crate) fn commit_new_art_colors(s: &mut Session) -> Result<()> { Ok(()) } -fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> { +/// Record new-art paints `before` and the session's current ones with the step just made (or the +/// interaction or undo group in progress), so Undo puts `before` back and Redo the current ones. +pub(super) fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> { let after = s.paint.clone(); if before != after || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() { let st = s.doc_mut()?; @@ -422,7 +424,9 @@ fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaul Ok(()) } -fn new_art_colors_before(s: &Session) -> Result { +/// The new-art paints an undo step that starts now puts back: those at the start of the undo group +/// or interaction in progress, else the session's current ones. +pub(super) fn new_art_colors_before(s: &Session) -> Result { let st = s.doc()?; Ok(st.undo_group.as_ref().map(|g| &g.paint).or_else(|| st.interaction.as_ref().map(|it| &it.paint)).cloned().unwrap_or_else(|| s.paint.clone())) } 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 73f447a6f0..ca97a7a9ca 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -16,7 +16,7 @@ use vectorcraft_render::effects; use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at}; use super::expand::has_seeded; use super::rasterfx; -use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, fileio, has_doc, str_param, switch_or}; +use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, check_switches, cmd, fileio, has_doc, str_param, switch_or}; /// The name of the `svg.filter` effect drawing `xml`: its `` id. An effect names the /// document's filter of that name, so `xml` that differs from the document's filter of the same @@ -76,7 +76,7 @@ fn effect_specs() -> Vec { "Effect Options", [], None, - "{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool, item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection), savedBevel?: [[x, y]…] (as effect.apply)} → {ids}", + "{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection), savedBevel?: [[x, y]…] (as effect.apply)} → {ids}", has_doc, set_params ), @@ -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 ), @@ -653,15 +653,28 @@ pub(crate) fn set_params_effects(s: &Session, p: &Value) -> Vec { return vec![]; }; let Ok(targets) = effect_targets(s, p, item, index, C) else { return vec![] }; - // A 3D effect whose type `threeDType` changes takes the new effect's parameters. + // A 3D effect whose type `threeDType` changes, and a Warp whose style `warpStyle` changes, take + // the new effect's parameters. let kind = three_d_type(p, C).ok().flatten(); + let warp = p.get("warpStyle").and_then(Value::as_str).filter(|style| effects::WarpStyle::from_id(style).is_some()); let effect = |&(id, at, index): &(NodeId, Option, usize)| { let id = &st.doc.node(id)?.appearance.effects_at(at)?.get(index)?.id; - Some(kind.filter(|_| effects::is_three_d(id)).map_or_else(|| id.clone(), str::to_string)) + Some(edited_effect_id(id, kind, warp)) }; targets.iter().filter_map(effect).collect() } +/// The id effect `id` has once `effect.setParams` sets its 3D type to `kind` or its Warp style to +/// `warp` (each when given and when `id` is an effect of that family). +fn edited_effect_id(id: &str, kind: Option<&str>, warp: Option<&str>) -> String { + let is_warp = id.strip_prefix("warp.").and_then(effects::WarpStyle::from_id).is_some(); + match (kind, warp) { + (Some(to), _) if effects::is_three_d(id) => to.to_string(), + (_, Some(style)) if is_warp => format!("warp.{style}"), + _ => id.to_string(), + } +} + /// The effect `threeDType` in `p` turns a 3D effect into ([`effects::THREE_D_TYPES`]), when given. fn three_d_type(p: &Value, cmd: &str) -> Result> { let key = "threeDType"; @@ -722,6 +735,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result { Ok(format!("warp.{style}")) }) .transpose()?; + check_switches(p, &["visible"], C)?; let visible = p.get("visible").and_then(Value::as_bool); let item = item_target(s, p, C)?; let edited = set_params_effects(s, p); @@ -861,8 +875,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, &[]) } @@ -879,7 +894,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(), } } @@ -952,6 +967,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(); @@ -1107,6 +1154,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/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index 5584073563..8b5f90eb4a 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -626,6 +626,50 @@ fn warp_options_non_warp_target_rejection_is_atomic() { assert!(!state.is_dirty()); } +/// `effect.setParams` refuses a `visible` that is not true or false, when called and when a step +/// plays, and the effect, the document and the undo history stay as they were. `null` leaves the +/// visibility as it is. +#[test] +fn set_params_refuses_a_visible_that_is_not_true_or_false() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": null})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for visible in [json!(1), json!(0), json!("false"), json!([])] { + let p = json!({"index": 0, "item": null, "visible": visible, "params": {"size": 9}}); + for replay in [false, true] { + let r = if replay { s.replay("effect.setParams", &p) } else { s.execute("effect.setParams", &p) }; + let err = r.err().map(|e| e.to_string()).unwrap_or_default(); + assert!(err.contains("`visible` must be true or false"), "{visible} (replay {replay}): {err}"); + let state = s.doc().unwrap(); + assert_eq!(state.doc, before, "{visible} (replay {replay})"); + assert_eq!(state.history.undo.len(), undo, "{visible} (replay {replay})"); + assert!(!state.is_dirty()); + } + } + s.execute("effect.setParams", &json!({"index": 0, "item": null, "visible": null, "params": {"size": 9}})).unwrap(); + let n = node(&s, id); + assert!(n.appearance.effects[0].visible); + assert_eq!(n.appearance.effects[0].params["size"], 9); +} + +/// The effect `effect.setParams` checks the parameters against is the one it leaves: a Warp's new +/// style and a 3D effect's new type, and the effect as it is otherwise. +#[test] +fn set_params_checks_the_effect_it_leaves() { + use super::edited_effect_id; + assert_eq!(edited_effect_id("warp.arc", None, Some("flag")), "warp.flag"); + assert_eq!(edited_effect_id("warp.arc", None, None), "warp.arc"); + assert_eq!(edited_effect_id("distort.roughen", None, Some("flag")), "distort.roughen"); + assert_eq!(edited_effect_id("threeD.extrude", Some("threeD.revolve"), None), "threeD.revolve"); + assert_eq!(edited_effect_id("warp.arc", Some("threeD.revolve"), None), "warp.arc"); + let (mut s, _) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": "warp.arc", "item": null})).unwrap(); + let p = json!({"index": 0, "item": null, "warpStyle": "flag", "params": {"bend": 25}}); + assert_eq!(super::set_params_effects(&s, &p), ["warp.flag"]); +} + #[test] fn list_remove_and_set_params() { let (mut s, id) = session_with_rect(); 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.rs b/crates/engine/src/cmd/fileio.rs index b7ff1c7734..333db1c68f 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -13,10 +13,10 @@ //! per-format options (`file.formatOptions`); [`save_with`] is the one save path of every frontend. //! - `pdf`: PDF settings and presets for every PDF export, `document.exportPdf`. //! - `pdfimport`: the PDF pages, box and password `document.open` and Place read, `document.pdfInfo`. -//! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PICT). +//! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PageMaker). //! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`. //! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`. -//! - `metafile`: EMF and WMF export, open and place. +//! - `metafile`: EMF and WMF export, open and place; PICT open and place. //! - `hpgl`: HP-GL export options and plots. //! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no //! built-in format reads). @@ -217,6 +217,8 @@ mod tests_dxfimport; mod tests_hpgl; #[cfg(test)] mod tests_metafile; +#[cfg(test)] +mod tests_pict; #[cfg(test)] mod tests_pdfoutput; diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index fe7c9d8f3e..26272d873d 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "File Formats", [], None, - "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PICT, with what to use instead)}", + "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}", always, formats ), diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index 0fcaa4bfc0..8486cd2226 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -1,6 +1,6 @@ //! DXF export for every DXF path (`document.export {format: dxf}`, `document.exportDxf`, Export As //! → DXF Options): the options parsed from the params, one drawing per artboard with Use -//! Artboards, and the formats that can't be written (DWG, PICT) with what to use instead. +//! Artboards, and the formats that can't be written (DWG, PageMaker) with what to use instead. use std::sync::Arc; @@ -106,12 +106,6 @@ pub const UNSUPPORTED: &[Unsupported] = &[ extensions: &["dwg"], hint: "DWG is not available (no openly licensed writer exists): export DXF instead, which CAD apps open", }, - Unsupported { - id: "pict", - label: "PICT", - extensions: &["pict", "pct", "pic"], - hint: "PICT is a retired format and is not supported: convert the file to PDF or PNG first", - }, Unsupported { id: "pmd", label: "PageMaker", diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 3492fd6051..75b202c8ab 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -520,6 +520,8 @@ pub const FORMATS: &[Format] = &[ reader("heif", "HEIC/HEIF", &["heic", "heif"], "image/heic", true), // jxl-oxide reads a JPEG XL file's first frame, which is stored as PNG. Exports don't write it. reader("jxl", "JPEG XL", &["jxl"], "image/jxl", true), + // QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images. + reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false), ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). @@ -564,6 +566,9 @@ pub const OPEN_EXTS: &[&str] = &[ "dxf", "emf", "wmf", + "pct", + "pic", + "pict", "plt", "hpgl", "hgl", @@ -581,10 +586,10 @@ pub const OPEN_EXTS: &[&str] = &[ /// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF or JPEG XL type, nor one for the `.pns`, `.dib` and `.rle` names of /// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS /// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. -/// The packaging declares no type for HP-GL plot files either. +/// The packaging declares no type for HP-GL plot files or PICT pictures either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", "plt", "hpgl", "hgl", "hpg", + "heic", "heif", "jxl", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -658,6 +663,9 @@ pub const PLACE_EXTS: &[&str] = &[ "dxf", "emf", "wmf", + "pct", + "pic", + "pict", "plt", "hpgl", "hgl", 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/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 6f0f8fd533..e9f6ecf3d4 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -73,6 +73,8 @@ pub struct RasterImage { pub height: u32, /// The resolution the file declares (see [`super::ppi::resolution`]). pub ppi: Option<(f64, f64)>, + /// A DCS file's clipping path, in the image's pixel space ([`crate::cmd::place::dcs`]). + pub clip: Option, } pub(super) fn err(e: impl std::fmt::Display) -> EngineError { @@ -132,6 +134,12 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) { return Some(f); } + // A version 2 PICT is known by its version opcodes after the picture's frame, at byte 522 of a + // file or byte 10 of a bare picture (version 1 by its file's name), so a format whose + // signature starts the file is checked first. + if vectorcraft_metafile::is_pict(bytes) { + return format("pict"); + } if clipboard::looks_like_svg(&String::from_utf8_lossy(&bytes[..bytes.len().min(4096)])) { return format("svg"); } @@ -380,6 +388,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result let (mut doc, mut warnings, restored) = match format.id { // EPS, .ps and PostScript .ai: the document our EPS files carry, else the PostScript read. _ if matches!(format.id, "eps" | "ps") || vectorcraft_pdf::is_postscript(bytes) => { + // A DCS file's plates print from its file: it is only placed linked. + if crate::cmd::place::dcs::is_dcs(bytes) { + return Err(err(format!("can't open `{}`: {}", file_name(name), crate::cmd::place::dcs::LINK_ONLY))); + } let editing = vectorcraft_eps::has_native(bytes).then_some((true, || vectorcraft_eps::native(bytes))); restore_or_import(editing, || { let r = vectorcraft_eps::import_names(bytes, opts.editing_data, opts.trust_editing_data, opts.legacy_names) @@ -499,6 +511,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result let (doc, warnings) = super::metafile::import(bytes)?; (doc, warnings, false) } + "pict" => { + let (doc, warnings) = super::metafile::import_pict(bytes)?; + (doc, warnings, false) + } "hpgl" => { let i = vectorcraft_cad::hpgl::import(bytes).map_err(err)?; (i.document, i.warnings, false) @@ -1014,13 +1030,13 @@ fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: return Err(err("the image is empty")); } let blob = ImageBlob::new(mime, bytes); - Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi }) + Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None }) } /// An image as a document of its physical size at the resolution it declares (as Place sizes it; /// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file. pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { - let RasterImage { key, blob, width, height, ppi } = raster_image(bytes)?; + let RasterImage { key, blob, width, height, ppi, .. } = raster_image(bytes)?; let (sx, sy) = crate::cmd::place::pt_per_px(ppi); let mut d = Document::new(width as f64 * sx, height as f64 * sy); let layer = d.layers[0].id; diff --git a/crates/engine/src/cmd/fileio/metafile.rs b/crates/engine/src/cmd/fileio/metafile.rs index 6bc658a4a0..d987d82757 100644 --- a/crates/engine/src/cmd/fileio/metafile.rs +++ b/crates/engine/src/cmd/fileio/metafile.rs @@ -2,6 +2,7 @@ //! `document.export {format: emf|wmf}` and Export As (one picture of an artboard, or one per //! artboard with Use Artboards; raster effects as images, rendered at the document's raster //! effects resolution), `document.open` and File → Place (one artboard, the picture's frame). +//! QuickDraw pictures (PICT) open and place the same way; they are never written. use serde_json::Value; use vectorcraft_doc::Document; @@ -52,3 +53,9 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec)> { let i = vectorcraft_metafile::import(bytes).map_err(super::err)?; Ok((i.document, i.warnings)) } + +/// A QuickDraw picture's document and the import's warnings. +pub(super) fn import_pict(bytes: &[u8]) -> Result<(Document, Vec)> { + let p = vectorcraft_metafile::import_pict(bytes).map_err(super::err)?; + Ok((p.document, p.warnings)) +} diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 03273d9450..1a3368b56f 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -1,5 +1,5 @@ //! DXF export through the commands: options, artboards, selection, images, and the formats that -//! can't be written (DWG, PICT). +//! can't be written (DWG, PageMaker). use serde_json::{Value, json}; @@ -275,23 +275,24 @@ fn formats_list_dxf_and_what_can_not_be_written() { } assert!(r["writable"].as_array().unwrap().contains(&json!("dxf"))); let unsupported: Vec<&str> = r["unsupported"].as_array().unwrap().iter().map(|u| u["id"].as_str().unwrap()).collect(); - assert_eq!(unsupported, ["dwg", "pict", "pmd"]); + assert_eq!(unsupported, ["dwg", "pmd"]); } #[test] -fn dwg_and_pict_say_what_to_use_instead() { +fn dwg_and_pagemaker_say_what_to_use_instead() { let mut s = two_boards(); for p in [json!({"format": "dwg"}), json!({"path": "/tmp/plan.DWG"})] { let e = s.execute("document.export", &p).unwrap_err().to_string(); assert!(e.contains("DWG is not available") && e.contains("DXF"), "{p}: {e}"); } + // PICT opens; it isn't written. let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string(); - assert!(e.contains("PICT is a retired format"), "{e}"); + assert!(e.contains("PICT files can be opened but not written"), "{e}"); let e = s .execute("document.open", &json!({"name": "old.pct", "dataBase64": vectorcraft_format::base64_encode(&[0u8; 600])})) .unwrap_err() .to_string(); - assert!(e.contains("old.pct") && e.contains("PICT"), "{e}"); + assert!(e.contains("not a PICT file"), "{e}"); let e = s .execute("document.open", &json!({"name": "site.dwg", "dataBase64": vectorcraft_format::base64_encode(b"AC1032\0\0")})) .unwrap_err() diff --git a/crates/engine/src/cmd/fileio/tests_pict.rs b/crates/engine/src/cmd/fileio/tests_pict.rs new file mode 100644 index 0000000000..513adffbef --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_pict.rs @@ -0,0 +1,104 @@ +//! PICT pictures through the commands: `document.open` by extension or by content, File › Place as +//! one group clipped to the picture's frame, the dialogs' filters and the format list, and files +//! that aren't pictures, or a PICT export, refused with a message. + +use serde_json::json; +use vectorcraft_doc::NodeKind; + +use super::*; + +fn b64(bytes: &[u8]) -> String { + vectorcraft_format::base64_encode(bytes) +} + +/// A version 2 PICT file of a 200 × 100 pt frame: a red rectangle and a line. +fn picture() -> Vec { + let words = |v: &[i16]| v.iter().flat_map(|x| x.to_be_bytes()).collect::>(); + let mut b = vec![0; 512]; + b.extend(words(&[0, 0, 0, 100, 200])); + b.extend([0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]); + b.extend(words(&[-1, 0])); + b.extend([0; 20]); + b.extend(words(&[0x1A, -1, 0, 0, 0x31, 10, 20, 50, 80, 0x20, 70, 10, 70, 190, 0xFF])); + b +} + +#[test] +fn document_open_reads_a_picture() { + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"name": "logo.pct", "dataBase64": b64(&picture())})).unwrap(); + assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("pict"), Some("logo.pct")), "{r}"); + assert_eq!(r["warnings"], json!([])); + let st = s.doc().unwrap(); + assert_eq!(st.doc.artboards[0].rect.size(), (200.0, 100.0).into()); + let mut paths = vec![]; + st.doc.walk(|n| { + if let NodeKind::Path { .. } = n.kind { + paths.push(n.clone()); + } + }); + assert_eq!(paths.len(), 2); + let b = paths[0].geometric_bounds().unwrap(); + assert!((b.x0 - 20.0).abs() < 1e-9 && (b.width() - 60.0).abs() < 1e-9, "{b:?}"); + // Opened as artwork: Save asks for a name. + assert!(st.path.is_none()); + + // A picture opens by its content under a name no format reads, and in each of its names. + for name in ["logo.PICT", "logo.pic", "logo.bin", "logo"] { + let r = Session::new().execute("document.open", &json!({"name": name, "dataBase64": b64(&picture())})).unwrap(); + assert_eq!(r["format"].as_str(), Some("pict"), "{name}: {r}"); + } + assert_eq!(detect("logo.dat", &picture()).map(|f| f.id), Some("pict")); + assert_eq!(detect("bare.dat", &picture()[512..]).map(|f| f.id), Some("pict")); +} + +#[test] +fn file_place_places_a_picture_as_one_clipped_group() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let p = json!({"name": "logo.pct", "dataBase64": b64(&picture()), "at": [150, 150]}); + let info = s.execute("file.place.info", &p).unwrap(); + assert_eq!(info["format"], "pict", "{info}"); + assert!((info["width"].as_f64().unwrap() - 200.0).abs() < 1e-9, "{info}"); + let r = s.execute("file.place", &p).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("pict"), Some(1)), "{r}"); + let doc = &s.doc().unwrap().doc; + let group = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + assert_eq!(group.name.as_deref(), Some("logo.pct")); + let NodeKind::Group { clip: true, .. } = &group.kind else { panic!("a clipping group, got {:?}", group.kind) }; + let b = group.geometric_bounds().unwrap(); + assert!((b.width() - 200.0).abs() < 1e-6 && (b.height() - 100.0).abs() < 1e-6, "{b:?}"); +} + +#[test] +fn files_that_are_not_pictures_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let e = s.execute("document.open", &json!({"name": "old.pct", "dataBase64": b64(&[0; 600])})).expect_err("refused"); + assert!(e.to_string().contains("not a PICT file"), "{e}"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), (100.0, 50.0).into()); + assert!(s.execute("file.place", &json!({"name": "old.pct", "dataBase64": b64(&[0; 600])})).is_err()); + // Other formats' files aren't taken for pictures by their content. + // A file that starts with a PNG signature and holds a picture's version opcodes at byte 522. + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + png.extend(&picture()[8..]); + assert!(detect("x.png", &png).is_none_or(|f| f.id != "pict")); + let e = s.execute("document.export", &json!({"format": "pict"})).expect_err("refused").to_string(); + assert!(e.contains("PICT files can be opened but not written"), "{e}"); +} + +#[test] +fn the_dialogs_and_the_format_list_name_pict() { + let exts = ["pct", "pic", "pict"]; + for e in exts { + assert!(OPEN_EXTS.contains(&e) && PLACE_EXTS.contains(&e) && UNASSOCIATED_EXTS.contains(&e), "{e}"); + assert_eq!(format_for_name(&format!("a.{e}")).map(|f| f.id), Some("pict"), "{e}"); + } + let filter = ("PICT", &exts[..]); + assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter)); + let r = Session::new().execute("document.formats", &json!({})).unwrap(); + let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pict").unwrap().clone(); + assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)), "{f}"); + assert_eq!(f["mime"], "image/x-pict"); + assert!(writable_format(None, Some("x/logo.pct")).is_err()); +} 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/fonts.rs b/crates/engine/src/cmd/fonts.rs index 74cece5af3..005427ded8 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Select Text by Font", [], None, - "{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the objects painted with a pattern whose art uses it and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}", + "{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}", has_doc, select_font ), @@ -108,23 +108,85 @@ fn pattern_being_edited(d: &Document, name: &str) -> bool { d.pattern_edit.as_ref().is_some_and(|e| e.pattern == name) } +/// Whether fill or stroke `i` paints: it is visible, its opacity is above 0 and, a stroke, it is +/// wider than 0. +fn paints(i: &AppearanceItem) -> bool { + i.visible() && i.opacity() > 0.0 && !matches!(i, AppearanceItem::Stroke(s) if s.width <= 0.0) +} + +/// The name of pattern paint `p`. +fn pattern_name(p: &Paint) -> Option<&str> { + match p { + Paint::Pattern { pattern, .. } => Some(pattern.as_str()), + _ => None, + } +} + +/// Whether `r` is laid out as an inline graphic: it has one and holds only its character. +fn draws_inline(r: &TextRun) -> bool { + r.inline.is_some() && vectorcraft_text::edit::is_inline_text(&r.text) +} + +/// The fill and, when it is wider than 0, the stroke of the characters of `r`. +fn run_paints(r: &TextRun) -> impl Iterator { + [Some(&r.style.fill), (r.style.stroke_width > 0.0).then_some(&r.style.stroke)].into_iter().flatten() +} + +/// [`run_paints`] of run `r` of `t` when its characters draw with them. The characters of an +/// inline graphic draw no glyph: their fill and stroke paint only their underline and +/// strikethrough (not on a path or in vertical type, see `vectorcraft_text::decorations`) and the +/// ruby readings that layout draws with their run (`ruby`, as [`ruby_runs`] finds them). +fn drawn_run_paints<'a>(t: &TextObject, ruby: &HashSet<*const TextRun>, r: &'a TextRun) -> impl Iterator { + let drawn = !draws_inline(r) || inline_decorated(t, ruby, r); + run_paints(r).filter(move |_| drawn) +} + +/// The inline graphic runs of `t` that layout draws a ruby reading with. A reading takes the run +/// of the first base character on its line, and type on a path has no ruby. `t` is laid out only +/// when it has ruby and an inline graphic painted with a pattern. +fn ruby_runs(t: &TextObject) -> HashSet<*const TextRun> { + let patterned = |r: &TextRun| draws_inline(r) && run_paints(r).any(|p| pattern_name(p).is_some()); + if t.ruby.is_empty() || !t.runs.iter().any(patterned) { + return HashSet::new(); + } + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.ruby.iter().filter_map(|g| t.runs.get(g.run)).filter(|r| draws_inline(r)).map(std::ptr::from_ref).collect() +} + +/// Whether inline graphic run `r` of `t` has an underline or strikethrough that draws, or a ruby +/// reading that layout draws with it (it is in `ruby`). +fn inline_decorated(t: &TextObject, ruby: &HashSet<*const TextRun>, r: &TextRun) -> bool { + let bars = !t.vertical && !matches!(t.kind, TextKind::OnPath { .. }); + if bars && (r.style.underline || r.style.strikethrough) { + return true; + } + ruby.contains(&std::ptr::from_ref(r)) +} + /// The patterns that the fills and strokes `n` draws name (of a text object, also those of its -/// characters): visible ones, and strokes wider than 0. -fn paint_patterns(n: &Node) -> impl Iterator { - let runs = match &n.kind { - NodeKind::Text(t) => t.runs.as_slice(), - _ => &[], - }; - n.appearance - .items - .iter() - .filter(|i| i.visible() && !matches!(i, AppearanceItem::Stroke(s) if s.width <= 0.0)) - .map(AppearanceItem::paint) - .chain(runs.iter().flat_map(|r| [Some(&r.style.fill), (r.style.stroke_width > 0.0).then_some(&r.style.stroke)]).flatten()) - .filter_map(|p| match p { - Paint::Pattern { pattern, .. } => Some(pattern.as_str()), - _ => None, - }) +/// characters): those that [`paints`] holds for, and the character paints of the runs that draw +/// (as [`drawn_runs`] finds them: not the overset runs of area type or type on a path) where they +/// draw (as [`drawn_run_paints`] says). +fn paint_patterns(n: &Node) -> Vec<&str> { + let mut out: Vec<&str> = n.appearance.items.iter().filter(|i| paints(i)).filter_map(|i| pattern_name(i.paint())).collect(); + if let NodeKind::Text(t) = &n.kind + && t.runs.iter().flat_map(run_paints).any(|p| pattern_name(p).is_some()) + { + let ruby = ruby_runs(t); + out.extend(drawn_runs(t).0.into_iter().flat_map(|r| drawn_run_paints(t, &ruby, r)).filter_map(pattern_name)); + } + out +} + +/// The symbols that the inline graphics in the type of `n` draw (as [`drawn_runs`] finds them: not +/// those in the overset runs of area type or type on a path). +fn inline_symbols(n: &Node) -> Vec<&str> { + match &n.kind { + NodeKind::Text(t) if t.runs.iter().any(draws_inline) => { + drawn_runs(t).0.into_iter().filter(|r| draws_inline(r)).filter_map(|r| r.inline.as_ref().map(|art| art.symbol.as_str())).collect() + } + _ => vec![], + } } /// Symbols and patterns, by name: those whose art is in scope. @@ -135,13 +197,15 @@ struct Resources { } impl Resources { - /// Adds what `n` itself shows: the symbol of an instance, the patterns its paints name, and - /// what the art of its opacity mask shows (not hidden or locked objects of that art). + /// Adds what `n` itself shows: the symbol of an instance, the symbols of the inline graphics in + /// its type, the patterns its paints name, and what the art of its opacity mask shows (not + /// hidden or locked objects of that art). fn add_own(&mut self, n: &Node) { if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { self.symbols.insert(symbol.clone()); } - self.patterns.extend(paint_patterns(n).map(str::to_string)); + self.symbols.extend(inline_symbols(n).into_iter().map(str::to_string)); + self.patterns.extend(paint_patterns(n).into_iter().map(str::to_string)); if let Some(m) = n.extras().mask.as_deref() { self.add(&m.art); } @@ -486,17 +550,16 @@ impl Printed<'_> { NodeKind::Text(t) => drawn_runs(t), _ => (vec![], false), }; - let items: Vec<&AppearanceItem> = - n.appearance.items.iter().filter(|i| i.visible() && !matches!(i, AppearanceItem::Stroke(s) if s.width <= 0.0)).collect(); - let patterns: Vec<&str> = items - .iter() - .map(|i| i.paint()) - .chain(runs.iter().flat_map(|r| [Some(&r.style.fill), (r.style.stroke_width > 0.0).then_some(&r.style.stroke)]).flatten()) - .filter_map(|p| match p { - Paint::Pattern { pattern, .. } => Some(pattern.as_str()), - _ => None, - }) - .collect(); + let items: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| paints(i)).collect(); + let ruby = match &n.kind { + NodeKind::Text(t) => ruby_runs(t), + _ => HashSet::new(), + }; + let run_patterns = runs.iter().flat_map(|r| match &n.kind { + NodeKind::Text(t) => Some(drawn_run_paints(t, &ruby, r)), + _ => None, + }); + let patterns: Vec<&str> = items.iter().map(|i| i.paint()).chain(run_patterns.flatten()).filter_map(pattern_name).collect(); let brushed = vectorcraft_brush::has_brush(n); if (mask.is_some() || !patterns.is_empty() || brushed) && areas.is_none_or(|a| !open || self.meets(n, a)) { if let Some(m) = mask { @@ -527,7 +590,7 @@ impl Printed<'_> { for r in runs { self.fonts.extend(run_fonts(r)); // Inline graphics draw their symbols' art. - if let Some(art) = &r.inline { + if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) { self.symbol(&art.symbol); } } @@ -910,14 +973,16 @@ fn replace(s: &mut Session, p: &Value) -> Result { } /// Whether `n` or a descendant that is not hidden or locked, nor in a hidden or locked group, -/// shows type in a font `uses` matches: text set in it, an instance of a symbol in `found`, a paint -/// naming a pattern in `found`, or such type in the art of its opacity mask. +/// shows type in a font `uses` matches: text set in it, an instance of a symbol in `found`, an +/// inline graphic of a symbol in `found`, a paint naming a pattern in `found`, or such type in the +/// art of its opacity mask. fn reaches(n: &Node, uses: &impl Fn(&TextObject) -> bool, found: &Resources) -> bool { n.visible && !n.locked && (matches!(&n.kind, NodeKind::Text(t) if uses(t)) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol)) - || paint_patterns(n).any(|p| found.patterns.contains(p)) + || inline_symbols(n).into_iter().any(|sym| found.symbols.contains(sym)) + || paint_patterns(n).into_iter().any(|p| found.patterns.contains(p)) || n.extras().mask.as_deref().is_some_and(|m| reaches(&m.art, uses, found)) || n.children().is_some_and(|ch| ch.iter().any(|c| reaches(c, uses, found)))) } @@ -964,14 +1029,16 @@ fn select_font(s: &mut Session, p: &Value) -> Result { found.patterns.extend(patterns); } // The objects the Selection tool can reach that show such type: the instances of those - // symbols, the objects that those patterns paint, and the objects whose opacity mask holds it - // (not layers, which the Selection tool doesn't select). + // symbols, the text whose inline graphics draw them, the objects that those patterns paint, + // and the objects whose opacity mask holds it (not layers, which the Selection tool doesn't + // select). let masked: HashSet = masked.into_iter().collect(); if !found.symbols.is_empty() || !found.patterns.is_empty() || !masked.is_empty() { let texts: HashSet = hits.iter().copied().collect(); d.walk(&mut |n: &Node| { let shows = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol)) - || paint_patterns(n).any(|p| found.patterns.contains(p)) + || inline_symbols(n).into_iter().any(|sym| found.symbols.contains(sym)) + || paint_patterns(n).into_iter().any(|p| found.patterns.contains(p)) || (masked.contains(&n.id) && n.extras().mask.as_deref().is_some_and(|m| reaches(&m.art, &uses, &found))); if shows && !n.is_layer() && !texts.contains(&n.id) && editable(n.id) { hits.push(n.id); @@ -1069,6 +1136,37 @@ fn font_list(_: &mut Session, p: &Value) -> Result { } } +/// Gives the inline graphics in the type of [`art_texts_of`] the current bounds of their symbols' +/// art, and lays out again the type whose inline graphics changed. A symbol drawn inline in the +/// art of another symbol takes one more round, so there is at most one round per symbol. +fn resolve_art_inline(doc: &mut Document) { + for _ in 0..=doc.symbols.len() { + let names: BTreeSet = + art_texts_of(doc).iter().flat_map(|(_, t, _)| t.runs.iter().filter_map(|r| r.inline.as_ref().map(|a| a.symbol.clone()))).collect(); + let bounds: BTreeMap> = names + .into_iter() + .map(|name| { + let b = doc.symbol_art_bounds(&name); + (name, b) + }) + .collect(); + let stale = |t: &TextObject| t.runs.iter().any(|r| r.inline.as_ref().is_some_and(|a| bounds.get(&a.symbol).is_some_and(|b| *b != a.bounds))); + let mut changed = false; + edit_art_texts_of(doc, &stale, &mut |t| { + for a in t.runs.iter_mut().filter_map(|r| r.inline.as_mut()) { + if let Some(b) = bounds.get(&a.symbol) { + a.bounds = *b; + } + } + refresh_bounds(t); + changed = true; + }); + if !changed { + break; + } + } +} + pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result { let db = vectorcraft_text::FontDb::global(); #[cfg(not(target_arch = "wasm32"))] @@ -1076,7 +1174,9 @@ pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result { #[cfg(target_arch = "wasm32")] let faces = 0; // The canvas redraws type in the fonts available now (renderers lay it out again when the - // fonts change), and the bounds follow; that isn't an edit to save. + // fonts change), and the bounds follow, also of the type in opacity masks and in the art of + // symbols and patterns; that isn't an edit to save. The type in art is laid out first, and the + // inline graphics of the type on the layers then take the new bounds of their symbols' art. for d in &mut s.docs { let mut texts = vec![]; d.doc.walk(|n| { @@ -1084,9 +1184,12 @@ pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result { texts.push(n.id); } }); - if !texts.is_empty() { + if !texts.is_empty() || !art_texts_of(&d.doc).is_empty() { d.change_unsaved(|doc| { let doc = std::sync::Arc::make_mut(doc); + edit_art_texts_of(doc, &|_| true, &mut refresh_bounds); + resolve_art_inline(doc); + doc.resolve_inline_art(); for id in texts { if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { refresh_bounds(t); @@ -1751,6 +1854,309 @@ mod tests { assert_eq!(symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family, "Source Sans 3"); } + /// A pattern in a fill whose opacity is 0 paints nothing: Find doesn't select the object for + /// the pattern's type, a selection-only Change leaves that type in its font, and Print doesn't + /// count its font. + #[test] + fn find_font_skips_patterns_at_an_opacity_of_0() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [t], "name": "Dots", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let painted = s.execute("shape.rectangle", &json!({"x": 0, "y": 20, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Dots", "ids": [painted]})).unwrap(); + let printed = |s: &Session| { + let d = &s.doc().unwrap().doc; + printed_type(d, &d.layers, &[Rect::new(-1000.0, -1000.0, 1000.0, 1000.0)]).0.into_iter().map(|(family, ..)| family).collect::>() + }; + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1); + assert_eq!(printed(&s), ["Source Serif 4"]); + s.edit("Clear the fill", |d, _| { + for it in d.node_mut(NodeId(painted)).unwrap().appearance.items.iter_mut() { + if let AppearanceItem::Fill(f) = it { + f.opacity = 0.0; + } + } + Ok(()) + }) + .unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0); + assert!(printed(&s).is_empty(), "{:?}", printed(&s)); + s.execute("select.set", &json!({"ids": [painted]})).unwrap(); + let r = s + .execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})) + .unwrap(); + assert_eq!(r, json!({"runs": 0})); + assert_eq!(pattern_families(&s, "Dots"), ["Source Serif 4"]); + } + + /// Characters of area type that don't fit its frame paint nothing: their pattern's type isn't + /// found through them until they are drawn. + #[test] + fn find_font_skips_patterns_of_overset_characters() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [t], "name": "Dots", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let area = s + .execute( + "text.create", + &json!({"x": 10, "y": 60, "text": "A\nB", "font": "Source Sans 3", "size": 20, "area": {"width": 100, "height": 40}}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": area, "start": 2, "end": 3, "font": "Inter"})).unwrap(); + let paint_run = |s: &mut Session, letter: &'static str| { + s.edit("Paint a run with the pattern", |d, _| { + if let Some(NodeKind::Text(t)) = d.node_mut(NodeId(area)).map(|n| &mut n.kind) { + for r in t.runs.iter_mut().filter(|r| r.text.contains(letter)) { + r.style.fill = Paint::Pattern { pattern: "Dots".into(), xf: Default::default() }; + } + } + Ok(()) + }) + .unwrap(); + }; + paint_run(&mut s, "B"); + let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), text(&s.doc().unwrap().doc, NodeId(area)).unwrap()); + assert!(laid.overflow, "the second line doesn't fit the frame"); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0); + paint_run(&mut s, "A"); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1); + } + + /// An inline graphic that doesn't fit its area type draws nothing, and neither does an inline + /// graphic named on a run of other characters: Find doesn't select the text for its symbol. + #[test] + fn find_font_skips_undrawn_inline_graphics() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [t], "name": "Dots", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let mark = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Se", "font": "Inter"})).unwrap()["id"].clone(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [mark]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let area = s + .execute( + "text.create", + &json!({"x": 10, "y": 60, "text": "A\nB", "font": "Source Sans 3", "size": 20, "area": {"width": 100, "height": 40}}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.insertInline", &json!({"id": area, "at": 3, "symbol": "Mark"})).unwrap(); + let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), text(&s.doc().unwrap().doc, NodeId(area)).unwrap()); + assert!(laid.overflow && laid.inlines.is_empty(), "the inline graphic doesn't fit the frame"); + assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 0); + let point = s.execute("text.create", &json!({"x": 10, "y": 140, "text": "Hi", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.insertInline", &json!({"id": point, "at": 0, "symbol": "Mark"})).unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(point)]); + // A run that names an inline graphic but holds other characters is laid out as those + // characters: its fill paints them, and it draws no symbol. + let plain = s.execute("text.create", &json!({"x": 10, "y": 180, "text": "Ok", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + let art = text(&s.doc().unwrap().doc, NodeId(point)).unwrap().runs.iter().find_map(|r| r.inline.clone()).unwrap(); + s.edit("Name an inline graphic on plain characters", |d, _| { + if let Some(NodeKind::Text(t)) = d.node_mut(NodeId(plain)).map(|n| &mut n.kind) { + for r in &mut t.runs { + r.inline = Some(art.clone()); + r.style.fill = Paint::Pattern { pattern: "Dots".into(), xf: Default::default() }; + } + } + Ok(()) + }) + .unwrap(); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(plain)]); + assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(point)]); + } + + /// The characters of an inline graphic draw no glyph: their pattern fill paints only their + /// underline, strikethrough or ruby reading. Without one, Find doesn't select the text for the + /// pattern's type and Print doesn't count its font. + #[test] + fn find_font_skips_patterns_of_undecorated_inline_graphics() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [t], "name": "Dots", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let mark = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [mark]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let point = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Hi", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.insertInline", &json!({"id": point, "at": 1, "symbol": "Mark"})).unwrap(); + let style = |s: &mut Session, f: &dyn Fn(&mut TextObject)| { + s.edit("Style the inline graphic", |d, _| { + if let Some(NodeKind::Text(t)) = d.node_mut(NodeId(point)).map(|n| &mut n.kind) { + f(t); + } + Ok(()) + }) + .unwrap(); + }; + let found = |s: &mut Session| s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"].as_u64(); + let printed = |s: &Session| { + let d = &s.doc().unwrap().doc; + printed_type(d, &d.layers, &[Rect::new(-1000.0, -1000.0, 1000.0, 1000.0)]).0.into_iter().map(|(family, ..)| family).collect::>() + }; + style(&mut s, &|t| { + for r in t.runs.iter_mut().filter(|r| r.inline.is_some()) { + r.style.fill = Paint::Pattern { pattern: "Dots".into(), xf: Default::default() }; + } + }); + assert_eq!(found(&mut s), Some(0)); + assert_eq!(printed(&s), ["Source Sans 3"]); + // An underline paints with the pattern. + style(&mut s, &|t| t.runs.iter_mut().filter(|r| r.inline.is_some()).for_each(|r| r.style.underline = true)); + assert_eq!(found(&mut s), Some(1)); + assert_eq!(printed(&s), ["Source Sans 3", "Source Serif 4"]); + // Vertical type draws no underline. + style(&mut s, &|t| t.vertical = true); + assert_eq!(found(&mut s), Some(0)); + // A ruby reading that starts over the character before the inline graphic draws with that + // character's paint. + style(&mut s, &|t| { + assert!(t.runs[1].inline.is_some(), "the inline graphic is the second run"); + t.ruby.push(vectorcraft_doc::RubySpan { + start: 0, + end: t.runs[0].text.len() + t.runs[1].text.len(), + text: "x".into(), + position: Default::default(), + align: Default::default(), + size_percent: 50.0, + overhang: true, + }); + }); + assert_eq!(found(&mut s), Some(0)); + // A ruby reading that starts over the inline graphic paints with the pattern. + style(&mut s, &|t| t.ruby[0].start = t.runs[0].text.len()); + assert_eq!(found(&mut s), Some(1)); + } + + /// Text whose inline graphic draws a symbol shows the symbol's type: Find selects that text + /// and the objects painted with a pattern whose art holds it, and a selection-only Change + /// changes the symbol's type. + #[test] + fn find_font_reaches_symbols_through_inline_graphics() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let serif = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Se", "font": "Source Serif 4"})).unwrap()["id"].clone(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [serif]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let inline = |s: &mut Session, y: i32| { + let id = s.execute("text.create", &json!({"x": 10, "y": y, "text": "In", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.insertInline", &json!({"id": id, "at": 0, "symbol": "Mark"})).unwrap(); + id + }; + let listed = inline(&mut s, 60); + let tiled = inline(&mut s, 100); + s.execute("object.pattern.make", &json!({"ids": [tiled], "name": "Loop", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [tiled]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let painted = s.execute("shape.rectangle", &json!({"x": 0, "y": 140, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [painted]})).unwrap(); + let mut instances = 0; + s.doc().unwrap().doc.walk(|n| instances += usize::from(matches!(n.kind, NodeKind::SymbolInstance { .. }))); + assert_eq!(instances, 0, "the symbol is drawn only by inline graphics"); + assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 2); + let mut selected = s.doc().unwrap().selection.objects.clone(); + selected.sort(); + assert_eq!(selected, [NodeId(listed), NodeId(painted)]); + s.execute("select.set", &json!({"ids": [painted]})).unwrap(); + let rows = font_rows(&mut s, json!({"selectionOnly": true})); + assert_eq!(rows, [("Inter".to_string(), 2, 1), ("Source Serif 4".to_string(), 1, 1)]); + let r = s + .execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})) + .unwrap(); + assert_eq!(r, json!({"runs": 1})); + assert_eq!(symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family, "Source Sans 3"); + } + + /// Refresh Font List lays out again the type in opacity masks and in the art of symbols and + /// patterns, as it does the type on the layers, and the inline graphics of the type on the + /// layers follow the symbols' type as laid out again. + #[test] + fn rescanning_fonts_refreshes_the_bounds_of_type_in_art() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let owner = s.execute("shape.rectangle", &json!({"x": 0, "y": 20, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let masked = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Mask", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + mask_with(&mut s, owner, masked); + let tiled = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Tile", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.pattern.make", &json!({"ids": [tiled], "name": "Dots", "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [tiled]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let stale = Rect::new(0.0, 0.0, 1.0, 1.0); + s.edit("Make the bounds stale", |d, _| { + edit_art_texts_of(d, &|_| true, &mut |t| t.cached_bounds = Some(stale)); + Ok(()) + }) + .unwrap(); + let bounds = |s: &Session| art_texts_of(&s.doc().unwrap().doc).iter().map(|(_, t, _)| t.cached_bounds).collect::>(); + assert_eq!(bounds(&s), [Some(stale), Some(stale)]); + s.execute("text.rescanFonts", &json!({})).unwrap(); + let after = bounds(&s); + assert_eq!(after.len(), 2); + assert!(after.iter().all(|b| b.is_some_and(|b| b != stale && b.width() > 1.0)), "{after:?}"); + let marked = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Se", "font": "Inter"})).unwrap()["id"].clone(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [marked]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let line = s.execute("text.create", &json!({"x": 10, "y": 140, "text": "In", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.insertInline", &json!({"id": line, "at": 0, "symbol": "Mark"})).unwrap(); + s.edit("Make the bounds stale", |d, _| { + edit_art_texts_of(d, &|_| true, &mut |t| t.cached_bounds = Some(stale)); + d.resolve_inline_art(); + Ok(()) + }) + .unwrap(); + let resolved = |s: &Session| { + let d = &s.doc().unwrap().doc; + matches!(d.inline_resolved(text(d, NodeId(line)).unwrap()), std::borrow::Cow::Borrowed(_)) + }; + assert!(resolved(&s), "the inline graphic took the stale bounds"); + s.execute("text.rescanFonts", &json!({})).unwrap(); + assert!(resolved(&s), "the inline graphic follows the symbol's type laid out again"); + // So does an inline graphic in the art of another symbol. + let held = s.execute("text.create", &json!({"x": 10, "y": 180, "text": "Out", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.insertInline", &json!({"id": held, "at": 0, "symbol": "Mark"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Outer", "ids": [held]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.edit("Make the bounds stale", |d, _| { + edit_art_texts_of(d, &|_| true, &mut |t| t.cached_bounds = Some(stale)); + Ok(()) + }) + .unwrap(); + let shrunk = s.doc().unwrap().doc.symbol_art_bounds("Mark"); + s.edit("Take the stale bounds", |d, _| { + edit_art_texts_of(d, &|_| true, &mut |t| { + for a in t.runs.iter_mut().filter_map(|r| r.inline.as_mut()) { + a.bounds = shrunk; + } + }); + Ok(()) + }) + .unwrap(); + let nested = |s: &Session| { + let d = &s.doc().unwrap().doc; + art_texts_of(d).iter().flat_map(|(_, t, _)| t.runs.iter().filter_map(|r| r.inline.as_ref().map(|a| a.bounds))).collect::>() + }; + assert_eq!(nested(&s), [shrunk]); + s.execute("text.rescanFonts", &json!({})).unwrap(); + let mark = s.doc().unwrap().doc.symbol_art_bounds("Mark"); + assert_ne!(mark, shrunk); + assert_eq!(nested(&s), [mark], "the inline graphic in the art of Outer follows Mark's type laid out again"); + } + /// The font family of text object `id`'s first run. fn text_family(s: &Session, id: u64) -> String { text(&s.doc().unwrap().doc, NodeId(id)).unwrap().runs[0].style.font_family.clone() diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index ab6dd3e56a..720a906462 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -31,10 +31,10 @@ use vectorcraft_doc::links::{Align, Preserve, hash_bytes}; use vectorcraft_doc::{ Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions, }; -use vectorcraft_geom::{Affine, PathData, Rect, shapes}; +use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file}; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param}; +use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or}; pub fn specs() -> Vec { vec![ @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "Update Links", [], None, - "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. The images and placed documents inside symbols, graph designs, patterns and opacity masks that show the same content are read again too (by default also those only that art shows); they have no ids to list. One undo step → {updated: [ids], missing: [ids]}", + "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. The images and placed documents inside symbols, graph designs, patterns and opacity masks that show the same content are read again too (by default also those only that art shows); they have no ids to list. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}", has_doc, update ), @@ -70,7 +70,7 @@ pub fn specs() -> Vec { "Relink", [], None, - "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object in the layers linked to the same file as one of them) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots)}", + "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object in the layers linked to the same file as one of them) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}", has_doc, relink ), @@ -79,7 +79,7 @@ pub fn specs() -> Vec { "Links", [], None, - "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots", + "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots", has_doc, list ), @@ -97,7 +97,7 @@ pub fn specs() -> Vec { "Embed Image", [], None, - "{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. One undo step → {embedded: [ids], missing: [ids]}", + "{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. An image placed from a DCS file can't be embedded (an error, and nothing changes). One undo step → {embedded: [ids], missing: [ids]}", has_doc, embed ), @@ -160,6 +160,8 @@ struct Group { ids: Vec, /// Placed documents: what they show. document: Option, + /// An image placed from a DCS file: the plate files of their own its plates were read from. + plate_files: Vec, } /// What a placed document shows: whether the art's bounds (not the artboard or page) are shown, @@ -175,9 +177,17 @@ fn linked(n: &Node) -> Option<(&LinkInfo, &str, Option)> { } } -/// Every linked file of `d` with the ids of the objects showing it (for [`crate::link_watch`]). +/// Every linked file of `d` with the ids of the objects showing it (for [`crate::link_watch`]): an +/// image placed from a DCS file has its plate files of their own too, beside its file. pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { - groups(d, None).into_iter().filter(|g| !g.ids.is_empty()).map(|g| (g.link.path, ids_json(&g.ids))).collect() + let mut out = vec![]; + for g in groups(d, None).into_iter().filter(|g| !g.ids.is_empty()) { + let ids = ids_json(&g.ids); + let plates: Vec = g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&g.link.path, &f.name)).collect(); + out.push((g.link.path, ids.clone())); + out.extend(plates.into_iter().map(|p| (p, ids.clone()))); + } + out } /// The linked images and placed documents of `d` by file and content: those in the layers (only `ids` when @@ -189,7 +199,11 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec { let wanted: Option> = ids.map(|ids| ids.iter().copied().collect()); let mut add = |link: &LinkInfo, key: &str, document: Option, id: Option| { let i = *index.entry((link.path.clone(), key.to_string(), document.is_some())).or_insert_with(|| { - out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document }); + let plate_files = match document { + None => d.images.get(key).map(ImageBlob::plate_files).unwrap_or_default(), + Some(_) => vec![], + }; + out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document, plate_files }); out.len() - 1 }); if let (Some(id), Some(g)) = (id, out.get_mut(i)) { @@ -335,10 +349,14 @@ fn refused(link: &LinkInfo, doc_path: Option<&str>) -> Option (Status, Option) { let Some(mut f) = locate(&g.link, base) else { return (Status::Missing, None) }; let l = &g.link; + if !g.plate_files.is_empty() && super::place::dcs::plate_files_changed(&g.plate_files, &f.path) { + return (Status::Modified, Some(f)); + } if l.size == Some(f.size) && l.modified.is_some() && l.modified == f.modified { return (Status::Ok, Some(f)); } @@ -346,7 +364,7 @@ fn probe(g: &Group, base: LinkBase) -> (Status, Option) { let same = match &l.hash { Some(h) => *h == hash_bytes(&bytes), // Linked before links kept a hash: the image the file decodes to. - None => g.document.is_none() && fileio::raster_image(&bytes).is_ok_and(|img| img.key == g.key), + None => g.document.is_none() && super::place::dcs::raster(&bytes, Some(&f.path)).is_ok_and(|img| img.key == g.key), }; f.bytes = Some(bytes); (if same { Status::Ok } else { Status::Modified }, Some(f)) @@ -433,7 +451,7 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a previews.insert(key); continue; }; - let Ok(img) = fileio::raster_image(&bytes) else { + let Ok(img) = super::place::dcs::raster(&bytes, Some(&f.path)) else { previews.insert(key); continue; }; @@ -512,10 +530,11 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) -> Ok(blob) } -/// The linked image file `bytes`, read ([`fileio::raster_image`]) with its preview; an error when -/// its pixels can't be read ([`readable`]). -fn linked_image(bytes: &[u8]) -> Result { - let mut img = fileio::raster_image(bytes)?; +/// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a +/// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels +/// can't be read ([`readable`]). +fn linked_image(bytes: &[u8], path: Option<&str>) -> Result { + let mut img = super::place::dcs::raster(bytes, path)?; img.blob = readable(img.blob, kept_unread(bytes), true)?; Ok(img) } @@ -536,7 +555,7 @@ fn read_image(f: &mut Found, base: &LinkInfo, reads: &mut ImageReads) -> Result< let img = match reads.get(&f.path) { Some((h, img)) if *h == hash => img.clone(), _ => { - let img = linked_image(&bytes)?; + let img = linked_image(&bytes, Some(&f.path))?; reads.insert(f.path.clone(), (hash.clone(), img.clone())); img } @@ -586,12 +605,89 @@ fn clip_shape((frame, room): Clip) -> PathData { shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame) } +/// What happens to the clip of an object a link update remakes. +enum ClipTo { + /// It stays as it is. + Keep, + /// It is clipped to this path: the clipping path of the clip group holding just it changes, + /// else it goes into a new clip group. + Path(PathData), + /// It goes into a new clip group of this path, inside the clip group that holds it. + Nest(PathData), + /// The clipping path of the clip group holding just it goes (a DCS file's clipping path that + /// its new file lacks): the group stays as a plain group of it, with its id, name, visibility + /// and transparency. + Off, +} + +/// The clipping path, with its fill rule, of the clip group holding just object `id` of `d`, when +/// one holds it. +fn clip_path_of(d: &Document, id: NodeId) -> Option<(&PathData, FillRule)> { + let g = d.node(d.parent_of(id)?)?; + match &g.kind { + NodeKind::Group { children, clip: true } => match &children[..] { + [c, o] if o.id == id => match &c.kind { + NodeKind::Path { path, rule, clipping: true, .. } => Some((path, *rule)), + _ => None, + }, + _ => None, + }, + _ => None, + } +} + +/// Do `a` and `b` have the same subpaths, each closed or open alike, and the same anchors, each +/// within a thousandth of a point? +fn same_path(a: &PathData, b: &PathData) -> bool { + let near = |p: vectorcraft_geom::Point, q: vectorcraft_geom::Point| p.distance(q) < 1e-3; + a.anchor_count() == b.anchor_count() + && a.subpaths.len() == b.subpaths.len() + && a.subpaths.iter().zip(&b.subpaths).all(|(x, y)| x.closed == y.closed) + && a.anchors() + .zip(b.anchors()) + .all(|((si, ai, x), (sj, aj, y))| si == sj && ai == aj && near(x.p, y.p) && near(x.h_in, y.h_in) && near(x.h_out, y.h_out)) +} + +/// The clip an image placed with `old_xf` takes when it shows `img`, read from a file, placed with +/// `new_xf`: Placement Options' clip `clip` when they clip it, else the clipping path a DCS file +/// draws `img` through. When neither clips it, a clip group holding just it whose clipping path +/// `held` is its old DCS file's (`old_clip`, in the old pixels, under the nonzero rule its clip +/// groups get) goes. +fn clip_to( + old_xf: Affine, + old_clip: Option<&PathData>, + clip: Option, + img: &RasterImage, + new_xf: Affine, + held: Option<(&PathData, FillRule)>, +) -> ClipTo { + if let Some(clip) = clip { + return ClipTo::Path(clip_shape(clip)); + } + // Whether the clip group holding just the image is the old DCS file's: a clipping path whose + // fill rule was changed in the document is not. + let file_held = match (old_clip, held) { + (Some(old), Some((held, rule))) => rule == FillRule::NonZero && same_path(&old.transformed(old_xf), held), + _ => false, + }; + match img.clip.as_ref().map(|path| path.transformed(new_xf)) { + // A clipping mask made in the document stays, with the file's clip group inside it. + Some(path) if held.is_some() && !file_held => ClipTo::Nest(path), + Some(path) => ClipTo::Path(path), + None if file_held => ClipTo::Off, + None => ClipTo::Keep, + } +} + +/// The object an object becomes, and what happens to its clip, given the clipping path of the clip +/// group holding just it ([`ClipTo`]). +type Remake<'a> = dyn FnMut(&Node, Option<(&PathData, FillRule)>) -> (Node, ClipTo) + 'a; + /// Remakes the linked objects outside the layer tree (in symbols, graph designs, patterns and /// opacity masks, where [`Document::node`] finds no ids) that `pick` holds for. struct Nested<'a> { pick: &'a dyn Fn(&Node) -> bool, - /// The object an object becomes, and the clip it takes ([`placed_xf`]). - make: &'a mut dyn FnMut(&Node) -> (Node, Option), + make: &'a mut Remake<'a>, /// The next node id for a clip group (taken from the document after the walk). next: u64, } @@ -622,12 +718,12 @@ impl Nested<'_> { if !(self.pick)(n) { return self.update(n, true); } - let (new, clip) = (self.make)(n); + let (new, clip) = (self.make)(n, None); let mut new = Arc::new(new); self.update(&mut new, true); *n = match clip { - Some(clip) => Arc::new(self.clip_group(new, clip)), - None => new, + ClipTo::Path(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)), + ClipTo::Keep | ClipTo::Off => new, }; } @@ -640,6 +736,8 @@ impl Nested<'_> { (!Arc::ptr_eq(&art, &m.art)).then_some(art) }); let mut slots: Vec<(usize, Arc)> = vec![]; + // The object a clip group that loses its clipping path holds alone. + let mut declipped = None; if let Some(children) = n.children() { // A clip group holding just the object: its clipping path changes. let clip_path = match (&n.kind, &children[..]) { @@ -655,32 +753,45 @@ impl Nested<'_> { } continue; } - let (new, clip) = (self.make)(c); + let held = clip_path.filter(|_| i == 1).and_then(|p| match &p.kind { + NodeKind::Path { path, rule, .. } => Some((path, *rule)), + _ => None, + }); + let (new, clip) = (self.make)(c, held); let mut new = Arc::new(new); self.update(&mut new, true); match (clip, clip_path) { - (None, _) => slots.push((i, new)), - (Some(clip), Some(path)) if i == 1 => { + (ClipTo::Keep, _) => slots.push((i, new)), + (ClipTo::Path(clip), Some(path)) if i == 1 => { let mut path = Node::clone(path); if let NodeKind::Path { path: p, .. } = &mut path.kind { - *p = clip_shape(clip); + *p = clip; } slots.extend([(0, Arc::new(path)), (1, new)]); } - (Some(clip), _) => { + (ClipTo::Path(clip) | ClipTo::Nest(clip), _) => { let group = self.clip_group(new, clip); slots.push((i, Arc::new(group))); } + (ClipTo::Off, Some(_)) if i == 1 => declipped = Some(new), + (ClipTo::Off, _) => slots.push((i, new)), } } } - if mask.is_none() && slots.is_empty() { + if mask.is_none() && slots.is_empty() && declipped.is_none() { return; } let n = Arc::make_mut(n); if let (Some(art), Some(m)) = (mask, n.extras_if_any().and_then(|e| e.mask.as_mut())) { m.art = art; } + // A clip group that stays as a plain group of just the object. + if let Some(object) = declipped { + if let NodeKind::Group { children, clip } = &mut n.kind { + (*children, *clip) = (vec![object], false); + } + return; + } if let Some(children) = n.children_mut() { for (i, c) in slots { if let Some(slot) = children.get_mut(i) { @@ -690,12 +801,12 @@ impl Nested<'_> { } } - /// A clip group of `object` clipped to `clip`, as [`clip_image`] makes one in the layers. - fn clip_group(&mut self, object: Arc, clip: Clip) -> Node { + /// A clip group of `object` clipped to `clip`, as [`clip_image_to`] makes one in the layers. + fn clip_group(&mut self, object: Arc, clip: PathData) -> Node { let (path_id, group_id) = (NodeId(self.next), NodeId(self.next + 1)); self.next += 2; let none = vectorcraft_color::Paint::None; - let mut path = Node::path(path_id, clip_shape(clip), Appearance::basic(none.clone(), none, 0.0)); + let mut path = Node::path(path_id, clip, Appearance::basic(none.clone(), none, 0.0)); if let NodeKind::Path { clipping, .. } = &mut path.kind { *clipping = true; } @@ -723,13 +834,13 @@ fn install_document( }; if let Some(also) = also { let pick = |n: &Node| shows(n, also, true); - let mut make = |n: &Node| { + let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| { let mut n = n.clone(); - let mut clip = None; + let mut clip = ClipTo::Keep; if let NodeKind::PlacedDocument(p) = &mut n.kind { let (xf, c) = placed(p); (p.key, p.width, p.height, p.xf, p.link) = (src.key.clone(), w, h, xf, link.clone()); - clip = c; + clip = c.map_or(ClipTo::Keep, |c| ClipTo::Path(clip_shape(c))); } (n, clip) }; @@ -801,10 +912,9 @@ fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), n (frame * at * Affine::scale_non_uniform(size.0 / nw, size.1 / nh), (o.clip && over).then_some((frame, room))) } -/// Clip image `id` of `d` to `room` in `frame`: the clipping path of the clip group holding just -/// it changes, else the image goes into a new clip group. -fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> { - let path = clip_shape(clip); +/// The clipping path of the clip group of `d` holding just object `id` becomes `path`; false when +/// no such clip group holds it. +fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool { let clip_path = d.parent_of(id).and_then(|p| match &d.node(p)?.kind { NodeKind::Group { children, clip: true } => match &children[..] { [c, im] if im.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c.id), @@ -812,12 +922,30 @@ fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> { }, _ => None, }); - if let Some(c) = clip_path { - if let Some(Node { kind: NodeKind::Path { path: p, .. }, .. }) = d.node_mut(c) { - *p = path; - } + let Some(c) = clip_path else { return false }; + if let Some(Node { kind: NodeKind::Path { path: p, .. }, .. }) = d.node_mut(c) { + *p = path; + } + true +} + +/// Clip image `id` of `d` to `room` in `frame`: the clipping path of the clip group holding just +/// it changes, else the image goes into a new clip group. +fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> { + clip_image_to(d, id, clip_shape(clip)) +} + +/// Clip object `id` of `d` to `path`: the clipping path of the clip group holding just it changes, +/// else it goes into a new clip group. +fn clip_image_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { + if set_clip_path(d, id, path.clone()) { return Ok(()); } + new_clip_group(d, id, path) +} + +/// Put object `id` of `d` into a new clip group of `path`, where it is. +fn new_clip_group(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?; let image = d.remove(id)?; let none = vectorcraft_color::Paint::None; @@ -839,7 +967,7 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ // the app connect to another computer. let path = fileio::document_path(path, doc_path).map_err(|r| EngineError::Other(format!("the image `{path}` isn't followed: {r}")))?; let bytes = read_file(&path)?; - let read = (link_info(&path, &bytes), linked_image(&bytes)?); + let read = (link_info(&path, &bytes), linked_image(&bytes, Some(&path))?); install(d, &[id], read, Some(Preserve::Bounds), None) } @@ -853,15 +981,17 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio // Every image picked shows content `also.1`, so one resolution serves them all. let old_pt = file_pt(d, also.1); let pick = |n: &Node| shows(n, also, false); - let mut make = |n: &Node| { + // The clipping path the old content's DCS file drew it through. + let old_clip = d.images.get(also.1).and_then(ImageBlob::separated_clip); + let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| { let mut n = n.clone(); - let mut clip = None; + let mut clip = ClipTo::Keep; if let NodeKind::Image(im) = &mut n.kind { let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o); + clip = clip_to(im.xf, old_clip.as_ref(), c, &img, xf, held); (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); - clip = c; } (n, clip) }; @@ -872,15 +1002,43 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); let (xf, clip) = placed_xf(im.xf, size(im.width, im.height), file_pt(d, &im.key), size(img.width, img.height), new_pt, o); + // Placement Options' clip, else a DCS file's clipping path, read again with its plates. + let old_clip = d.images.get(&im.key).and_then(ImageBlob::separated_clip); + clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id)))); if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind { (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); } - clips.extend(clip.map(|c| (*id, c))); } + // A DCS file's spot plates print on spot swatches of their inks. + super::place::dcs::add_spot_swatches(d, &img.blob.spot_plates()); store_image(d, &img.key, img.blob, true); - clips.into_iter().try_for_each(|(id, clip)| clip_image(d, id, clip)) + clips.into_iter().try_for_each(|(id, clip)| match clip { + ClipTo::Keep => Ok(()), + ClipTo::Path(path) => clip_image_to(d, id, path), + ClipTo::Nest(path) => new_clip_group(d, id, path), + ClipTo::Off => unclip(d, id), + }) +} + +/// Take the clipping path of the clip group holding just object `id` of `d` away: the group stays +/// as a plain group of the object, with its id, name, visibility and transparency as they were. +fn unclip(d: &mut Document, id: NodeId) -> Result<()> { + let Some((g, clip)) = d.parent_of(id).and_then(|g| match &d.node(g)?.kind { + NodeKind::Group { children, clip: true } => match &children[..] { + [c, o] if o.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some((g, c.id)), + _ => None, + }, + _ => None, + }) else { + return Ok(()); + }; + d.remove(clip)?; + if let Some(Node { kind: NodeKind::Group { clip, .. }, .. }) = d.node_mut(g) { + *clip = false; + } + Ok(()) } /// Groups (of the document saved at `doc_path`) as `{name, path, ids}` rows (those with objects in @@ -1013,7 +1171,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps // Read when the images show the preview, or when the file's details changed. let bytes = if (preview && !eps_preview) || f.bytes.is_some() { f.read().ok() } else { None }; if preview && !eps_preview { - let Some((b, img)) = bytes.as_deref().and_then(|b| Some((b, linked_image(b).ok()?))) else { + let Some((b, img)) = bytes.as_deref().and_then(|b| Some((b, linked_image(b, Some(&f.path)).ok()?))) else { out.missing.extend(row); continue; }; @@ -1051,15 +1209,17 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps m.iter().find(|(k, doc, _)| k == key && *doc == document.is_some()).map(|(_, _, new)| new) }; let pick = |n: &Node| new(n).is_some(); - let mut make = |n: &Node| { + let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| { let mut out = n.clone(); if let (Some(link), Some(l)) = (new(n), link_mut(&mut out)) { *l = link.clone(); } - (out, None) + (out, ClipTo::Keep) }; 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 } @@ -1326,10 +1486,44 @@ fn update_where(s: &mut Session, ids: Option>, path: Option<&str>) - } } let updated: Vec = reads.iter().flat_map(|(g, _)| ids_json(&g.ids)).collect(); + let warnings = spot_swatch_notes(&st.doc, reads.iter().map(|(_, read)| read)); if !reads.is_empty() { s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))?; } - Ok(json!({ "updated": updated, "missing": missing })) + let mut out = json!({ "updated": updated, "missing": missing }); + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } + Ok(out) +} + +/// The warnings for the spot plates of the DCS files in `reads` whose ink a swatch of `d` already +/// names in another color, or as a process color ([`super::place::dcs::swatch_notes`]), or that an +/// earlier file of `reads` adds as a spot swatch in another color, each once. +fn spot_swatch_notes<'a>(d: &Document, reads: impl Iterator) -> Vec { + let mut out: Vec = vec![]; + // The spot swatches the reads add, in the order they are installed. + let mut added: Vec<(String, [f32; 4])> = vec![]; + for read in reads { + let Read::Image((_, img)) = read else { continue }; + let spots = img.blob.spot_plates(); + let mut notes = super::place::dcs::swatch_notes(d, &spots); + for (name, cmyk) in spots.into_iter().filter(|(name, _)| d.swatch(name).is_none()) { + match added.iter().find(|(n, _)| *n == name) { + Some((_, first)) if first.iter().zip(cmyk).any(|(a, b)| (a - b).abs() >= 0.005) => { + notes.push(format!("the document's swatch `{name}` is kept: it is a different color")); + } + Some(_) => {} + None => added.push((name, cmyk)), + } + } + for note in notes { + if !out.contains(¬e) { + out.push(note); + } + } + } + out } /// Which links `links.relink` points at the new file (the Replace choice of Relink). @@ -1511,7 +1705,11 @@ fn relink(s: &mut Session, p: &Value) -> Result { } } // Read before it is copied: a file that can't be shown isn't copied. - let img = if images.is_empty() { None } else { Some(linked_image(&bytes).map_err(|e| bad(C, format!("{path}: {e}")))?) }; + let img = if images.is_empty() { None } else { Some(linked_image(&bytes, Some(&path)).map_err(|e| bad(C, format!("{path}: {e}")))?) }; + // A copy beside the document would point at plate files it can't find there. + if copy_to.is_some() && img.as_ref().is_some_and(|img| !img.blob.plate_files().is_empty()) { + return Err(bad(C, format!("{path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are"))); + } let mut sources = vec![]; for ((page, bounding, page_box), ids) in documents { sources.push((page, ids, super::place::document::source(&path, &bytes, Some(&path), page, bounding, page_box, C)?)); @@ -1546,12 +1744,16 @@ fn relink(s: &mut Session, p: &Value) -> Result { } } let relinked: Vec = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect(); + let warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read)); if !reads.is_empty() { s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None)))?; } not_found.sort(); not_found.dedup(); let mut out = json!({ "relinked": relinked, "notFound": not_found }); + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } if copy_to.is_some() { // The copies are in the document's folder, which the client did not give. for pair in copied.iter_mut().chain(kept.iter_mut()) { @@ -1710,6 +1912,9 @@ pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap &'static str { + if im.link.is_some() && d.images.get(&im.key).is_some_and(ImageBlob::is_separated) { + return "DCS"; + } im.link .as_ref() .and_then(|l| fileio::format_for_name(l.name()).or_else(|| fileio::readable_format_for_name(l.name()))) @@ -1730,6 +1935,45 @@ fn status_rank(status: &str) -> usize { ["missing", "modified", "ok", "embedded"].iter().position(|s| *s == status).unwrap_or(4) } +/// The DCS images in the layers of `d` that are transparent (themselves, or a group or layer that +/// holds them) or overlap an object that is, as Show DCS Transparency Interactions marks them. +fn dcs_transparency(d: &Document) -> BTreeSet { + /// Each visible DCS image's id, bounds and whether it is transparent, and the bounds of each + /// other visible object with its own transparency. + fn walk(d: &Document, n: &Node, held: bool, images: &mut Vec<(NodeId, Rect, bool)>, see_through: &mut Vec) { + if !n.visible { + return; + } + let own = n.shows_own_transparency(); + match &n.kind { + NodeKind::Image(im) if d.images.get(&im.key).is_some_and(ImageBlob::is_separated) => { + if let Some(b) = n.geometric_bounds() { + images.push((n.id, b, held || own)); + // A transparent DCS image is an object with its own transparency for the + // others it overlaps. + if own { + see_through.push(b); + } + } + } + _ if own => see_through.extend(n.geometric_bounds()), + _ => {} + } + for c in n.children().into_iter().flatten() { + walk(d, c, held || own, images, see_through); + } + } + let (mut images, mut see_through) = (vec![], vec![]); + for l in &d.layers { + walk(d, l, false, &mut images, &mut see_through); + } + images + .into_iter() + .filter(|(_, b, transparent)| *transparent || see_through.iter().any(|t| t.intersect(*b).area() > 0.0)) + .map(|(id, ..)| id) + .collect() +} + fn list(s: &mut Session, p: &Value) -> Result { const C: &str = "links.list"; let st = s.doc()?; @@ -1737,6 +1981,7 @@ fn list(s: &mut Session, p: &Value) -> Result { if !matches!(show, "all" | "missing" | "modified" | "embedded") { return Err(bad(C, format!("show `{show}`: all, missing, modified or embedded"))); } + let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() }; let statuses = statuses(st); let mut objects = vec![]; st.doc.walk(|n| { @@ -1791,6 +2036,9 @@ fn list(s: &mut Session, p: &Value) -> Result { if preview { row["preview"] = json!(true); } + if interactions.contains(&n.id) { + row["dcsTransparency"] = json!(true); + } rows.push(row); } let text = |r: &Value, k: &str| r[k].as_str().unwrap_or_default().to_lowercase(); @@ -1829,6 +2077,14 @@ fn embed(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "select the linked images or placed documents, or pass ids")); } + // A DCS file's plates print from its file. + let separated = |id: &NodeId| match kind(id) { + Some(NodeKind::Image(im)) => st.doc.images.get(&im.key).is_some_and(ImageBlob::is_separated), + _ => false, + }; + if let Some(id) = ids.iter().find(|id| separated(id)) { + return Err(bad(C, format!("object {}: {}", id.0, super::place::dcs::LINK_ONLY))); + } // Placed documents become editable copies of their art: those whose file can be read. let (mut documents, mut missing) = (vec![], vec![]); for id in ids.iter().copied() { @@ -1847,6 +2103,10 @@ fn embed(s: &mut Session, p: &Value) -> Result { } match probe(&g, LinkBase::of(st)) { (Status::Ok | Status::Modified, Some(mut f)) => match read_image(&mut f, &g.link, &mut image_reads) { + // One showing its preview is a DCS file only its file tells. + Ok((_, img)) if img.blob.is_separated() => { + return Err(bad(C, format!("object {}: {}", g.ids.first().map_or(0, |id| id.0), super::place::dcs::LINK_ONLY))); + } Ok(read) => { done.extend(&g.ids); reads.push((g.ids, read)); @@ -1913,7 +2173,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result { }; let path = absolute_path(&if fileio::extension(path).is_empty() { format!("{path}.{ext}") } else { path.to_string() }); // Read before writing: pixels that can't be read leave no file behind. - let img = linked_image(&bytes)?; + let img = linked_image(&bytes, Some(&path))?; write_file(&path, &bytes)?; let read = (link_info(&path, &bytes), img); s.edit("Unembed", |d, _| install(d, &[id], read, Some(Preserve::Bounds), None))?; 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..eaf1597423 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -690,7 +690,9 @@ fn placed_across(d: &Document, ids: &[NodeId], paint: Paint, p: &Value, fill: bo /// The images among `ids` that a fill of `paint` colorizes: grayscale and 1-bit images, for a solid /// color (or none on a colorized image, which takes the color off). The color may be black, white, /// a process color or a spot color; on an image with an alpha channel, only a spot color, black or -/// white, and other colors are an error. +/// white, and other colors are an error. A colorized image that shows a preview that isn't +/// grayscale, such as a missing link's placeholder, takes a solid color as its new colorize paint; +/// while its paint is one an alpha channel allows, a process color is an error there too. fn colorized_images(d: &Document, ids: &[NodeId], paint: &Paint) -> std::result::Result, String> { let mut out = vec![]; for id in ids { @@ -701,7 +703,22 @@ 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 }; + // The Fill proxy shows such an image's colorize paint. Its pixels are not known until the + // file is relinked: a process color replaces only a process color, which the image's + // pixels already accepted, so a relink can't bring back an alpha channel under one. + if matches!(paint, Paint::Solid { .. }) + && let Some(old) = n.extras().colorize.as_deref() + && d.image_blob(im).is_some_and(|b| !b.takes_colorize()) + { + if !colorizes_transparency(d, paint) && colorizes_transparency(d, old) { + return Err(PROCESS_ON_TRANSPARENCY.into()); + } + out.push(*id); + 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 +775,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/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 1ab5707d58..5910435a75 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -622,7 +622,16 @@ fn set_format(s: &mut Session, p: &Value) -> Result { Some(v) => Some(match v.as_str() { Some("none") => vectorcraft_doc::Mojikumi::None, Some("lineEndHalf") => vectorcraft_doc::Mojikumi::LineEndHalf, - _ => return Err(bad(C, "`mojikumi` must be \"none\" or \"lineEndHalf\"")), + Some("yakumonoHankaku") => vectorcraft_doc::Mojikumi::YakumonoHankaku, + Some("gyomatsuYakumonoHankaku") => vectorcraft_doc::Mojikumi::GyomatsuYakumonoHankaku, + Some("gyomatsuYakumonoZenkaku") => vectorcraft_doc::Mojikumi::GyomatsuYakumonoZenkaku, + Some("yakumonoZenkaku") => vectorcraft_doc::Mojikumi::YakumonoZenkaku, + _ => { + return Err(bad( + C, + "`mojikumi` must be \"none\", \"yakumonoHankaku\", \"gyomatsuYakumonoHankaku\", \"gyomatsuYakumonoZenkaku\", \"yakumonoZenkaku\" or \"lineEndHalf\"", + )); + } }), }; let kinsoku = match p.get("kinsoku") { diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 60fa90c32c..c38854ae76 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -15,8 +15,8 @@ //! commands a command runs, the steps of a `command.batch` or an `action.batch` included: a //! misspelled `widht` no longer runs the command with its default. So are the `params` of an //! effect (#1592): `effect.apply` and -//! `effect.setParams` answer a key the effect doesn't take, or a value of another type than its -//! default, with a parameter error ([`check_effect_params`]). +//! `effect.setParams` answer a key the effect doesn't take, or a value of another type than the +//! effect reads, with a parameter error ([`check_effect_params`]). //! //! A command with a parameter schema (`CommandSpec::schema`) is also checked against the schema //! before it runs ([`crate::schemas::check`]): the schema refuses a value of the wrong type or out @@ -263,15 +263,15 @@ pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError } /// `params` of built-in effect `effect`, as command `id` was given them (#1592): only keys the -/// effect takes (those of its dialog defaults and of its params description), each of its -/// default's type, a `color` the effect can draw ([`check_effect_color`]) and a Levels or Curves -/// `channel` the effect has ([`check_effect_channel`]). Numbers out of range pass: the effect -/// clamps them when it draws. An effect plug-in resolves its own against its manifest, and an -/// unknown effect is the command's to report. +/// effect takes (those of its dialog defaults and of its params description), each of the type +/// the effect reads ([`check_effect_types`]), a `color` the effect can draw ([`check_effect_color`]) +/// and a Levels or Curves `channel` the effect has ([`check_effect_channel`]). Numbers out of range +/// pass: the effect clamps them when it draws. An installed effect plug-in's are checked against its +/// manifest, and an unknown effect is the command's to report. pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> { let Value::Object(given) = params else { return Ok(()) }; if effect.starts_with(vectorcraft_plugins::effect::PREFIX) { - return Ok(()); + return check_effect_types(id, effect, params); } let Some(info) = vectorcraft_render::effects::effect_info(effect) else { return Ok(()) }; let defaults = info.defaults.as_object(); @@ -282,18 +282,10 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> keys.push(key); } } - for (key, v) in given { - if !keys.contains(&key.as_str()) { - return Err(unknown(id, key, &keys)); - } - match defaults.and_then(|d| d.get(key)) { - Some(Value::Number(_)) if !v.is_number() => return Err(bad(id, format!("`{key}` must be a number"))), - Some(Value::Bool(_)) if !v.is_boolean() => return Err(bad(id, format!("`{key}` must be true or false"))), - // (A colour is also taken as `[r, g, b]` or as a colour object.) - Some(Value::String(_)) if v.is_number() || v.is_boolean() => return Err(bad(id, format!("`{key}` must be a string"))), - _ => {} - } + if let Some(key) = given.keys().find(|k| !keys.contains(&k.as_str())) { + return Err(unknown(id, key, &keys)); } + check_effect_types(id, effect, params)?; // An SVG filter's XML is one drawable element. if effect == vectorcraft_render::effects::SVG_FILTER && let Some(xml) = given.get("xml") @@ -329,6 +321,59 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> check_effect_channel(id, effect, params) } +/// The type of the values in `params` of effect `effect`, as command `id` was given them: a key +/// the effect has a dialog default for takes a value of its default's type, a key only the +/// effect's params description names takes the type the effect reads ([`undefaulted_type`]), and +/// an installed effect plug-in's take the types its manifest gives them. The `style` of Crop Marks +/// is `roman` or `japanese`. A number given as text (`"10 pt"`), `true` for a number, `1` for a +/// switch and `null` for either are refused. +fn check_effect_types(id: &str, effect: &str, params: &Value) -> Result<()> { + let Value::Object(given) = params else { return Ok(()) }; + if effect.starts_with(vectorcraft_plugins::effect::PREFIX) { + return match vectorcraft_plugins::effect::installed(effect) { + Some(plugin) => plugin.manifest().resolve_params(params).map(drop).map_err(|why| bad(id, why.to_string())), + None => Ok(()), + }; + } + let Some(info) = vectorcraft_render::effects::effect_info(effect) else { return Ok(()) }; + for (key, v) in given { + let want = info.defaults.get(key).cloned().or_else(|| undefaulted_type(effect, key)); + match want { + Some(Value::Number(_)) if !v.is_number() => return Err(bad(id, format!("`{key}` must be a number"))), + Some(Value::Bool(_)) if !v.is_boolean() => return Err(bad(id, format!("`{key}` must be true or false"))), + // (A colour is also taken as `[r, g, b]` or as a colour object.) + Some(Value::String(_)) if v.is_number() || v.is_boolean() => return Err(bad(id, format!("`{key}` must be a string"))), + _ => {} + } + } + // Crop Marks draw one of two styles. + if effect == vectorcraft_render::effects::CROP_MARKS + && let Some(style) = given.get("style") + && style.as_str().and_then(vectorcraft_doc::marks::MarkStyle::parse).is_none() + { + return Err(bad(id, "`style` must be roman or japanese")); + } + Ok(()) +} + +/// A value of the type effect `effect` reads for `key`, a parameter its params description names +/// without a dialog default: the earlier 3D Perspective and light (`perspective`, `lightAzimuth`, +/// `lightElevation`) and Scribble `variation` are numbers, an Outline Stroke's `width` is a number +/// and a Gaussian Blur's `linear` is true or false. A Glass or Texturizer `textureImage`, an SVG +/// filter's `name` and `xml`, a Warp's `version` and the `style` of Crop Marks have checks of their +/// own; they aren't listed. +pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option { + use vectorcraft_render::effects; + let number = || Some(Value::from(0.0)); + match key { + "perspective" | "lightAzimuth" | "lightElevation" if effects::is_three_d(effect) => number(), + "variation" if effect == "stylize.scribble" => number(), + "width" if effect == "path.outlineStroke" => number(), + "linear" if effect == "blur.gaussian" => Some(Value::Bool(false)), + _ => None, + } +} + /// Can an effect read `v` as its `color`: a string [`Color::from_hex`] reads (`#rrggbb`, `#rgb`, /// `#rrggbbaa`, black, white, red, green, blue), `[r, g, b]` whose first three entries are numbers /// (read on a 0..1 scale) or a color object (`{"model": "rgb", "r": …}`)? The effect draws its diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index c05493e964..b4639f0de5 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Close Path", [], None, - "{id, subpath?: usize (the open subpath to close, 0 included; default: the last open one), in?: [x,y] (handle into the first anchor, placed as path.setHandle places it: a smooth first anchor keeps its outgoing handle in line at its own length, a corner keeps it where it is), out?: [x,y] (the first anchor's outgoing handle, placed after `in`; the anchor becomes a corner), independent?: bool (`in` makes the first anchor a corner and leaves its outgoing handle)}", + "{id, subpath?: usize (the open subpath to close, 0 included; default: the last open one), at?: [x,y] (move the first anchor there, its handles with it, before `in` and `out` are placed), in?: [x,y] (handle into the first anchor, placed as path.setHandle places it: a smooth first anchor keeps its outgoing handle in line at its own length, a corner keeps it where it is), out?: [x,y] (the first anchor's outgoing handle, placed after `in`; the anchor becomes a corner), independent?: bool (`in` makes the first anchor a corner and leaves its outgoing handle)}", has_doc, close ), @@ -205,6 +205,7 @@ fn append_anchor(s: &mut Session, p: &Value) -> Result { /// Close the active open subpath of `id`, optionally setting the handles of the first anchor. The /// incoming handle moves as Move Direction Handle moves it: the outgoing handle turns with it only /// on a smooth anchor, so the first segment of a path that starts at a corner keeps its shape. +/// `at` first moves the anchor, its handles with it (the Pen's closing drag with Space held). fn close(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "path.close")?.ok_or_else(|| bad("path.close", "missing id"))?; let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize); @@ -212,6 +213,7 @@ fn close(s: &mut Session, p: &Value) -> Result { None => Ok(None), Some(h) => finite_numbers(h).map(|[x, y]| Some(Point::new(x, y))).ok_or_else(|| bad("path.close", format!("`{key}` must be [x, y]"))), }; + let at = handle("at")?; let h_in = handle("in")?; let h_out = handle("out")?; let independent = switch_or(p, "independent", false, "path.close")?; @@ -223,6 +225,9 @@ fn close(s: &mut Session, p: &Value) -> Result { }; sp.closed = true; if let Some(first) = sp.anchors.first_mut() { + if let Some(to) = at { + first.translate(to - first.p); + } if let Some(h) = h_in { first.set_handle(false, h, independent); } diff --git a/crates/engine/src/cmd/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs index 4075676ca6..2800e8e674 100644 --- a/crates/engine/src/cmd/patterncmds.rs +++ b/crates/engine/src/cmd/patterncmds.rs @@ -14,6 +14,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Paint; use vectorcraft_doc::pattern::{self, Overlap, PATTERN_EDIT_LAYER, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType, pattern_paint}; +use vectorcraft_doc::swatches::PaintFn; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Point, Rect}; @@ -54,7 +55,15 @@ pub fn specs() -> Vec { in_pattern_edit, pattern_done ), - cmd!("object.pattern.cancel", "Cancel", [], None, "{} leave pattern editing mode, discarding changes", in_pattern_edit, pattern_cancel), + cmd!( + "object.pattern.cancel", + "Cancel", + [], + None, + "{} leave pattern editing mode, discarding changes; a pattern made for this edit is removed with its swatches, and every paint of it, new art's fill and stroke included, becomes none", + in_pattern_edit, + pattern_cancel + ), cmd!( "object.pattern.saveCopy", "Save a Copy", @@ -78,7 +87,7 @@ pub fn specs() -> Vec { "Delete Pattern", [], None, - "{name} delete a pattern swatch (objects painted with it lose that paint)", + "{name} delete a pattern and its swatches; every paint of it, new art's fill and stroke included, becomes none → {unpainted: the number of document paints cleared}", has_doc, pattern_delete ), @@ -403,26 +412,96 @@ pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result Result { - s.edit("Cancel Pattern Editing", |d, sel| { + let changed = s.edit("Cancel Pattern Editing", |d, sel| { let (pe, _) = leave_edit(d, sel)?; match pe.original { - Some(orig) => { + Some(mut orig) => { + if orig.name != pe.pattern && (d.pattern(&orig.name).is_some() || swatch_name_clash(d, &pe.pattern, &orig.name)) { + orig.name = pe.pattern.clone(); + } + let back = (orig.name != pe.pattern).then(|| orig.name.clone()); if let Some(def) = d.pattern_mut(&pe.pattern) { *def = orig; } + if let Some(old) = &back { + rename_pattern_uses(d, &pe.pattern, old); + } + Ok(back.map(|old| (pe.pattern, Some(old)))) } None => { - d.patterns.retain(|p| p.name != pe.pattern); - d.swatches.retain(|sw| !matches!(&sw.paint, Paint::Pattern { pattern, .. } if *pattern == pe.pattern)); + forget_pattern(d, &pe.pattern); + Ok(Some((pe.pattern, None))) } } - Ok(()) })?; after_edit_mode(s, None)?; + if let Some((name, to)) = changed { + map_new_art_paints(s, &mut pattern_paints(&name, to.as_deref()))?; + } ok() } +/// A [`PaintFn`] that puts a paint of pattern `to` in place of each paint of pattern `name`, with +/// its placement kept, or no paint for `to` `None`. +fn pattern_paints<'a>(name: &'a str, to: Option<&'a str>) -> impl FnMut(&Paint) -> Option + 'a { + move |p| match p { + Paint::Pattern { pattern, xf } if pattern == name => Some(match to { + Some(n) => Paint::Pattern { pattern: n.to_string(), xf: *xf }, + None => Paint::None, + }), + _ => None, + } +} + +/// Remove pattern `name` from `d`: its definition and every swatch, grouped or not, whose paint is +/// the pattern. Every paint of the pattern left anywhere in the document (the art, opacity masks, +/// type, symbol definitions, graph designs, graphs' stored series and label paints, other patterns' +/// tiles, graphic and character styles and the art of brushes) becomes no paint. Returns the number of such paints. +fn forget_pattern(d: &mut Document, name: &str) -> usize { + d.patterns.retain(|p| p.name != name); + let is_it = |sw: &vectorcraft_color::Swatch| matches!(&sw.paint, Paint::Pattern { pattern, .. } if pattern == name); + d.swatches.retain(|sw| !is_it(sw)); + for g in &mut d.swatch_groups { + g.swatches.retain(|sw| !is_it(sw)); + } + super::swatch::map_all_paints(d, &mut pattern_paints(name, None)) +} + +/// Apply `f` to the fill and stroke new art takes and to the paints of its template appearance. A +/// change is recorded with the step just made, so Undo and Redo put these paints back with the +/// document. +fn map_new_art_paints(s: &mut Session, f: &mut PaintFn) -> Result<()> { + let start = super::colormgmt::new_art_colors_before(s)?; + let old = s.paint.clone(); + let pd = &mut s.paint; + let template = pd.appearance.iter_mut().flat_map(|a| a.items.iter_mut()).map(|it| match it { + vectorcraft_doc::AppearanceItem::Fill(f) => &mut f.paint, + vectorcraft_doc::AppearanceItem::Stroke(s) => &mut s.paint, + }); + for p in [&mut pd.fill, &mut pd.stroke].into_iter().chain(template) { + if let Some(q) = f(p) { + *p = q; + } + } + if s.paint != old { + super::colormgmt::record_new_art_colors(s, start)?; + // The step takes the paints the command finally leaves, after the selection's appearance + // is inherited. + let st = s.doc()?; + if st.interaction.is_none() { + let uid = st.uid; + s.batch_paint_docs.push(uid); + } + } + Ok(()) +} + fn pattern_save_copy(s: &mut Session, p: &Value) -> Result { let wanted = text_param(p, "name", "object.pattern.saveCopy")?.map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); let name = s.edit("Save a Copy", |d, _| { @@ -524,6 +603,9 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result { } Ok(()) })?; + if let Some(nn) = &new_name { + map_new_art_paints(s, &mut pattern_paints(&name, Some(nn)))?; + } Ok(json!({ "name": out_name })) } @@ -552,47 +634,19 @@ fn swatch_name_clash(d: &Document, old: &str, new: &str) -> bool { } /// Rename a pattern in swatches, paints and the edit record. Of the swatches named `old`, only the -/// pattern's own take the new name. +/// pattern's own take the new name. The paints are renamed wherever [`forget_pattern`] clears them. fn rename_pattern_uses(d: &mut Document, old: &str, new: &str) { - let fix = |p: &mut Paint| { - if let Paint::Pattern { pattern, .. } = p - && pattern == old - { - *pattern = new.to_string(); - } - }; - for sw in d.swatches.iter_mut().chain(d.swatch_groups.iter_mut().flat_map(|g| g.swatches.iter_mut())) { + for sw in d.swatches_iter_mut() { if sw.name == old && pattern_name(&sw.paint).is_some_and(|p| p == old) { sw.name = new.to_string(); } - fix(&mut sw.paint); } if let Some(pe) = &mut d.pattern_edit && pe.pattern == old { pe.pattern = new.to_string(); } - let ids = nodes_using(d, Some(old)); - for id in ids { - if let Some(n) = d.node_mut(id) { - for it in n.appearance.items.iter_mut() { - match it { - vectorcraft_doc::AppearanceItem::Fill(f) => fix(&mut f.paint), - vectorcraft_doc::AppearanceItem::Stroke(s) => fix(&mut s.paint), - } - } - } - } -} - -fn nodes_using(d: &Document, name: Option<&str>) -> Vec { - let mut ids = vec![]; - d.walk(|n| { - if pattern::uses_pattern(n, name) { - ids.push(n.id); - } - }); - ids + super::swatch::map_all_paints(d, &mut pattern_paints(old, Some(new))); } fn pattern_delete(s: &mut Session, p: &Value) -> Result { @@ -604,29 +658,8 @@ fn pattern_delete(s: &mut Session, p: &Value) -> Result { if editing(s).is_some_and(|e| e.pattern == name) { return Err(bad(C, "finish editing the pattern first")); } - let n = s.edit("Delete Pattern", |d, _| { - d.patterns.retain(|p| p.name != name); - let is_it = |sw: &vectorcraft_color::Swatch| matches!(&sw.paint, Paint::Pattern { pattern, .. } if *pattern == name); - d.swatches.retain(|sw| !is_it(sw)); - for g in &mut d.swatch_groups { - g.swatches.retain(|sw| !is_it(sw)); - } - let ids = nodes_using(d, Some(&name)); - for id in &ids { - if let Some(n) = d.node_mut(*id) { - for it in n.appearance.items.iter_mut() { - let p = match it { - vectorcraft_doc::AppearanceItem::Fill(f) => &mut f.paint, - vectorcraft_doc::AppearanceItem::Stroke(s) => &mut s.paint, - }; - if matches!(p, Paint::Pattern { pattern, .. } if *pattern == name) { - *p = Paint::None; - } - } - } - } - Ok(ids.len()) - })?; + let n = s.edit("Delete Pattern", |d, _| Ok(forget_pattern(d, &name)))?; + map_new_art_paints(s, &mut pattern_paints(&name, None))?; Ok(json!({ "unpainted": n })) } diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 5d56a2b646..36444878ef 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -6,11 +6,13 @@ //! `link` ([`super::links`]). //! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options //! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`). -//! - An EMF or WMF picture becomes one group, clipped to its frame (`crop: "crop"`) or bounded by -//! its art (`crop: "bounding"`). +//! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or +//! bounded by its art (`crop: "bounding"`). //! - An EPS file (or a PostScript .ai) becomes one group, clipped to its bounding box or bounded by //! its art: the document an EPS file of ours carries, else what its PostScript draws, else its //! preview ([`fileio::load`]). +//! - A DCS file, an EPS file with one program per printing plate, becomes one linked image of its +//! plates ([`dcs`]); it is never embedded. //! - A PDF/.ai/.ait page or a native document's artboard becomes one group, clipped to the page //! (`crop: "crop"`; a PDF page's `art`, `trim`, `bleed` or `media` box too) or bounded by its art //! (`crop: "bounding"`). With Link, a PDF/.ai/.ait page placed from a file becomes a placed @@ -32,6 +34,7 @@ //! `place` tool) with several files, which emits one `file.place` per click or drag. pub(crate) mod adopt; +pub(crate) mod dcs; mod doc; pub(crate) mod document; pub(crate) mod docx; @@ -69,7 +72,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF (clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file placed in a clip group, which the Links commands take}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -78,7 +81,7 @@ pub fn specs() -> Vec { "Placed File Info", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…} (both as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", + "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…} (both as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", always, info ), @@ -114,6 +117,8 @@ enum Art { /// A VectorCraft document or a PDF/.ai page placed linked: the file read, the link, and /// whether the art's bounds (not the artboard or page) are shown. Document(document::Source, LinkInfo, bool), + /// A DCS file: one linked image of its plates, clipped by its clipping path ([`dcs`]). + Dcs(Box), Vector { /// The loaded document: the source of the art's resources. src: Box, @@ -205,6 +210,15 @@ fn load(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Result) -> Node { }; Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))) } + Art::Dcs(a) => { + let a = *a; + super::links::store_image(d, &a.img.key, a.img.blob, link.is_some()); + dcs::add_spot_swatches(d, &a.spots); + let im = + ImageObject { key: a.img.key, width: a.img.width, height: a.img.height, xf: a.xf, link, placement: Default::default(), pixels: None }; + let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + match a.clip { + Some(c) => { + let children = vec![Arc::new(d.reid(&c)), Arc::new(image)]; + Node::new(d.alloc_id(), NodeKind::Group { children, clip: true }) + } + None => image, + } + } Art::Text(t) => Node::new(d.alloc_id(), NodeKind::Text(Box::new(text::area_text(t, l.natural, &d.setup)))), Art::Document(s, link, bounding) => document::node(d, &s, link, bounding), Art::Vector { src, mut nodes, clip } => { @@ -506,9 +535,13 @@ impl PlaceJob { pub fn read(self) -> Result { let mut loaded = load(&self.params, PLACE, self.target, true)?; let linked = loaded.link.is_some() && bool_or(&self.params, "link", true); - if let Art::Image(img) = &mut loaded.art { - let unread = super::links::kept_unread(&img.blob.bytes); - img.blob = super::links::readable_and_kept(img.blob.clone(), unread, linked)?; + match &mut loaded.art { + Art::Image(img) => { + let unread = super::links::kept_unread(&img.blob.bytes); + img.blob = super::links::readable_and_kept(img.blob.clone(), unread, linked)?; + } + Art::Dcs(a) => a.img.blob = super::links::readable(a.img.blob.clone(), false, true)?, + _ => {} } Ok(PlaceRead { job: self, loaded }) } @@ -628,7 +661,11 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { let below = st.current_layer().or_else(|| parent.and_then(|p| st.doc.layer_of(p))); let link = loaded.link.take().filter(|_| bool_or(p, "link", true)); let linked = link.is_some(); - let (name, format, warnings) = (loaded.name.clone(), loaded.format.id, std::mem::take(&mut loaded.warnings)); + let (name, format, mut warnings) = (loaded.name.clone(), loaded.format.id, std::mem::take(&mut loaded.warnings)); + let dcs_clipped = matches!(&loaded.art, Art::Dcs(a) if a.clip.is_some()); + if let Art::Dcs(a) = &loaded.art { + warnings.extend(dcs::swatch_notes(&st.doc, &a.spots)); + } let (id, size) = s.edit("Place", |d, sel| { let node = transformed(build(d, loaded, link), m); let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default(); @@ -650,9 +687,18 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { } Ok((id, size)) })?; - Ok( - json!({ "ids": [id.0], "name": name, "format": format, "linked": linked, "width": size.width(), "height": size.height(), "warnings": warnings }), - ) + let mut out = json!({ "ids": [id.0], "name": name, "format": format, "linked": linked, "width": size.width(), "height": size.height(), "warnings": warnings }); + // A DCS file clipped by its clipping path: its image, which the Links commands take. + if dcs_clipped { + let image = s.doc()?.doc.node(id).and_then(|n| match &n.kind { + NodeKind::Group { children, clip: true } => children.get(1).filter(|c| matches!(c.kind, NodeKind::Image(_))).map(|c| c.id), + _ => None, + }); + if let Some(image) = image { + out["image"] = json!(image.0); + } + } + Ok(out) } /// The artboard under `at` (its edges included, [`Document::artboard_holding`]), else the first. @@ -750,10 +796,14 @@ fn read_queue(p: Value, queued: Vec) -> Result { // so that drawing it does not decode the file again. let checked = load(&q, QUEUE, None, false).and_then(|mut l| { let linked = l.link.is_some() && bool_or(&q, "link", true); - if let Art::Image(img) = &mut l.art { - let unread = super::links::kept_unread(&img.blob.bytes); - let check = if thumbnail.is_some() { super::links::readable_and_kept } else { super::links::readable }; - img.blob = check(img.blob.clone(), unread, linked)?; + match &mut l.art { + Art::Image(img) => { + let unread = super::links::kept_unread(&img.blob.bytes); + let check = if thumbnail.is_some() { super::links::readable_and_kept } else { super::links::readable }; + img.blob = check(img.blob.clone(), unread, linked)?; + } + Art::Dcs(a) => a.img.blob = super::links::readable(a.img.blob.clone(), false, true)?, + _ => {} } Ok(l) }); @@ -871,6 +921,15 @@ pub fn read_info(p: &Value) -> Result { out["ppi"] = json!([x, y]); out["colorMode"] = json!(color_mode(&img.blob.bytes)); } + if let Art::Dcs(a) = &l.art { + let (x, y) = a.img.ppi.unwrap_or((72.0, 72.0)); + out["pixelWidth"] = json!(a.img.width); + out["pixelHeight"] = json!(a.img.height); + out["ppi"] = json!([x, y]); + out["colorMode"] = json!("CMYK"); + let plates: Vec = a.img.blob.separated().map(|s| s.plates.iter().map(|p| p.name.clone()).collect()).unwrap_or_default(); + out["plates"] = json!(plates); + } if let Some(px) = p.get("thumbnail").and_then(Value::as_f64) { out["thumbnailBase64"] = json!(thumbnail_png(l, px)?); } 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/place/dcs.rs b/crates/engine/src/cmd/place/dcs.rs new file mode 100644 index 0000000000..b540221a23 --- /dev/null +++ b/crates/engine/src/cmd/place/dcs.rs @@ -0,0 +1,132 @@ +//! DCS files (`file.place` with Link): an EPS file with one program per printing plate +//! ([`vectorcraft_eps::dcs`]). It is placed as one linked image whose plates are kept with its +//! pixels ([`vectorcraft_doc::separated`]): the screen and composite output show the plates mixed +//! into CMYK, and print separations put each plate on its own ink. Its spot plates become spot +//! swatches, and the clipping path its composite is drawn through clips it. A DCS file can't be +//! opened or embedded (Embed, Place without Link): the image stays linked to its file, which the +//! Links commands read again ([`raster`]). + +use vectorcraft_color::swatch::Swatch; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::separated::PlateFile; +use vectorcraft_doc::{Document, ImageBlob, Node, NodeKind}; +use vectorcraft_geom::{Affine, Rect}; + +use super::super::fileio::{self, RasterImage}; +use super::super::{EngineError, Result}; + +/// The largest plate file read (bytes). +const MAX_PLATE_FILE: u64 = 1 << 30; + +/// What refuses to open or embed a DCS file. +pub(crate) const LINK_ONLY: &str = "DCS files can only be placed linked: use File › Place with Link on"; + +/// A DCS file read for placing. +pub(crate) struct DcsArt { + pub img: RasterImage, + /// The image's pixels onto the file's page (its bounding box, top-left at the origin). + pub xf: Affine, + pub page: Rect, + /// The clipping path the composite is drawn through, on the page. + pub clip: Option, + /// The spot plates' inks and their process equivalents. + pub spots: Vec<(String, [f32; 4])>, + pub warnings: Vec, +} + +/// Is `bytes` a DCS file (an EPS file naming its plates)? +pub(crate) fn is_dcs(bytes: &[u8]) -> bool { + vectorcraft_eps::dcs::read(bytes).is_some() +} + +/// DCS file `bytes`, read from `path` (when there is one: plate files of their own are found in its +/// folder), with every plate. +pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result { + let dcs = vectorcraft_eps::dcs::read(bytes).ok_or_else(|| EngineError::Other("not a DCS file".into()))?; + let mut files = vec![]; + let mut file = |name: &str| plate_file(path, name, &mut files); + let p = vectorcraft_eps::dcs::place(bytes, &dcs, &mut file).map_err(EngineError::Other)?; + // The clipping path in the image's pixel space, where the Links commands put it again; the + // image keeps it, so they know a clip group of that path as the file's. + let to_pixels = (p.xf.determinant().abs() > 1e-12).then(|| p.xf.inverse()); + let clip = match (&p.clip, to_pixels) { + (Some(Node { kind: NodeKind::Path { path, .. }, .. }), Some(inv)) => Some(path.transformed(inv)), + _ => None, + }; + let blob = ImageBlob::separated_tiff_clipped(&p.separated, p.ppi, &files, clip.as_ref()) + .ok_or_else(|| EngineError::Other("the plates can't be kept".into()))?; + let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip }; + let spots = p.separated.spots().map(|s| (s.name.clone(), s.cmyk)).collect(); + Ok(DcsArt { img, xf: p.xf, page: p.page, clip: p.clip, spots, warnings: p.warnings }) +} + +/// A linked file's image, as the Links commands read it again: a DCS file's plates +/// ([`read`]), else the image file ([`fileio::raster_image`]). +pub(crate) fn raster(bytes: &[u8], path: Option<&str>) -> Result { + if is_dcs(bytes) { read(bytes, path).map(|a| a.img) } else { fileio::raster_image(bytes) } +} + +/// The path of the plate file a DCS file at `main` names `name`: the file of that name (its last +/// component, of any system's path) in `main`'s folder, with that name. +fn plate_path(main: Option<&str>, name: &str) -> std::result::Result<(String, String), String> { + let base = name.rsplit(['/', '\\', ':']).next().unwrap_or(name); + let folder = main.map(std::path::Path::new).and_then(std::path::Path::parent); + let Some(folder) = folder.filter(|_| !base.is_empty()) else { + return Err(format!("`{name}` is a file of its own, which can only be found next to the DCS file's path")); + }; + Ok((folder.join(base).to_string_lossy().into_owned(), base.to_string())) +} + +/// The path of the plate file named `name` that the DCS file at `main` (a path as a link keeps +/// it) was read with ([`plate_path`]); `None` when `main` has no folder. +pub(crate) fn plate_file_path(main: &str, name: &str) -> Option { + plate_path(Some(main), name).ok().map(|(path, _)| path) +} + +/// The plate file a DCS file at `main` names `name` ([`plate_path`]), noted in `files` as it is now. +fn plate_file(main: Option<&str>, name: &str, files: &mut Vec) -> std::result::Result, String> { + let (path, base) = plate_path(main, name)?; + match fileio::file_stamp(&path) { + None => Err(format!("`{base}` is not in the DCS file's folder")), + Some((size, _)) if size > MAX_PLATE_FILE => Err(format!("`{base}` is larger than {} MB", MAX_PLATE_FILE >> 20)), + Some((size, modified)) => { + let bytes = fileio::read_file(&path).map_err(|e| e.to_string())?; + files.push(PlateFile { name: base, size, modified: modified.unwrap_or(0) }); + Ok(bytes) + } + } +} + +/// Whether one of `files`, the plate files of their own a separated image was read from +/// ([`ImageBlob::plate_files`]), next to the DCS file at `main`, is gone or changed since. +pub(crate) fn plate_files_changed(files: &[PlateFile], main: &str) -> bool { + files.iter().any(|f| { + let stamp = plate_path(Some(main), &f.name).ok().and_then(|(path, _)| fileio::file_stamp(&path)); + stamp.is_none_or(|(size, modified)| size != f.size || modified.unwrap_or(0) != f.modified) + }) +} + +/// Add `spots` to `d` as spot swatches, each whose name no swatch has, in its process equivalent. +pub(crate) fn add_spot_swatches(d: &mut Document, spots: &[(String, [f32; 4])]) { + for (name, [c, m, y, k]) in spots { + if d.swatch(name).is_none() { + d.swatches.push(Swatch { name: name.clone(), paint: Paint::solid(Color::cmyk(*c, *m, *y, *k)), global: true, spot: true }); + } + } +} + +/// A warning for each of `spots` whose name a swatch of `d` already has that isn't a spot color in +/// the same process equivalent: the document's swatch stays, and the plate prints by it. +pub(crate) fn swatch_notes(d: &Document, spots: &[(String, [f32; 4])]) -> Vec { + let mut out = vec![]; + for (name, cmyk) in spots { + let Some(sw) = d.swatch(name) else { continue }; + let same = sw.spot + && matches!(sw.paint.color(), Some(Color::Cmyk { c, m, y, k }) if [c, m, y, k].iter().zip(cmyk).all(|(a, b)| (a - b).abs() < 0.005)); + if !same { + let how = if sw.spot { "a different color" } else { "a process color, so the plate prints as process inks" }; + out.push(format!("the document's swatch `{name}` is kept: it is {how}")); + } + } + out +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 1aa2e8c1ba..febdf07e97 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", @@ -524,6 +528,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.same.textStrokeColor", "select.segments", "select.set", + "select.storedPath", "select.toggle", "select.update", "shape.arc", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index c605cd39f3..a73485f4fa 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -212,6 +212,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("fontNamesInEnglish", "Type", "Options", "Show Font Names in English", bool), p!("autoSizeAreaType", "Type", "Options", "Auto Size New Area Type", bool), p!("fontPreview", "Type", "Options", "Enable in-menu font previews", bool), + p!("fontSamplesOnWhite", "Type", "Options", "Show samples on white", bool), p!("fontPreviewSize", "Type", "Options", "Font Preview Size", choice(&[("small", "Small"), ("medium", "Medium"), ("large", "Large")])), p!("recentFontsCount", "Type", "Options", "Number of Recent Fonts", int(1, 15)), p!("missingGlyphProtection", "Type", "Options", "Enable Missing Glyph Protection", bool), diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 9fe4665a5c..628facc1c3 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -112,6 +112,9 @@ fn preview(s: &mut Session, p: &Value) -> Result { super::printadvanced::flattener(C, &set, &s.prefs.flattener_presets)?; let mut pv = vectorcraft_pdf::preview(doc, &set).map_err(|e| pdf_error(C, e))?; pv.warnings.extend(type_warnings(doc, set.print_layers, &areas(&pv))); + // What the job loses comes first, then the notes on the options. + let settings = std::mem::take(&mut pv.setting_notes); + pv.warnings.extend(settings); let mut v = serde_json::to_value(pv).map_err(|e| EngineError::Other(e.to_string()))?; v["settings"] = to_json(&set)?; Ok(v) @@ -199,7 +202,9 @@ fn print(s: &mut Session, p: &Value) -> Result { let mut r = vectorcraft_pdf::print(printed, &PrintOptions { settings: set, for_printer: bool_or(p, "forPrinter", false), ..Default::default() }) .map_err(|e| pdf_error(PRINT, e))?; + // What the job loses comes first, then the notes on the options. r.warnings.extend(typed); + r.warnings.extend(r.setting_notes); return write_or_return(path, &r.bytes, json!({ "pages": r.pages, "format": "pdf", "warnings": r.warnings })); } let level = match p.get("level").filter(|v| !v.is_null()) { @@ -209,12 +214,13 @@ fn print(s: &mut Session, p: &Value) -> Result { } None => Level::default(), }; - let mut warnings = vec![]; + // What the job loses, then the notes on the options: a reply lists them in that order. + let (mut warnings, mut setting_notes) = (vec![], vec![]); if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) { warnings.push("transparency is flattened into opaque art and images (PostScript has none): see flattenerPreset".to_string()); } if !set.color.profile.trim().is_empty() && set.output.mode == vectorcraft_pdf::OutputMode::Composite { - warnings.push("the printer profile converts the colours of PDF output: PostScript prints the document's colours".to_string()); + setting_notes.push("the printer profile converts the colours of PDF output: PostScript prints the document's colours".to_string()); } let flatness = (!set.graphics.auto_flatness).then_some(set.graphics.flatness); let plan = vectorcraft_pdf::plan(prepared.as_ref().unwrap_or(doc), &PrintOptions { settings: set, postscript: true, ..Default::default() }) @@ -244,5 +250,11 @@ fn print(s: &mut Session, p: &Value) -> Result { } let areas: Vec = plan.sheets.iter().filter_map(|sh| on_page(sh.area, sh.view * sh.place, sh.size)).collect(); warnings.extend(type_warnings(&full, which, &areas)); + for w in plan.setting_notes.iter().chain(&out.setting_notes) { + if !warnings.contains(w) && !setting_notes.contains(w) { + setting_notes.push(w.clone()); + } + } + warnings.extend(setting_notes); write_or_return(path, &out.bytes, json!({ "pages": plan.order.len(), "format": "postscript", "warnings": warnings })) } 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..ac9ca365f4 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; @@ -48,6 +49,15 @@ pub fn specs() -> Vec { has_doc, set ), + cmd!( + "select.storedPath", + "Select Path", + [], + None, + "{id: object id, fingerprint: text (\"v1:\" and 16 lowercase hex digits)} the Actions panel's Select Path step: select only the path or compound path `id` when its fingerprint (a hash of its kind, fill rule and anchors, its members' for a compound path) is still `fingerprint` and it can be selected: not hidden or locked, nor in a hidden or locked layer or group, a template layer or on a locked artboard, and inside the isolated object in isolation mode. A missing object, another kind of object, a path whose kind, fill rule or anchors changed, or one that cannot be selected is an error, and the selection stays as it was → {count, ids} (the resulting selection)", + has_doc, + stored_path + ), cmd!( "select.add", "Add to Selection", @@ -103,6 +113,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", @@ -439,6 +458,150 @@ fn selection_result(s: &Session) -> Result { Ok(json!({ "count": selection.len(), "ids": selection.objects })) } +/// The prefix of every fingerprint [`path_fingerprint`] gives: the version of its hash. +const FINGERPRINT_PREFIX: &str = "v1:"; + +/// FNV-1a (64 bits) over the bytes written to it, starting from the offset basis. +pub(crate) struct Fnv(pub(crate) u64); + +impl Default for Fnv { + fn default() -> Self { + Self(0xcbf2_9ce4_8422_2325) + } +} + +impl std::io::Write for Fnv { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0 = buf.iter().fold(self.0, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// The fingerprint of the path or compound path `n` that `select.storedPath` compares: FNV-1a (64 +/// bits) over a kind byte, the fill rule and the anchors of the path, or of each member of the +/// compound path in order, as JSON, written as [`FINGERPRINT_PREFIX`] and 16 lowercase hex digits. +/// None for any object [`is_storable_kind`] does not take. +pub fn path_fingerprint(n: &Node) -> Option { + fn feed(h: &mut Fnv, n: &Node) -> Option<()> { + use std::io::Write; + match &n.kind { + NodeKind::Path { path, rule, .. } => { + h.write_all(b"P").ok()?; + serde_json::to_writer(&mut *h, rule).ok()?; + serde_json::to_writer(&mut *h, path).ok() + } + NodeKind::Compound { children, rule } => { + h.write_all(b"C").ok()?; + serde_json::to_writer(&mut *h, rule).ok()?; + h.write_all(&(children.len() as u64).to_le_bytes()).ok()?; + children.iter().try_for_each(|c| feed(h, c)) + } + _ => None, + } + } + if !is_storable_kind(n) { + return None; + } + let mut h = Fnv::default(); + feed(&mut h, n)?; + Some(format!("{FINGERPRINT_PREFIX}{:016x}", h.0)) +} + +/// Whether `n` is an object a Select Path step can store: a path that is not a guide, or a compound +/// path whose members all are. +fn is_storable_kind(n: &Node) -> bool { + let path = |n: &Node| matches!(n.kind, NodeKind::Path { guide: false, .. }); + match &n.kind { + NodeKind::Compound { children, .. } => children.iter().all(|c| path(c)), + _ => path(n), + } +} + +/// The `id` and `fingerprint` of `select.storedPath`'s params `p`, or why they are not ones: an +/// object with only a non-negative whole `id` and a `fingerprint` that [`path_fingerprint`] could give. +pub fn stored_path_params(p: &Value) -> std::result::Result<(NodeId, &str), String> { + let o = p.as_object().ok_or("`params` must be an object")?; + if let Some(key) = o.keys().find(|k| !matches!(k.as_str(), "id" | "fingerprint")) { + let keys = "id, fingerprint"; + return Err(format!("unknown parameter `{key}`; the command takes: {keys}")); + } + let value = o.get("id").unwrap_or(&Value::Null); + let id = value.as_u64().map(NodeId).ok_or_else(|| format!("invalid object id {value}: expected a non-negative integer"))?; + let fingerprint = o.get("fingerprint").and_then(Value::as_str).unwrap_or_default(); + let hex = fingerprint.strip_prefix(FINGERPRINT_PREFIX).unwrap_or_default(); + if hex.len() != 16 || !hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) { + return Err("`fingerprint` must be \"v1:\" and 16 lowercase hex digits".into()); + } + Ok((id, fingerprint)) +} + +/// Why the object `id` of `st` cannot be the path of a Select Path step: it is not there, is not a +/// path (not a guide) or compound path ([`is_storable_kind`]), is a member of a compound path, cannot +/// be selected ([`is_selectable`]), or is on a locked artboard, in isolation mode too. +fn storable_path(st: &DocState, id: NodeId) -> std::result::Result<(), String> { + let value = id.0; + let n = st.doc.node(id).ok_or_else(|| format!("no such object id {value}"))?; + let in_compound = st.doc.parent_of(id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); + if !is_storable_kind(n) || in_compound { + return Err(WHOLE_PATH.into()); + } + // In isolation mode `is_selectable` does not look at the locked artboards, so they are checked here too. + let locks = st.doc.locked_artboards(); + if !is_selectable(&st.doc, st.isolation, &locks, id) || locks.holds_id(id) { + return Err("the path is hidden or locked, or cannot be selected here".into()); + } + Ok(()) +} + +/// What [`storable_selection`] asks for when the selection is not a whole path or compound path. +const WHOLE_PATH: &str = "select one whole path or compound path"; + +/// The one object selected in `st` when it can be the path of a Select Path step: a whole path or +/// compound path that can be selected ([`storable_path`]). An error for no selection, several +/// objects, a path with ruler guides, anchors or segments of a path alone, a group, type or any other object, a guide, or a +/// member of a compound path. It does not hash the path, so menus can ask it every frame. +pub fn storable_selection(st: &DocState) -> std::result::Result { + let sel = &st.selection; + let id = match sel.objects.as_slice() { + [] => return Err("select a path".into()), + [id] if sel.guides.is_empty() => *id, + _ => return Err("select only one path".into()), + }; + if sel.anchors.get(&id).is_some_and(|a| !a.is_empty()) || sel.segments.get(&id).is_some_and(|s| !s.is_empty()) { + return Err(WHOLE_PATH.into()); + } + storable_path(st, id)?; + Ok(id) +} + +/// The params of a `select.storedPath` step for the path selected in `st` ([`storable_selection`]): +/// `{id, fingerprint}`. +pub fn stored_path_step(st: &DocState) -> std::result::Result { + let id = storable_selection(st)?; + let fingerprint = st.doc.node(id).and_then(path_fingerprint).ok_or(WHOLE_PATH)?; + Ok(json!({ "id": id.0, "fingerprint": fingerprint })) +} + +/// `select.storedPath {id, fingerprint}`: selects only the path `id` when it is still the path the +/// step stored ([`path_fingerprint`]) and can be selected ([`storable_path`]); else an error, and +/// the selection stays as it was. +fn stored_path(s: &mut Session, p: &Value) -> Result { + const C: &str = "select.storedPath"; + let (id, fingerprint) = stored_path_params(p).map_err(|e| bad(C, e))?; + let st = s.doc()?; + let value = id.0; + let n = st.doc.node(id).ok_or_else(|| bad(C, format!("no such object id {value}")))?; + if path_fingerprint(n).as_deref() != Some(fingerprint) { + return Err(bad(C, format!("object {value} is not the stored path: it changed, or the document is another one"))); + } + storable_path(st, id).map_err(|e| bad(C, e))?; + s.select(|_, sel| sel.set([id]))?; + selection_result(s) +} + fn key(s: &mut Session, p: &Value) -> Result { let id = p.get("id").map(|value| checked_id(s, value, "select.key")).transpose()?; let guide = match p.get("guide").filter(|v| !v.is_null()) { @@ -730,6 +893,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/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 751313957f..22c1c0c929 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet, VecDeque}; use serde_json::{Value, json}; use vectorcraft_color::{Color, Gradient, GradientKind, GradientMethod, GradientStop, Paint, Swatch, SwatchGroup, tint_percent}; use vectorcraft_doc::pattern::pattern_paint; -use vectorcraft_doc::swatches::{LinkFn, color_name, map_node_solid_paints, node_colors}; +use vectorcraft_doc::swatches::{LinkFn, PaintFn, color_name, map_node_paints, map_node_solid_paints, node_colors}; use vectorcraft_doc::{Document, NodeId}; use super::paint::paint_from; @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Select All Unused", ["Window", "Swatches"], None, - "{} → {names: [the swatches nothing uses, in panel order]}: a colour is used when a paint links to it or an unlinked paint, gradient stop or mesh point has its colour; a gradient when a gradient links to it or has its stops; a pattern when it fills or strokes anything (art, symbols, pattern tiles and graphic styles count). None is never listed", + "{} → {names: [the swatches nothing uses, in panel order]}: a colour is used when a paint links to it or an unlinked paint, gradient stop or mesh point has its colour; a gradient when a gradient links to it or has its stops; a pattern when it fills or strokes anything (art, symbols, pattern tiles and graphic styles count); a color, spot or process, when an image placed from a DCS file that the art shows has a spot plate of its name. None is never listed", has_doc, swatch_unused ), @@ -681,32 +681,16 @@ pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) { /// paint changed is merged into its entry ([`merge_stored`]), so fields the brush definition does /// not read are kept at every level. pub(super) fn map_swatch_links(d: &mut Document, f: &mut LinkFn) -> usize { - use vectorcraft_brush::{Brush, BrushKind, Colorization}; - let mut n = d.map_solid_paints(f); - // Each stored entry, its brush when it parses, the brush as written before the edit (only - // when its paint changed), and whether its paint changed. - let mut lib: Vec<(Value, Option, Value, bool)> = match d.unknown.get(vectorcraft_brush::DOC_KEY) { - Some(v) => v.as_array().into_iter().flatten().map(|e| (e.clone(), Brush::from_json(e.clone()).ok(), Value::Null, false)).collect(), - None => { - vectorcraft_brush::library(d).into_iter().map(|b| (serde_json::to_value(&b).unwrap_or_default(), Some(b), Value::Null, false)).collect() - } - }; - let mut in_brushes = 0; - for (_, b, base, changed) in lib.iter_mut() { - let Some(b) = b else { continue }; - let before_edit = serde_json::to_value(&*b).unwrap_or_default(); + use vectorcraft_brush::{BrushKind, Colorization}; + let n = d.map_solid_paints(f); + n + edit_brush_library(d, &mut |b| { let key = match b.kind.colorization() { Colorization::HueShift { key } => Some(key), _ => None, }; let before = key.map(|_| art_paint_colors(b.art())); - let in_brush = b.art_mut().into_iter().map(|art| map_node_solid_paints(art, f)).sum::(); - *changed = in_brush > 0; - if *changed { - *base = before_edit; - } - in_brushes += in_brush; - let (Some(key), Some(before)) = (key, before) else { continue }; + let in_brush = b.art_mut().into_iter().map(|art| map_node_solid_paints(art, &mut *f)).sum::(); + let (Some(key), Some(before)) = (key, before) else { return in_brush }; // Colors are compared by hex value, as `art_colors` (Brush Options' key colors) lists them. let same = |a: &Color, b: &Color| a.to_hex() == b.to_hex(); let after = art_paint_colors(b.art()); @@ -719,10 +703,47 @@ pub(super) fn map_swatch_links(d: &mut Document, f: &mut LinkFn) -> usize { BrushKind::Art(a) => &mut a.colorization, BrushKind::Scatter(s) => &mut s.colorization, BrushKind::Pattern(p) => &mut p.colorization, - BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => continue, + BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => return in_brush, }; *c = Colorization::HueShift { key }; } + in_brush + }) +} + +/// Apply a paint rewrite ([`Document::map_paints`]) to the document and to the art of the brushes +/// in its library ([`edit_brush_library`]). Returns the number of changed paints. +pub(super) fn map_all_paints(d: &mut Document, f: &mut PaintFn) -> usize { + let n = d.map_paints(f); + n + edit_brush_library(d, &mut |b| b.art_mut().into_iter().map(|art| map_node_paints(art, &mut *f)).sum()) +} + +/// Apply `edit` to each brush of the document's library, the stored entries or, with none stored, +/// the built-in library; `edit` returns how many paints of the brush's art it changed. The library +/// is stored again only when a brush's paint changed. Stored entries are stored again as they were +/// read, except that a brush whose paint changed is merged into its entry ([`merge_stored`]), so +/// fields the brush definition does not read are kept at every level. Returns the number of +/// changed paints. +fn edit_brush_library(d: &mut Document, edit: &mut dyn FnMut(&mut vectorcraft_brush::Brush) -> usize) -> usize { + use vectorcraft_brush::Brush; + // Each stored entry, its brush when it parses, the brush as written before the edit (only + // when its paint changed), and whether its paint changed. + let mut lib: Vec<(Value, Option, Value, bool)> = match d.unknown.get(vectorcraft_brush::DOC_KEY) { + Some(v) => v.as_array().into_iter().flatten().map(|e| (e.clone(), Brush::from_json(e.clone()).ok(), Value::Null, false)).collect(), + None => { + vectorcraft_brush::library(d).into_iter().map(|b| (serde_json::to_value(&b).unwrap_or_default(), Some(b), Value::Null, false)).collect() + } + }; + let mut in_brushes = 0; + for (_, b, base, changed) in lib.iter_mut() { + let Some(b) = b else { continue }; + let before_edit = serde_json::to_value(&*b).unwrap_or_default(); + let in_brush = edit(b); + *changed = in_brush > 0; + if *changed { + *base = before_edit; + } + in_brushes += in_brush; } if in_brushes > 0 { let lib = lib @@ -733,9 +754,8 @@ pub(super) fn map_swatch_links(d: &mut Document, f: &mut LinkFn) -> usize { }) .collect(); d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), Value::Array(lib)); - n += in_brushes; } - n + in_brushes } /// `new` (a definition as written after an edit) with the parts of `raw` (its stored entry) that @@ -988,8 +1008,28 @@ fn swatch_unused(s: &mut Session, _: &Value) -> Result { let colors: HashSet = colors.iter().filter_map(color_key).collect(); let patterns: HashSet<&String> = patterns.iter().collect(); let gradients: HashSet = gradients.iter().filter_map(gradient_key).collect(); + // The spot inks the images placed from DCS files have plates for: their swatches print them. + // Only images the art shows count: a deleted one's pixels stay for undo. + let mut shown: HashSet<&str> = HashSet::new(); + for root in d + .layers + .iter() + .chain(d.symbols.iter().map(|s| &s.art)) + .chain(d.graph_designs.iter().map(|g| &g.art)) + .chain(d.patterns.iter().flat_map(|p| &p.art)) + { + vectorcraft_doc::swatches::walk_with_masks(root, &mut |n| { + if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { + shown.insert(im.key.as_str()); + } + }); + } + let plate_inks: HashSet = + shown.iter().filter_map(|k| d.images.get(*k)).flat_map(vectorcraft_doc::ImageBlob::spot_plates).map(|(name, _)| name).collect(); let used = |w: &Swatch| { gradient_links.contains(&w.name) + // A spot swatch prints the plate; a process one gives the color it prints as process. + || (w.paint.color().is_some() && plate_inks.contains(&w.name)) || match w.tint_of() { Some((base, tint)) => float_key(tint).is_some_and(|t| link_tints.contains(&(base, t))), None => link_names.contains(w.name.as_str()), diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index f5b79aaa84..e71948086f 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -2108,6 +2108,60 @@ fn new_type_is_composed_with_line_end_half_width_punctuation() { assert!(serde_json::to_value(&old).unwrap().get("mojikumi").is_none()); } +/// `text.setFormat {mojikumi}` takes each predefined Mojikumi set as one undo step, refuses any +/// other value without changing the type, and each set survives a native save and reopen and a +/// paragraph style that captures it. +#[test] +fn every_predefined_mojikumi_set_is_set_saved_and_carried_by_styles() { + use vectorcraft_doc::Mojikumi; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "「雅楽」。"})).unwrap()["id"].as_u64().unwrap(); + let para = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.para.clone(), + _ => panic!("text"), + }; + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let sets = [ + ("yakumonoHankaku", Mojikumi::YakumonoHankaku), + ("gyomatsuYakumonoHankaku", Mojikumi::GyomatsuYakumonoHankaku), + ("gyomatsuYakumonoZenkaku", Mojikumi::GyomatsuYakumonoZenkaku), + ("yakumonoZenkaku", Mojikumi::YakumonoZenkaku), + ("none", Mojikumi::None), + ("lineEndHalf", Mojikumi::LineEndHalf), + ]; + for (key, set) in sets { + s.execute("text.setFormat", &json!({"mojikumi": key})).unwrap(); + assert_eq!(para(&s).mojikumi, set, "{key}"); + let doc = s.doc().unwrap().doc.clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + match &back.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => assert_eq!(t.para.mojikumi, set, "{key} saved"), + _ => panic!("text"), + } + let style = format!("Spacing {key}"); + s.execute("paraStyle.new", &json!({"name": style, "attrs": {"mojikumi": key}})).unwrap(); + s.execute("text.setFormat", &json!({"mojikumi": if set == Mojikumi::None { "lineEndHalf" } else { "none" }})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": style, "id": id})).unwrap(); + assert_eq!(para(&s).mojikumi, set, "{key} from a paragraph style"); + } + // One undo step back to the set before. + s.execute("text.setFormat", &json!({"mojikumi": "yakumonoHankaku"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(para(&s).mojikumi, Mojikumi::LineEndHalf); + // A value that is no set, or not a string, is refused and leaves the type as it was. + s.execute("text.setFormat", &json!({"mojikumi": "gyomatsuYakumonoZenkaku"})).unwrap(); + for bad in [json!("YakumonoHankaku"), json!("lineEnd"), json!(""), json!(1)] { + assert!(s.execute("text.setFormat", &json!({"mojikumi": bad, "leftIndent": 12})).is_err(), "{bad}"); + let p = para(&s); + assert_eq!((p.mojikumi, p.left_indent), (Mojikumi::GyomatsuYakumonoZenkaku, 0.0), "{bad}"); + } + // A null value leaves the set as it is. + s.execute("text.setFormat", &json!({"mojikumi": null, "leftIndent": 12})).unwrap(); + let p = para(&s); + assert_eq!((p.mojikumi, p.left_indent), (Mojikumi::GyomatsuYakumonoZenkaku, 12.0)); +} + #[test] fn vertical_point_type_keeps_its_anchor_on_the_column_centre_line() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index 617d9d944c..1e01c8f62e 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -4,12 +4,12 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{Node, NodeKind, Scaling}; +use vectorcraft_doc::{Node, NodeKind, OrientedBox, Scaling}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use super::edit::{outermost, selected_roots}; use super::{ - CommandSpec, NodeId, Result, Session, always, bad, bool_or, check_numbers, check_switches, checked_ids_param, cmd, color_value, f64_or, + CommandSpec, NodeId, Result, Session, always, bad, bool_or, check_numbers, check_switches, checked_ids_param, cmd, color_value, f64_or, f64_req, find_command, finite_numbers, has_doc, index, }; use crate::EngineError; @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Free Distort", [], None, - "{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), ids?} projective warp of anchors and handles; a linked opacity mask's art is warped with its object, an unlinked one stays", + "{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; a linked opacity mask's art is warped with its object, an unlinked one stays", has_doc, distort ), @@ -62,11 +62,14 @@ pub fn specs() -> Vec { pub struct Projective { m: [f64; 8], src: Rect, + /// Page → the frame `src` is measured in. + pre: Affine, } impl Projective { - /// Map `src`'s corners (TL, TR, BR, BL) onto `q`. - pub fn from_rect(src: Rect, q: [Point; 4]) -> Self { + /// Map the corners (TL, TR, BR, BL) of `src`, a box that may be turned, onto the page points `q`. + pub fn from_box(bx: OrientedBox, q: [Point; 4]) -> Self { + let src = bx.rect; let [p0, p1, p2, p3] = q; let (dx1, dx2, dx3) = (p1.x - p2.x, p3.x - p2.x, p0.x - p1.x + p2.x - p3.x); let (dy1, dy2, dy3) = (p1.y - p2.y, p3.y - p2.y, p0.y - p1.y + p2.y - p3.y); @@ -80,11 +83,12 @@ impl Projective { let b = p3.x - p0.x + h * p3.x; let d = p1.y - p0.y + g * p1.y; let e = p3.y - p0.y + h * p3.y; - Self { m: [a, b, p0.x, d, e, p0.y, g, h], src } + Self { m: [a, b, p0.x, d, e, p0.y, g, h], src, pre: bx.to_doc().inverse() } } pub fn apply(&self, p: Point) -> Point { let [a, b, c, d, e, f, g, h] = self.m; + let p = self.pre * p; let u = if self.src.width().abs() > 1e-12 { (p.x - self.src.x0) / self.src.width() } else { 0.0 }; let v = if self.src.height().abs() > 1e-12 { (p.y - self.src.y0) / self.src.height() } else { 0.0 }; let w = g * u + h * v + 1.0; @@ -152,17 +156,29 @@ fn distort(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "nothing to distort")); } + let angle = p.get("angle").filter(|v| !v.is_null()).map(|_| f64_req(p, "angle", C)).transpose()?.map_or(0.0, vectorcraft_geom::normalize_deg); let src = match p.get("from").filter(|v| !v.is_null()) { - None => s.doc()?.doc.bounds_of(&ids, false).ok_or_else(|| bad(C, "nothing to distort"))?, + None if angle == 0.0 => OrientedBox::aligned(s.doc()?.doc.bounds_of(&ids, false).ok_or_else(|| bad(C, "nothing to distort"))?), + None => { + // The selection's bounds square to the turned frame. + let doc = &s.doc()?.doc; + let (symbols, to_local) = (doc.symbol_boxes(), OrientedBox { angle, rect: Rect::ZERO }.to_doc().inverse()); + let rect = ids + .iter() + .filter_map(|id| doc.node(*id)) + .fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.bounds_in(&symbols, to_local, false))); + OrientedBox { angle, rect: rect.ok_or_else(|| bad(C, "nothing to distort"))? } + } Some(v) => { let [x0, y0, x1, y1] = finite_numbers(v).ok_or_else(|| bad(C, "from must be [x0, y0, x1, y1]"))?; - Rect::new(x0, y0, x1, y1) + OrientedBox { angle, rect: Rect::new(x0, y0, x1, y1) } } }; - if !src.width().is_finite() || !src.height().is_finite() || src.width().abs() < 1e-9 || src.height().abs() < 1e-9 { + let r = src.rect; + if !r.width().is_finite() || !r.height().is_finite() || r.width().abs() < 1e-9 || r.height().abs() < 1e-9 { return Err(bad(C, "cannot distort a zero-size or non-finite bounding box")); } - let pr = Projective::from_rect(src, [tl, tr, br, bl]); + let pr = Projective::from_box(src, [tl, tr, br, bl]); s.edit("Free Distort", |d, _| { for id in &ids { if let Some(n) = d.node_mut(*id) { diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index cc545b179f..3ab6a7dcb8 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -27,7 +27,8 @@ pub struct HistoryEntry { pub(crate) named: Option, /// A number no other step takes ([`History::step`]). serial: u64, - /// Original and converted new-art colors, only for steps that change document color mode. + /// Original and changed new-art paints, only for steps that change them: a document color mode + /// change, and a pattern Cancel, Delete or rename that clears or renames a pattern paint. pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, /// Owned new-art snapshots included in both directional estimates. color_mode_bytes: usize, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 214d3279f8..c5b39bcd8e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -32,6 +32,7 @@ pub use cmd::distortcmds::perspective_click; pub use cmd::params::{check_keys, check_params}; pub use cmd::pathops::auto_simplify_level; pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; +pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step}; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use cmd::{EyedropperOptions, PathfinderOptions}; pub use journal::Journal; @@ -218,9 +219,10 @@ pub struct Session { /// groups: for each step, the documents ([`DocState::uid`]) whose undo groups it belongs to, and /// the index of the document it left active when it changed the active document. pub(crate) batch_steps: Option, Option)>>, - /// After `command.batch` kept a color-mode step's new-art colors, until the top-level command - /// has inherited the selection's appearance: the documents ([`DocState::uid`]) whose newest - /// history step takes the colors the batch finally left. + /// After `command.batch` kept a color-mode step's new-art colors, or a pattern command recorded + /// the new-art paints it changed, until the top-level command has inherited the selection's + /// appearance: the documents ([`DocState::uid`]) whose newest history step takes the colors the + /// command finally left. pub(crate) batch_paint_docs: Vec, /// The composite fonts (lowercase names) that the open documents defined when the font /// database was last brought in step with them ([`cmd::compositefonts::sync`]). diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rs index 747ce91545..c524f056a5 100644 --- a/crates/engine/src/link_watch.rs +++ b/crates/engine/src/link_watch.rs @@ -184,7 +184,9 @@ impl Session { if changed.is_empty() { return Ok(none()); } - let ids: Vec = changed.iter().flat_map(|(_, ids)| ids.iter().copied()).collect(); + // Each once: a DCS file and its plate files list the same objects. + let mut seen = HashSet::new(); + let ids: Vec = changed.iter().flat_map(|(_, ids)| ids.iter().copied()).filter(|id| seen.insert(*id)).collect(); let mode = if update { "automatically" } else { self.prefs.update_links.as_str() }; match mode { "automatically" => { diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 52c4b7a4f2..05ef5e84f5 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -104,6 +104,9 @@ pub struct Prefs { pub font_names_in_english: bool, pub auto_size_area_type: bool, pub font_preview: bool, + /// Type › Show samples on white: the font menus draw each family's sample in dark type on a + /// white area in every brightness (off by default). + pub font_samples_on_white: bool, pub font_preview_size: String, pub recent_fonts_count: u32, pub missing_glyph_protection: bool, @@ -427,6 +430,7 @@ impl Default for Prefs { font_names_in_english: true, auto_size_area_type: false, font_preview: true, + font_samples_on_white: false, font_preview_size: s("medium"), recent_fonts_count: 10, missing_glyph_protection: true, 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..3d0d9ba1c6 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); @@ -288,7 +290,10 @@ impl Session { st.revision += 1; } st.doc = it.doc.clone(); - let restore_paint = cmd == "command.batch" || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch"); + // A batch, or a preview that changed the new-art paints (a pattern rename), started from + // the paints the interaction began with. + let restore_paint = + cmd == "command.batch" || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some(); let paint = it.paint.clone(); it.preview_paint = None; it.color_mode_paints = None; @@ -421,7 +426,7 @@ impl Session { if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) - .filter(|it| it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch")) + .filter(|it| it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some()) .map(|it| it.paint.clone()) { self.paint = paint; @@ -431,6 +436,9 @@ impl Session { st.undo_interaction(); // Guides locked and slices locked or hidden during the interaction stay deselected. deselect_hidden(&menu, &st.doc, &mut st.selection); + // With New Art Has Basic Appearance off, new art takes the appearance of the selection as + // the document has it again, not as a preview left it. + self.inherit_new_art(); Ok(()) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d3d6046f89..aea802b3d1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -45,6 +45,7 @@ mod containers; mod css; mod cut; mod dashalign; +mod dcs; mod distort; mod docsetup; mod document_move; @@ -176,6 +177,7 @@ mod smartguides; mod smooth_path; mod spelling; mod store; +mod stored_path; mod strokegeom; mod strokegradient; mod strokereach; 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/bboxrotate.rs b/crates/engine/src/tests/bboxrotate.rs index 0d9188243c..8907b21cc0 100644 --- a/crates/engine/src/tests/bboxrotate.rs +++ b/crates/engine/src/tests/bboxrotate.rs @@ -104,6 +104,92 @@ fn handles_turn_with_the_object_and_scale_along_its_axes() { assert!(near(selection_box(&s).rect.width(), 100.0)); } +/// Presses, drags and lets go with the current tool along `pts`, holding `mods`. +fn drag_with(s: &mut Session, pts: &[Point], mods: Mods) { + let v = ViewInfo::default(); + let kinds = std::iter::once(PointerKind::Down).chain(std::iter::repeat_n(PointerKind::Drag, pts.len().saturating_sub(2))); + for (kind, p) in kinds.chain([PointerKind::Up]).zip(pts) { + s.pointer(&PointerEvent::new(kind, p.x, p.y).with_mods(mods), v).unwrap(); + } +} + +/// The anchors of path `id`, on the page. +fn anchors(s: &Session, id: NodeId) -> Vec { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, an)| an.p).collect() +} + +fn has_point(pts: &[Point], p: Point) -> bool { + pts.iter().any(|q| q.distance(p) < 1e-6) +} + +#[test] +fn free_transform_handles_turn_with_the_object_and_scale_along_its_axes() { + let mut s = session(); + let a = turned_rect(&mut s); + let b = selection_box(&s); + // The Right handle of the turned box, dragged 50 pt further out along the object's own x axis. + let right = b.to_doc() * Handle::Right.pos(b.rect); + let to = b.to_doc() * (Handle::Right.pos(b.rect) + vectorcraft_geom::Vec2::new(50.0, 0.0)); + let n = undo_len(&s); + s.select_tool("freeTransform", ViewInfo::default()).unwrap(); + drag_with(&mut s, &[right, to, to], Mods::default()); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Scale")); + // 150 × 50 along its own axes, still at exactly 45°, the left side where it was. + assert_eq!(angle(&s, a), b.angle); + let nb = selection_box(&s); + assert!(near(nb.rect.width(), 150.0) && near(nb.rect.height(), 50.0), "{nb:?}"); + let left = |b: &OrientedBox| b.to_doc() * Handle::Left.pos(b.rect); + assert!(left(&nb).distance(left(&b)) < 1e-6); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(selection_box(&s).rect.width(), 100.0)); +} + +#[test] +fn free_transform_shears_along_the_turned_side() { + let mut s = session(); + let a = turned_rect(&mut s); + let b = selection_box(&s); + let [tl, tr, br, bl] = b.corners(); + // Dragging the Top handle 20 pt along the object's own top side with Cmd held once the drag + // started (a Cmd press is the temporary Selection tool) slides that side along itself; the + // bottom side stays. + let top = b.to_doc() * Handle::Top.pos(b.rect); + let along = b.to_doc() * (Handle::Top.pos(b.rect) + vectorcraft_geom::Vec2::new(20.0, 0.0)); + let shift = along - top; + let v = ViewInfo::default(); + s.select_tool("freeTransform", v).unwrap(); + let cmd = Mods { cmd: true, ..Default::default() }; + for (kind, p, m) in [(PointerKind::Down, top, Mods::default()), (PointerKind::Drag, along, cmd), (PointerKind::Up, along, cmd)] { + s.pointer(&PointerEvent::new(kind, p.x, p.y).with_mods(m), v).unwrap(); + } + assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Shear")); + let pts = anchors(&s, a); + for p in [tl + shift, tr + shift, br, bl] { + assert!(has_point(&pts, p), "{p:?} not in {pts:?}"); + } +} + +#[test] +fn free_transform_distort_starts_from_the_turned_box() { + let mut s = session(); + let a = turned_rect(&mut s); + let b = selection_box(&s); + let [tl, tr, br, bl] = b.corners(); + s.select_tool("freeTransform", ViewInfo::default()).unwrap(); + s.set_tool_option("mode", &json!("distort")); + let to = br + vectorcraft_geom::Vec2::new(10.0, 20.0); + let n = undo_len(&s); + drag_with(&mut s, &[br, to, to], Mods::default()); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("object.distort")); + // The dragged corner of the turned box lands under the pointer; the other three stay. + let pts = anchors(&s, a); + for p in [tl, tr, to, bl] { + assert!(has_point(&pts, p), "{p:?} not in {pts:?}"); + } +} + #[test] fn transform_panel_sizes_follow_the_turned_box() { let mut s = session(); diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index c71014eb1c..e281b3ee04 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -462,6 +462,49 @@ fn a_colorized_missing_link_placeholder_is_not_flattened() { assert_eq!(colorize(&s, id), Some(Paint::solid(Color::rgb8(255, 0, 0))), "the image keeps its paint"); } +/// A fill color on a colorized image that shows the missing-link placeholder recolors the image, +/// as the Fill proxy shows its colorize paint, and adds no fill item. +#[test] +fn a_fill_color_recolors_a_colorized_missing_link_placeholder() { + let mut s = session(); + let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); + let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }); + s.edit("Colorize", |d, _| { + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + Ok(()) + }) + .unwrap(); + let appearance = s.doc().unwrap().doc.node(id).unwrap().appearance.clone(); + s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": [id.0]})).unwrap(); + assert_eq!(colorize(&s, id).and_then(|p| p.color()).map(|c| c.to_hex()), Some("#0000ff".into())); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance, appearance, "no fill item"); + assert_eq!(s.proxy_paints().0.color().map(|c| c.to_hex()), Some("#0000ff".into())); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(colorize(&s, id), Some(Paint::solid(Color::rgb8(255, 0, 0)))); +} + +/// The pixels behind the placeholder may have an alpha channel, so a missing-link image colorized +/// with a spot color takes another spot color, black or white, and refuses a process color. +#[test] +fn a_colorized_missing_link_placeholder_in_a_spot_color_refuses_a_process_color() { + let mut s = session(); + let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); + let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }); + s.execute("swatch.new", &json!({"name": "Ink 2", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); + s.edit("Colorize", |d, _| { + let ink = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 }; + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(ink)); + Ok(()) + }) + .unwrap(); + let before = colorize(&s, id); + let e = s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": [id.0]})).unwrap_err().to_string(); + assert!(e.contains("a process color can't colorize a grayscale image with transparency"), "{e}"); + assert_eq!(colorize(&s, id), before); + s.execute("paint.setFill", &json!({"swatch": "Ink 2", "ids": [id.0]})).unwrap(); + assert!(matches!(colorize(&s, id), Some(Paint::Solid { swatch: Some(w), .. }) if w == "Ink 2"), "{:?}", colorize(&s, id)); +} + #[test] fn flattened_colorized_image_shows_the_art_under_white_pixels() { let mut s = session(); diff --git a/crates/engine/src/tests/containers.rs b/crates/engine/src/tests/containers.rs index dd32135c18..437f932724 100644 --- a/crates/engine/src/tests/containers.rs +++ b/crates/engine/src/tests/containers.rs @@ -256,6 +256,122 @@ fn an_images_stroke_with_outline_object_draws_exports_and_expands_along_its_fram assert!(kids[0].appearance.fill_paint().is_none()); } +/// A 100×100 PNG, transparent but for an opaque red disc of radius 30 in its middle. +fn disc_png() -> Vec { + let mut png = vec![]; + image::RgbaImage::from_fn(100, 100, |x, y| { + let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0); + image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }]) + }) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + png +} + +#[test] +fn an_images_stroke_with_outline_object_follows_its_opaque_area() { + let mut s = session(); + // The frame runs from 50 to 150, the disc from 70 to 130. + let r = run(&mut s, "file.place", json!({"name": "disc.png", "dataBase64": vectorcraft_format::base64_encode(&disc_png()), "at": [100, 100]})); + let im = NodeId(r["ids"][0].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({})); + run(&mut s, "appearance.setItem", json!({"index": 0, "weight": 8, "color": "#000000"})); + run(&mut s, "effect.apply", json!({"effect": "path.outlineObject", "item": 0})); + // Under the image, the stroke's outer 4 pt shows around the disc, from 66 to 70; nothing runs + // along the frame. + let shade = |s: &Session, x: u32, y: u32| match pixel(s, x, y) { + p if p == RED => "red", + [r, g, b, _] if r.max(g).max(b) < 40 => "black", + [r, g, b, _] if r.min(g).min(b) > 215 => "white", + p => panic!("({x}, {y}) is {p:?}"), + }; + assert_eq!([shade(&s, 64, 100), shade(&s, 67, 100), shade(&s, 100, 100), shade(&s, 100, 132)], ["white", "black", "red", "black"]); + assert_eq!([shade(&s, 49, 100), shade(&s, 52, 100)], ["white", "white"]); + // SVG and PDF hold the disc's outline stroked 8 pt. + let doc = s.doc().unwrap().doc.clone(); + let disc = |b: vectorcraft_geom::Rect| [b.x0 - 70.0, b.y0 - 70.0, b.x1 - 130.0, b.y1 - 130.0].iter().all(|d| d.abs() < 0.5); + let svg = vectorcraft_svg::export(&doc, &Default::default()); + assert!(svg.contains(" Vec { let v = ViewInfo::default(); diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs new file mode 100644 index 0000000000..2801432a0a --- /dev/null +++ b/crates/engine/src/tests/dcs.rs @@ -0,0 +1,697 @@ +//! DCS files placed with Link (`file.place`): one linked image of their plates, their spot plates +//! as spot swatches, clipped by their composite's clipping path, never opened or embedded; and +//! the Links panel's Show DCS Transparency Interactions (`links.list` with `dcsTransparency`). +//! The files are made from scratch as http://www.telegraphics.net/doc/DCS.txt describes them. + +use std::path::PathBuf; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Node, NodeKind}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +/// A fresh scratch folder for one test. +fn temp_dir(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("vc-dcs-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A plate program: one 2 × 2 grayscale image (`gray`, row by row) on a 20 × 10 pt page. +fn plate_eps(gray: [u8; 4]) -> String { + let hex: String = gray.iter().map(|g| format!("{g:02x}")).collect(); + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n20 10 scale\n2 2 8 [2 0 0 -2 0 2] <{hex}> image\nshowpage\n%%Trailer\n%%EOF\n" + ) +} + +/// A single-file DCS 2.0 file of `plates` (name, plate program), with the header lines `extra`; its +/// composite is drawn through a clipping path, the left half of the page. +fn single_file(plates: &[(&str, String)], extra: &str) -> Vec { + let header = |offsets: &[usize]| { + let mut s = String::from("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n"); + s.push_str(extra); + for ((name, eps), at) in plates.iter().zip(offsets) { + s.push_str(&format!("%%PlateFile: ({name}) EPS #{at:010} {:010}\n", eps.len())); + } + s.push_str("%%EndComments\ngsave newpath 0 0 moveto 10 0 lineto 10 10 lineto 0 10 lineto closepath clip newpath\n"); + s.push_str("20 10 scale 2 2 8 [2 0 0 -2 0 2] <808080808080808080808080> false 3 colorimage grestore showpage\n%%EOF\n"); + s + }; + let main = header(&vec![0; plates.len()]).len(); + let mut offsets = vec![]; + let mut at = main; + for (_, eps) in plates { + offsets.push(at); + at += eps.len(); + } + let mut out = header(&offsets).into_bytes(); + for (_, eps) in plates { + out.extend(eps.as_bytes()); + } + out +} + +/// Cyan solid on the top row, PANTONE 185 C at 50% on the left column. +fn two_plates() -> Vec { + single_file( + &[("Cyan", plate_eps([0, 0, 255, 255])), ("PANTONE 185 C", plate_eps([127, 255, 127, 255]))], + "%%DocumentCustomColors: (PANTONE 185 C)\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n", + ) +} + +fn write(dir: &std::path::Path, name: &str, bytes: &[u8]) -> String { + let p = dir.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().into_owned() +} + +/// The image inside placed object `id` (itself, or the image of its clipping group). +fn image_of(s: &Session, id: &Value) -> Node { + let n = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().clone(); + let mut found = None; + n.walk(&mut |c: &Node| { + if found.is_none() && matches!(c.kind, NodeKind::Image(_)) { + found = Some(c.clone()); + } + }); + found.expect("an image") +} + +fn error(s: &mut Session, cmd: &str, p: Value) -> String { + s.execute(cmd, &p).unwrap_err().to_string() +} + +#[test] +fn a_dcs_file_places_as_one_linked_image_of_its_plates() { + let dir = temp_dir("place"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + assert_eq!(r["linked"], true); + assert_eq!(r["warnings"], json!([])); + let id = &r["ids"][0]; + let placed = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().clone(); + let NodeKind::Group { children, clip: true } = &placed.kind else { panic!("a clipping group: {:?}", placed.kind) }; + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }), "the composite's clipping path"); + assert_eq!(children[0].geometric_bounds().map(|b| b.width().round()), Some(10.0)); + assert_eq!(r["width"].as_f64().map(f64::round), Some(10.0), "clipped to the left half of its 20 pt page"); + let image = image_of(&s, id); + let NodeKind::Image(im) = &image.kind else { not_an_image() }; + assert!(im.link.as_ref().is_some_and(|l| l.path.ends_with("pic.eps"))); + let doc = &s.doc().unwrap().doc; + let plates = doc.images[&im.key].separated().expect("its plates are kept"); + assert_eq!(plates.plates.iter().map(|p| p.name.as_str()).collect::>(), ["Cyan", "PANTONE 185 C"]); + assert_eq!(plates.plates[1].data, [128, 0, 128, 0]); + let sw = doc.swatch("PANTONE 185 C").expect("a spot swatch for the spot plate"); + assert!(sw.spot); + assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 0.91, 0.76, 0.0))); + assert!(!doc.swatches_iter().any(|w| w.spot && w.name == "Cyan"), "process plates add no spot swatch"); + let list = s.execute("links.list", &json!({})).unwrap(); + assert_eq!(list["links"][0]["format"], "DCS"); + assert_eq!(list["links"][0]["status"], "ok"); + let info = s.execute("file.place.info", &json!({ "path": path })).unwrap(); + assert_eq!(info["plates"], json!(["Cyan", "PANTONE 185 C"])); + assert_eq!(info["colorMode"], "CMYK"); + assert_eq!(info["pixelWidth"], 2); + // One undo step takes the swatch away too. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("PANTONE 185 C").is_none()); +} + +fn not_an_image() -> ! { + panic!("an image") +} + +#[test] +fn a_dcs_file_is_never_opened_or_embedded() { + let dir = temp_dir("refused"); + let bytes = two_plates(); + let path = write(&dir, "pic.eps", &bytes); + let mut s = session(); + let only = "DCS files can only be placed linked"; + assert!(error(&mut s, "file.place", json!({ "path": path, "link": false })).contains(only)); + let data = json!({ "name": "pic.eps", "dataBase64": vectorcraft_format::base64_encode(&bytes) }); + assert!(error(&mut s, "file.place", data).contains(only), "bytes alone can't be linked"); + assert!(error(&mut s, "document.open", json!({ "path": path })).contains(only)); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let image = image_of(&s, &r["ids"][0]); + let e = error(&mut s, "links.embed", json!({ "ids": [image.id.0] })); + assert!(e.contains(only), "{e}"); + let NodeKind::Image(im) = &image_of(&s, &r["ids"][0]).kind else { not_an_image() }; + assert!(im.link.is_some(), "still linked"); +} + +#[test] +fn a_swatch_of_the_same_name_is_kept_with_a_warning() { + let dir = temp_dir("swatch"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + s.execute("swatch.new", &json!({"name": "PANTONE 185 C", "color": {"c": 0.0, "m": 1.0, "y": 1.0, "k": 0.0}, "spot": true})).unwrap(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + assert_eq!(r["warnings"], json!(["the document's swatch `PANTONE 185 C` is kept: it is a different color"])); + let sw = s.doc().unwrap().doc.swatch("PANTONE 185 C").unwrap().clone(); + assert_eq!(sw.paint.color(), Some(Color::cmyk(0.0, 1.0, 1.0, 0.0))); +} + +#[test] +fn plate_files_of_their_own_are_read_from_the_dcs_files_folder() { + let dir = temp_dir("files"); + write(&dir, "pic.C", plate_eps([0, 255, 255, 255]).as_bytes()); + write(&dir, "pic.K", plate_eps([255, 255, 255, 0]).as_bytes()); + let main = "%!PS-Adobe-2.0 EPSF-1.2\n%%BoundingBox: 0 0 20 10\n%%CyanPlate: OldDisk:Scans:pic.C\n%%BlackPlate: pic.K\n%%EndComments\nshowpage\n"; + let path = write(&dir, "pic.eps", main.as_bytes()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let image = image_of(&s, &r["ids"][0]); + assert!(matches!(image.kind, NodeKind::Image(_)), "no clipping path without a composite"); + let NodeKind::Image(im) = &image.kind else { not_an_image() }; + let plates = s.doc().unwrap().doc.images[&im.key].separated().unwrap(); + assert_eq!(plates.plates[0].data, [255, 0, 0, 0], "the plate file found by its name in the folder"); + assert_eq!(plates.plates[1].data, [0, 0, 0, 255]); + std::fs::remove_file(dir.join("pic.K")).unwrap(); + let e = error(&mut s, "file.place", json!({ "path": path })); + assert!(e.contains("the Black plate can't be read") && e.contains("`pic.K` is not in the DCS file's folder"), "{e}"); +} + +#[test] +fn update_link_reads_the_plates_again() { + let dir = temp_dir("update"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let id = image_of(&s, &r["ids"][0]).id; + let changed = single_file(&[("Cyan", plate_eps([0, 0, 0, 0])), ("Varnish", plate_eps([255; 4]))], "%%CMYKCustomColor: 0 0 .2 0 (Varnish)\n"); + std::fs::write(&path, &changed).unwrap(); + let u = s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(u["updated"], json!([id.0])); + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { not_an_image() }; + let plates = s.doc().unwrap().doc.images[&im.key].separated().unwrap(); + assert_eq!(plates.plates.len(), 2); + assert_eq!(plates.plates[0].data, [255; 4]); + let sw = s.doc().unwrap().doc.swatch("Varnish").expect("a spot swatch for the plate the file gained"); + assert!(sw.spot); + assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 0.0, 0.2, 0.0))); +} + +#[test] +fn update_link_takes_the_files_new_clipping_path() { + let dir = temp_dir("update-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = image_of(&s, &r["ids"][0]).id; + let clip_width = |s: &Session| { + let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") }; + children[0].geometric_bounds().map(|b| b.width()) + }; + let before = clip_width(&s).unwrap(); + // The same file, its composite now drawn through the left quarter of the page (same length, + // so the plates stay where the header says). + let text = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1); + std::fs::write(&path, text.as_bytes()).unwrap(); + let u = s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(u["updated"], json!([id.0])); + let after = clip_width(&s).unwrap(); + assert!((after - before / 2.0).abs() < 1e-6, "the clipping path follows the file: {before} → {after}"); +} + +#[test] +fn update_link_clips_an_image_whose_file_gained_a_clipping_path() { + let dir = temp_dir("update-gained-clip"); + // The composite drawn without its clipping path (same length). + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + let path = write(&dir, "pic.eps", unclipped.as_bytes()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Image(_)), "no clipping path, no group"); + std::fs::write(&path, two_plates()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + let doc = &s.doc().unwrap().doc; + let group = doc.node(doc.parent_of(id).expect("a parent")).unwrap(); + let NodeKind::Group { children, clip: true } = &group.kind else { panic!("a clipping group: {:?}", group.kind) }; + assert_eq!(children[0].geometric_bounds().map(|b| b.width().round()), Some(10.0), "the left half of the page"); +} + +#[test] +fn a_changed_plate_file_marks_the_link_modified() { + let dir = temp_dir("plate-changed"); + write(&dir, "pic.C", plate_eps([0, 255, 255, 255]).as_bytes()); + let main = "%!PS-Adobe-2.0 EPSF-1.2\n%%BoundingBox: 0 0 20 10\n%%CyanPlate: pic.C\n%%EndComments\nshowpage\n"; + let path = write(&dir, "pic.eps", main.as_bytes()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let id = image_of(&s, &r["ids"][0]).id; + assert_eq!(s.execute("links.list", &json!({})).unwrap()["links"][0]["status"], "ok"); + // Only the plate file changes (a size of its own, so the change shows whatever the clock). + write(&dir, "pic.C", format!("{}% more\n", plate_eps([255, 255, 255, 0])).as_bytes()); + assert_eq!(s.execute("links.list", &json!({})).unwrap()["links"][0]["status"], "modified"); + let u = s.execute("links.update", &json!({})).unwrap(); + assert_eq!(u["updated"], json!([id.0])); + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { not_an_image() }; + assert_eq!(s.doc().unwrap().doc.images[&im.key].separated().unwrap().plates[0].data, [0, 0, 0, 255]); + assert_eq!(s.execute("links.list", &json!({})).unwrap()["links"][0]["status"], "ok"); + std::fs::remove_file(dir.join("pic.C")).unwrap(); + assert_eq!(s.execute("links.list", &json!({})).unwrap()["links"][0]["status"], "modified", "a plate file that is gone"); +} + +#[test] +fn the_link_watch_reads_the_link_again_when_only_a_plate_file_changes() { + let dir = temp_dir("plate-watch"); + write(&dir, "pic.C", plate_eps([0, 255, 255, 255]).as_bytes()); + let main = "%!PS-Adobe-2.0 EPSF-1.2\n%%BoundingBox: 0 0 20 10\n%%CyanPlate: pic.C\n%%EndComments\nshowpage\n"; + let path = write(&dir, "pic.eps", main.as_bytes()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let id = image_of(&s, &r["ids"][0]).id; + let files: Vec = crate::link_watch::linked_files(&s.doc().unwrap().doc).into_iter().map(|(p, _)| p).collect(); + assert!(files.iter().any(|p| p.ends_with("pic.C")), "the plate file is watched too: {files:?}"); + // The first look only remembers the files. + assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([])); + write(&dir, "pic.C", format!("{}% more\n", plate_eps([255, 255, 255, 0])).as_bytes()); + assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([id.0])); + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { not_an_image() }; + assert_eq!(s.doc().unwrap().doc.images[&im.key].separated().unwrap().plates[0].data, [0, 0, 0, 255]); +} + +/// The width of the clipping path of the clip group holding the image in the art of symbol +/// `name`; `None` when no clip group holds it. +fn symbol_clip_width(s: &Session, name: &str) -> Option { + fn find(n: &Node) -> Option> { + if let NodeKind::Group { children, clip: true } = &n.kind + && let [c, im] = &children[..] + && matches!(im.kind, NodeKind::Image(_)) + { + return Some(c.geometric_bounds().map(|b| b.width())); + } + if matches!(n.kind, NodeKind::Image(_)) { + return Some(None); + } + n.children().and_then(|ch| ch.iter().find_map(|c| find(c))) + } + let doc = &s.doc().unwrap().doc; + find(&doc.symbols.iter().find(|w| w.name == name).expect("the symbol").art).expect("an image in the symbol") +} + +#[test] +fn update_link_takes_the_files_clipping_path_into_symbols_too() { + let dir = temp_dir("update-symbol-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let id = image_of(&s, &r["ids"][0]).id; + let other = s.execute("file.place", &json!({ "path": path, "at": [200, 100] })).unwrap(); + s.execute("symbol.new", &json!({ "name": "Pic", "ids": [other["ids"][0]] })).unwrap(); + let before = symbol_clip_width(&s, "Pic").expect("the file's clipping path"); + // The composite now drawn through the left quarter of the page (same length). + let text = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1); + std::fs::write(&path, text.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + let after = symbol_clip_width(&s, "Pic").expect("still clipped"); + assert!((after - before / 2.0).abs() < 1e-6, "the symbol's clipping path follows the file: {before} → {after}"); + // The file without a clipping path (same length): the symbol's image is no longer clipped. + let unclipped = text.replacen("closepath clip newpath", "closepath newpath ", 1); + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(symbol_clip_width(&s, "Pic"), None); +} + +#[test] +fn a_file_that_lost_its_clipping_path_unclips_the_image() { + let dir = temp_dir("update-lost-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let id = image_of(&s, &r["ids"][0]).id; + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + let doc = &s.doc().unwrap().doc; + let placed = NodeId(r["ids"][0].as_u64().unwrap()); + assert_eq!(doc.node(placed).and_then(plain_group_of_image), Some((false, true)), "the placed group stays, without the clip"); + let parent = doc.parent_of(id).expect("a parent"); + assert!(!matches!(doc.node(parent).unwrap().kind, NodeKind::Group { clip: true, .. }), "the image is not clipped"); + // Relinked to a plain image: no clip group either. + let png = dir.join("plain.png"); + image::RgbImage::from_pixel(2, 2, image::Rgb([9, 9, 9])).save(&png).unwrap(); + std::fs::write(&path, two_plates()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert!( + s.doc().unwrap().doc.parent_of(id).is_some_and(|p| matches!(s.doc().unwrap().doc.node(p).unwrap().kind, NodeKind::Group { clip: true, .. })) + ); + s.execute("links.relink", &json!({ "ids": [id.0], "path": png.to_string_lossy() })).unwrap(); + let doc = &s.doc().unwrap().doc; + assert!( + !matches!(doc.node(doc.parent_of(id).unwrap()).unwrap().kind, NodeKind::Group { clip: true, .. }), + "a plain image isn't clipped by the DCS file's path" + ); +} + +/// The kind of group `g` is, as (clip, the kinds of its children are just one image). +fn plain_group_of_image(g: &Node) -> Option<(bool, bool)> { + match &g.kind { + NodeKind::Group { children, clip } => Some((*clip, matches!(&children[..], [c] if matches!(c.kind, NodeKind::Image(_))))), + _ => None, + } +} + +#[test] +fn a_hidden_or_transparent_clip_group_loses_the_files_old_clipping_path() { + let dir = temp_dir("lost-clip-kept-group"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let place = |s: &mut Session, x: f64| s.execute("file.place", &json!({ "path": path, "at": [x, 100] })).unwrap(); + let (faded, hidden, in_symbol) = (place(&mut s, 100.0), place(&mut s, 200.0), place(&mut s, 300.0)); + let (faded, hidden) = (NodeId(faded["ids"][0].as_u64().unwrap()), NodeId(hidden["ids"][0].as_u64().unwrap())); + let image = image_of(&s, &json!(faded.0)).id; + s.execute("transparency.set", &json!({"ids": [faded.0, in_symbol["ids"][0]], "opacity": 50})).unwrap(); + s.edit("hide", |d, _| { + if let Some(n) = d.node_mut(hidden) { + n.visible = false; + } + Ok(()) + }) + .unwrap(); + s.execute("symbol.new", &json!({ "name": "Pic", "ids": [in_symbol["ids"][0]] })).unwrap(); + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + let hidden_image = image_of(&s, &json!(hidden.0)).id; + s.execute("links.update", &json!({ "ids": [image.0, hidden_image.0] })).unwrap(); + let doc = &s.doc().unwrap().doc; + for (g, why) in [(faded, "the transparent group"), (hidden, "the hidden group")] { + let n = doc.node(g).unwrap_or_else(|| panic!("{why} stays")); + assert_eq!(plain_group_of_image(n), Some((false, true)), "{why} holds the image alone, unclipped"); + } + assert!((doc.node(faded).unwrap().opacity - 0.5).abs() < 1e-6, "its transparency kept"); + assert!(!doc.node(hidden).unwrap().visible, "still hidden"); + // In a symbol's art too. + let art = &doc.symbols.iter().find(|w| w.name == "Pic").expect("the symbol").art; + let mut found = None; + art.walk(&mut |n: &Node| { + if found.is_none() && n.children().is_some_and(|ch| ch.iter().any(|c| matches!(c.kind, NodeKind::Image(_)))) { + found = plain_group_of_image(n); + } + }); + assert_eq!(found, Some((false, true)), "the symbol's transparent group holds the image alone, unclipped"); +} + +#[test] +fn a_clipping_mask_of_ones_own_stays_when_the_link_is_updated() { + let dir = temp_dir("own-mask"); + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + let path = write(&dir, "pic.eps", unclipped.as_bytes()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let rect = s.execute("shape.rectangle", &json!({"x": 95, "y": 95, "width": 4, "height": 4})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({ "ids": [id.0, rect] })).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(g), "the clipping mask made in the document stays"); + let mask_width = |s: &Session| { + let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(g).unwrap().kind else { panic!("the mask's group") }; + children[0].geometric_bounds().map(|b| b.width().round()) + }; + assert_eq!(mask_width(&s), Some(4.0)); + // The file gains a clipping path: its clip group goes inside the mask, which keeps its path. + std::fs::write(&path, two_plates()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + let doc = &s.doc().unwrap().doc; + let inner = doc.parent_of(id).expect("a parent"); + assert_ne!(inner, g); + assert!(matches!(doc.node(inner).unwrap().kind, NodeKind::Group { clip: true, .. }), "the file's clip group"); + assert_eq!(doc.parent_of(inner), Some(g)); + assert_eq!(mask_width(&s), Some(4.0), "the mask's path is kept"); +} + +#[test] +fn a_dcs_file_takes_the_place_parameters_an_eps_file_takes() { + let dir = temp_dir("params"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + assert!(error(&mut s, "file.place", json!({ "path": path, "page": 0 })).contains("page")); + assert!(error(&mut s, "file.place", json!({ "path": path, "crop": "trim" })).contains("crop")); +} + +#[test] +fn a_clipped_placement_answers_its_image_for_the_links_commands() { + let dir = temp_dir("image-id"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + assert_eq!(r["image"], json!(image_of(&s, &r["ids"][0]).id.0)); + let info = s.execute("links.info", &json!({ "id": r["image"] })).unwrap(); + assert_eq!(info["format"], "DCS"); + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + let plain = write(&dir, "plain.eps", unclipped.as_bytes()); + assert!(s.execute("file.place", &json!({ "path": plain })).unwrap().get("image").is_none(), "an image placed alone is its own id"); +} + +#[test] +fn update_and_relink_warn_of_a_swatch_kept_for_a_new_spot_plate() { + let dir = temp_dir("update-swatch"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let id = image_of(&s, &r["ids"][0]).id; + s.execute("swatch.new", &json!({"name": "Varnish", "color": {"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}})).unwrap(); + let changed = single_file(&[("Cyan", plate_eps([0, 0, 0, 0])), ("Varnish", plate_eps([255; 4]))], "%%CMYKCustomColor: 0 0 .2 0 (Varnish)\n"); + std::fs::write(&path, &changed).unwrap(); + let u = s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + let kept = "the document's swatch `Varnish` is kept: it is a process color, so the plate prints as process inks"; + assert_eq!(u["warnings"], json!([kept])); + let other = write(&dir, "other.eps", &changed); + let r = s.execute("links.relink", &json!({ "ids": [id.0], "path": other })).unwrap(); + assert_eq!(r["warnings"], json!([kept])); + assert!(s.execute("links.update", &json!({ "ids": [id.0] })).unwrap().get("warnings").is_some(), "every read warns"); +} + +#[test] +fn a_deleted_dcs_image_leaves_its_spot_swatch_unused() { + let dir = temp_dir("unused"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let unused = |s: &mut Session| s.execute("swatch.unused", &json!({})).unwrap()["names"].as_array().unwrap().iter().any(|n| n == "PANTONE 185 C"); + assert!(!unused(&mut s), "in use while the image shows it"); + s.execute("select.set", &json!({ "ids": [r["ids"][0]] })).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(unused(&mut s), "unused once the image is deleted"); +} + +#[test] +fn a_process_swatch_giving_a_dcs_plate_its_color_is_used() { + let dir = temp_dir("unused-process"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + s.execute("swatch.new", &json!({"name": "PANTONE 185 C", "color": {"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}})).unwrap(); + let unused = |s: &mut Session| s.execute("swatch.unused", &json!({})).unwrap()["names"].as_array().unwrap().iter().any(|n| n == "PANTONE 185 C"); + assert!(unused(&mut s), "nothing uses it yet"); + s.execute("file.place", &json!({ "path": path })).unwrap(); + assert!(!unused(&mut s), "the plate of its name prints as its process inks"); +} + +#[test] +fn an_opened_clipping_path_is_not_the_files_and_stays() { + let dir = temp_dir("opened-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = image_of(&s, &r["ids"][0]).id; + // The clipping path opened, its anchors where they were. + s.edit("open", |d, _| { + let clip = d.node(group).and_then(|g| g.children()).map(|ch| ch[0].id).unwrap(); + if let Some(Node { kind: NodeKind::Path { path, .. }, .. }) = d.node_mut(clip) { + path.subpaths[0].closed = false; + } + Ok(()) + }) + .unwrap(); + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(group), "a clipping path edited in the document stays"); +} + +#[test] +fn a_clipping_path_given_another_fill_rule_is_not_the_files_and_stays() { + let dir = temp_dir("rule-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = image_of(&s, &r["ids"][0]).id; + // The clipping path's fill rule changed, its anchors where they were. + s.edit("rule", |d, _| { + let clip = d.node(group).and_then(|g| g.children()).map(|ch| ch[0].id).unwrap(); + if let Some(Node { kind: NodeKind::Path { rule, .. }, .. }) = d.node_mut(clip) { + *rule = vectorcraft_geom::FillRule::EvenOdd; + } + Ok(()) + }) + .unwrap(); + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(group), "a clipping path whose fill rule was changed stays"); +} + +#[test] +fn an_even_odd_clipping_path_is_placed_and_matched_under_the_nonzero_rule() { + let dir = temp_dir("eo-clip"); + // The same length, so the plates' offsets hold. + let eo = String::from_utf8(two_plates()).unwrap().replacen("gsave newpath 0 0 moveto", "gsave 0 0 moveto ", 1); + let eo = eo.replacen("closepath clip newpath", "closepath eoclip newpath", 1); + assert_eq!(eo.len(), two_plates().len()); + let path = write(&dir, "pic.eps", eo.as_bytes()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = image_of(&s, &r["ids"][0]).id; + let doc = &s.doc().unwrap().doc; + let clip = &doc.node(group).and_then(|g| g.children()).expect("the file's clip group")[0]; + assert!(matches!(clip.kind, NodeKind::Path { rule: vectorcraft_geom::FillRule::NonZero, clipping: true, .. }), "{:?}", clip.kind); + // The file without its clipping path: the group's clipping path is the file's, and goes. + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + std::fs::write(&path, unclipped.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert_eq!(s.doc().unwrap().doc.node(group).and_then(plain_group_of_image), Some((false, true)), "the file's clipping path is gone"); +} + +#[test] +fn files_updated_together_warn_when_they_add_one_ink_in_two_colors() { + let dir = temp_dir("update-two-inks"); + let (a, b) = (write(&dir, "a.eps", &two_plates()), write(&dir, "b.eps", &two_plates())); + let mut s = session(); + s.execute("file.place", &json!({ "path": a })).unwrap(); + s.execute("file.place", &json!({ "path": b })).unwrap(); + let varnish = + |c: &str| single_file(&[("Cyan", plate_eps([0; 4])), ("Varnish", plate_eps([255; 4]))], &format!("%%CMYKCustomColor: {c} (Varnish)\n")); + std::fs::write(&a, varnish("0 0 .2 0")).unwrap(); + std::fs::write(&b, varnish("1 0 0 0")).unwrap(); + let u = s.execute("links.update", &json!({})).unwrap(); + assert_eq!(u["updated"].as_array().map(Vec::len), Some(2), "{u}"); + assert_eq!(u["warnings"], json!(["the document's swatch `Varnish` is kept: it is a different color"])); +} + +#[test] +fn relink_with_copy_refuses_a_dcs_file_with_plate_files() { + let dir = temp_dir("copy"); + write(&dir, "pic.C", plate_eps([0, 255, 255, 255]).as_bytes()); + let main = "%!PS-Adobe-2.0 EPSF-1.2\n%%BoundingBox: 0 0 20 10\n%%CyanPlate: pic.C\n%%EndComments\nshowpage\n"; + let path = write(&dir, "pic.eps", main.as_bytes()); + let docs = dir.join("docs"); + std::fs::create_dir_all(&docs).unwrap(); + let mut s = session(); + s.execute("document.save", &json!({ "path": docs.join("doc.vectorcraft").to_string_lossy() })).unwrap(); + let png = dir.join("plain.png"); + image::RgbImage::from_pixel(2, 2, image::Rgb([9, 9, 9])).save(&png).unwrap(); + let r = s.execute("file.place", &json!({ "path": png.to_string_lossy() })).unwrap(); + let id = r["ids"][0].clone(); + let e = error(&mut s, "links.relink", json!({ "ids": [id], "path": path, "copy": true })); + assert!(e.contains("plate files"), "{e}"); + assert!(!docs.join("pic.eps").exists(), "nothing is copied"); + // A single-file DCS file has its plates inside it: it is copied. + let single = write(&dir, "single.eps", &two_plates()); + s.execute("links.relink", &json!({ "ids": [id], "path": single, "copy": true })).unwrap(); + assert!(docs.join("single.eps").exists()); +} + +#[test] +fn a_saved_document_reads_the_plates_again_and_prints_the_spot_ink() { + let dir = temp_dir("saved"); + let path = write(&dir, "pic.eps", &two_plates()); + let saved = dir.join("doc.vectorcraft").to_string_lossy().into_owned(); + let mut s = session(); + s.execute("file.place", &json!({ "path": path })).unwrap(); + let unused = s.execute("swatch.unused", &json!({})).unwrap(); + assert!(!unused["names"].as_array().unwrap().iter().any(|n| n == "PANTONE 185 C"), "the plate's swatch is in use: {unused}"); + s.execute("document.save", &json!({ "path": saved })).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({ "path": saved })).unwrap(); + let list = s.execute("links.list", &json!({})).unwrap(); + assert_eq!(list["links"][0]["format"], "DCS"); + assert_eq!(list["links"][0]["status"], "ok"); + let id = NodeId(list["links"][0]["id"].as_u64().unwrap()); + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { not_an_image() }; + let plates = s.doc().unwrap().doc.images[&im.key].separated().expect("the plates, read from the file again"); + assert_eq!(plates.plates[1].data, [128, 0, 128, 0]); + let v = s.execute("print.preview", &json!({"settings": {"output": {"mode": "separations"}}})).unwrap(); + let inks: Vec<&str> = v["sheets"].as_array().unwrap().iter().filter_map(|p| p["ink"].as_str()).collect(); + assert_eq!(inks, ["Cyan", "Magenta", "Yellow", "Black", "PANTONE 185 C"]); +} + +#[test] +fn dcs_transparency_marks_transparent_and_overlapped_dcs_images() { + let dir = temp_dir("transparency"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let image = image_of(&s, &r["ids"][0]).id; + let marked = |s: &mut Session| s.execute("links.list", &json!({ "dcsTransparency": true })).unwrap()["links"][0]["dcsTransparency"] == true; + assert!(!marked(&mut s), "nothing transparent"); + assert!(s.execute("links.list", &json!({})).unwrap()["links"][0].get("dcsTransparency").is_none()); + // A half-transparent square away from it, then over it. + let far = s.execute("shape.rectangle", &json!({"x": 300, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("transparency.set", &json!({"ids": [far], "opacity": 50})).unwrap(); + assert!(!marked(&mut s), "a transparent object elsewhere"); + s.execute("shape.rectangle", &json!({"x": 90, "y": 90, "width": 20, "height": 20})).unwrap(); + let over = s.execute("shape.rectangle", &json!({"x": 92, "y": 92, "width": 4, "height": 4})).unwrap()["id"].as_u64().unwrap(); + assert!(!marked(&mut s), "opaque objects over it"); + s.execute("transparency.set", &json!({"ids": [over], "blend": "multiply"})).unwrap(); + assert!(marked(&mut s), "a blend mode over it"); + s.execute("transparency.set", &json!({"ids": [over], "blend": "normal"})).unwrap(); + s.execute("transparency.set", &json!({"ids": [image.0], "opacity": 80})).unwrap(); + assert!(marked(&mut s), "the image itself"); + assert!(error(&mut s, "links.list", json!({ "dcsTransparency": "yes" })).contains("dcsTransparency"), "a flag that isn't true or false"); +} + +#[test] +fn dcs_transparency_counts_a_transparent_dcs_image_over_another() { + let dir = temp_dir("transparency-two"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let a = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let b = s.execute("file.place", &json!({ "path": path, "at": [103, 100] })).unwrap(); + let (a, b) = (image_of(&s, &a["ids"][0]).id, image_of(&s, &b["ids"][0]).id); + s.execute("transparency.set", &json!({"ids": [a.0], "opacity": 80})).unwrap(); + let list = s.execute("links.list", &json!({ "dcsTransparency": true })).unwrap(); + let marked = |id: NodeId| list["links"].as_array().unwrap().iter().any(|r| r["id"] == id.0 && r["dcsTransparency"] == true); + assert!(marked(a), "the transparent image"); + assert!(marked(b), "the opaque image it overlaps"); +} + +#[test] +fn dcs_transparency_counts_characters_with_a_transparent_gradient() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let dir = temp_dir("transparency-text"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 96, "y": 104, "text": "Hi", "size": 12})).unwrap()["id"].as_u64().unwrap()); + let marked = |s: &mut Session| s.execute("links.list", &json!({ "dcsTransparency": true })).unwrap()["links"][0]["dcsTransparency"] == true; + assert!(!marked(&mut s), "opaque characters over it"); + let mut stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + stops[1].opacity = 0.5; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + s.edit("t", |d, _| { + if let Some(Node { kind: NodeKind::Text(text), .. }) = d.node_mut(t) { + text.runs[0].style.fill = gradient.clone(); + } + Ok(()) + }) + .unwrap(); + assert!(marked(&mut s), "characters filled with a gradient that has a transparent stop"); + assert!(s.doc().unwrap().doc.node(t).unwrap().shows_transparency()); +} diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index ea10df64b5..5986b618fd 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -3278,6 +3278,14 @@ fn close_path_places_the_first_anchors_handles() { s.execute("path.close", &json!({"id": id.0, "in": [60.0, 140.0], "out": [120.0, 60.0]})).unwrap(); let b = path(&s, id).subpaths[0].anchors[0]; assert_eq!((b.h_in, b.h_out, b.kind), (Point::new(60.0, 140.0), Point::new(120.0, 60.0), AnchorKind::Corner)); + // `at` moves the anchor, its handles with it, before `in` is placed. + s.execute("edit.undo", &json!({})).unwrap(); + refuses_with(&mut s, "path.close", &json!({"id": id.0, "at": "120, 90"}), "`at` must be [x, y]"); + s.execute("path.close", &json!({"id": id.0, "at": [120.0, 90.0], "in": [60.0, 140.0]})).unwrap(); + let b = path(&s, id).subpaths[0].anchors[0]; + assert_eq!((b.p, b.h_in, b.h_out), (Point::new(120.0, 90.0), Point::new(60.0, 140.0), Point::new(170.0, 90.0)), "{b:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id).subpaths[0].anchors[0], a, "one undo step"); } #[test] 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/params.rs b/crates/engine/src/tests/params.rs index 3cbdb5df9f..e72f607030 100644 --- a/crates/engine/src/tests/params.rs +++ b/crates/engine/src/tests/params.rs @@ -600,6 +600,105 @@ fn effect_params_are_the_effects_own() { assert!(s.check_params("effect.setParams", &json!({"index": 7, "params": {"blurr": 3}})).is_ok()); } +/// An effect parameter that only the effect's params description names, with no dialog default, +/// is held to the type the effect reads: the earlier 3D Perspective and light, Scribble's +/// `variation` and an Outline Stroke's `width` are numbers, and a Gaussian Blur's `linear` is true +/// or false. The `style` of Crop Marks is `roman` or `japanese`. Every such key of every effect is +/// listed, or has a check of its own. A key left out keeps its default. +#[test] +fn an_effect_parameter_without_a_default_is_held_to_its_type() { + use crate::cmd::params::undefaulted_type; + use vectorcraft_render::effects::effect_catalog; + // Read by checks of their own: a stored texture or a texture to load, an SVG filter, a Warp's + // map and the style of Crop Marks. + let own_check = |effect: &str, key: &str| match key { + "textureImage" | "name" | "xml" => true, + "version" => effect.starts_with("warp."), + "style" => effect == "cropMarks", + _ => false, + }; + let mut unlisted = vec![]; + for e in effect_catalog() { + for key in doc_keys(e.params).unwrap().keys { + if e.defaults.get(key).is_none() && undefaulted_type(e.id, key).is_none() && !own_check(e.id, key) { + unlisted.push(format!("{}.{key}", e.id)); + } + } + } + assert!(unlisted.is_empty(), "parameters without a default or a listed type: {unlisted:?}"); + let apply = |effect: &str, params| json!({"effect": effect, "params": params}); + for (effect, params, why) in [ + ("threeD.revolve", json!({"perspective": true}), "`perspective` must be a number"), + ("threeD.extrude", json!({"lightAzimuth": "30"}), "`lightAzimuth` must be a number"), + ("threeD.rotate", json!({"lightElevation": null}), "`lightElevation` must be a number"), + ("threeD.inflate", json!({"perspective": "50%"}), "`perspective` must be a number"), + ("path.outlineStroke", json!({"width": "10 pt"}), "`width` must be a number"), + ("stylize.scribble", json!({"variation": false}), "`variation` must be a number"), + ("blur.gaussian", json!({"radius": 2, "linear": 1}), "`linear` must be true or false"), + ("cropMarks", json!({"style": "bogus"}), "`style` must be roman or japanese"), + ("cropMarks", json!({"style": 1}), "`style` must be roman or japanese"), + ("cropMarks", json!({"style": null}), "`style` must be roman or japanese"), + ] { + assert_eq!(refusal("effect.apply", apply(effect, params.clone())), why, "{effect} {params}"); + assert_eq!(refusal("appearance.addEffect", apply(effect, params.clone())), why, "{effect} {params}"); + } + for (effect, params) in [ + ("threeD.revolve", json!({"perspective": 40, "lightAzimuth": 30.5, "lightElevation": 0})), + ("path.outlineStroke", json!({"width": 10})), + ("stylize.scribble", json!({"variation": 2})), + ("blur.gaussian", json!({"linear": true})), + ("blur.gaussian", json!({})), + ("cropMarks", json!({"style": "japanese"})), + ("cropMarks", json!({})), + ] { + assert!(check_params("effect.apply", &apply(effect, params.clone())).is_ok(), "{effect} {params}"); + } +} + +/// `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse such a parameter of the +/// wrong type when they run, and so does a step of a `command.batch` whose effect a step before it +/// added, with the document and its undo history as they were. A saved step still plays with it, +/// as with a key the effect no longer takes. +#[test] +fn effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.history.undo.len(), st.doc.clone()) + }; + let before = state(&s); + let apply = |effect: &str, params| json!({"effect": effect, "params": params}); + for (id, params, why) in [ + ("effect.apply", apply("path.outlineStroke", json!({"width": "10 pt"})), "`width` must be a number"), + ("appearance.addEffect", apply("blur.gaussian", json!({"linear": 1})), "`linear` must be true or false"), + ("effect.apply", apply("threeD.revolve", json!({"perspective": "50"})), "`perspective` must be a number"), + ] { + let e = s.execute(id, ¶ms).unwrap_err().to_string(); + assert!(e.contains(why), "{id} {params}: {e}"); + assert_eq!(state(&s), before, "{id} {params}"); + } + let batch = json!({"commands": [ + {"command": "effect.apply", "params": apply("path.outlineStroke", json!({"width": 3}))}, + {"command": "effect.setParams", "params": {"index": 0, "params": {"width": "10 pt"}}}, + ]}); + let e = s.execute("command.batch", &batch).unwrap_err().to_string(); + assert!(e.contains("`width` must be a number"), "{e}"); + assert_eq!(state(&s), before); + s.execute("effect.apply", &apply("path.outlineStroke", json!({"width": 3}))).unwrap(); + let applied = state(&s); + for params in [json!({"width": "10 pt"}), json!({"width": null}), json!({"width": true})] { + let e = s.execute("effect.setParams", &json!({"index": 0, "params": params.clone()})).unwrap_err().to_string(); + assert!(e.contains("`width` must be a number"), "{params}: {e}"); + assert_eq!(state(&s), applied, "{params}"); + } + s.execute("effect.setParams", &json!({"index": 0, "params": {"width": 4}})).unwrap(); + s.replay("effect.setParams", &json!({"index": 0, "params": {"retired": "x", "width": "10 pt"}})).unwrap(); + let st = s.doc().unwrap(); + assert_eq!(st.doc.layers[0].children().unwrap()[0].appearance.effects[0].params["width"], json!("10 pt")); +} + /// The Transform effect (`distort.transform`) is held to its params description: `effect.apply` /// and `effect.setParams` refuse each of its on/off options given as text, such as `reflectX: /// "false"`, and each of its numbers given as text, such as `copies: "0"`, and leave the effect diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index 0b948242db..0f29befd80 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -2,7 +2,7 @@ use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::pattern::{PATTERN_EDIT_LAYER, RepeatKind, TileType}; +use vectorcraft_doc::pattern::{PATTERN_EDIT_LAYER, RepeatKind, TileType, pattern_paint}; use vectorcraft_doc::{Node, NodeKind}; use vectorcraft_geom::{Point, Rect}; use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; @@ -212,6 +212,186 @@ fn cancel_new_pattern_removes_it() { assert_eq!(doc(&s).layers.len(), 1); } +fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document { + Arc::make_mut(&mut s.doc_mut().unwrap().doc) +} + +fn is_pattern(p: &Paint, name: &str) -> bool { + matches!(p, Paint::Pattern { pattern, .. } if pattern == name) +} + +/// How many paints of pattern `name` the document holds: in the art and the definitions +/// ([`vectorcraft_doc::Document::visit_paints`]), the swatches, the character styles and the +/// stored brush library. +fn pattern_uses(d: &vectorcraft_doc::Document, name: &str) -> usize { + let mut n = 0; + d.visit_paints(&mut |p| n += usize::from(is_pattern(p, name))); + n += d.swatches_iter().filter(|w| is_pattern(&w.paint, name)).count(); + let styled = d.char_styles.iter().flat_map(|c| ["fill", "stroke"].map(|k| c.attrs.get(k).cloned())).flatten(); + n += styled.filter(|v| serde_json::from_value::(v.clone()).is_ok_and(|p| is_pattern(&p, name))).count(); + let needle = format!("\"pattern\":\"{name}\""); + n + d.unknown.get(vectorcraft_brush::DOC_KEY).map_or(0, |v| v.to_string().matches(&needle).count()) +} + +/// Canceling a new pattern removes every swatch of it, a color group's included, and the fills and +/// strokes of it on art outside the editing layer become no paint. The object's other paints, and +/// a swatch that only shares the pattern's name, stay. +#[test] +fn cancel_new_pattern_forgets_group_swatch_and_outside_fills_and_strokes() { + let mut s = session(); + let other = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + s.execute("paint.setStroke", &json!({"ids": [other.0], "color": "#00ff00"})).unwrap(); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "Tiles"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [other.0], "swatch": "Tiles"})).unwrap(); + let d = doc_mut(&mut s); + let solid = Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { + name: "Mine".into(), + swatches: vec![ + vectorcraft_color::Swatch { name: "Grouped".into(), paint: pattern_paint("Tiles"), global: false, spot: false }, + vectorcraft_color::Swatch { name: "Tiles".into(), paint: solid.clone(), global: false, spot: false }, + ], + }); + assert!(pattern_uses(doc(&s), "Tiles") >= 3); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + let d = doc(&s); + assert!(d.pattern("Tiles").is_none()); + assert_eq!(pattern_uses(d, "Tiles"), 0); + assert!(d.swatch("Grouped").is_none(), "the group's pattern swatch goes"); + assert_eq!(d.swatch("Tiles").map(|w| &w.paint), Some(&solid), "a color swatch named like the pattern stays"); + let n = node(&s, other); + assert!(n.appearance.fill_paint().is_none()); + assert!(matches!(n.appearance.stroke_paint(), Paint::Solid { .. }), "the stroke stays"); +} + +/// Save a Copy keeps the copy as its own pattern when the new pattern is canceled, and the copy's +/// tile art loses its paints of the canceled pattern. +#[test] +fn cancel_new_pattern_forgets_its_paints_in_a_saved_copy() { + let mut s = session(); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "Tiles"})).unwrap(); + let layer = doc(&s).pattern_edit.as_ref().unwrap().layer; + let tile = doc(&s).node(layer).unwrap().children().unwrap()[0].id; + s.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Tiles"})).unwrap(); + assert_eq!(s.execute("object.pattern.saveCopy", &json!({})).unwrap()["name"], "Tiles copy"); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + let d = doc(&s); + let copy = d.pattern("Tiles copy").expect("the copy stays"); + assert_eq!(copy.art.len(), 1); + assert!(copy.art[0].appearance.fill_paint().is_none()); + assert_eq!(pattern_uses(d, "Tiles"), 0); +} + +/// Canceling a new pattern also clears its paints in type, opacity mask art, symbol definitions, +/// graph designs, graphic and character styles and brush art, and in the fill, stroke and +/// appearance new art takes, so new art does not take a paint of a pattern that is gone. +#[test] +fn cancel_new_pattern_forgets_hidden_paints_and_new_art_defaults() { + let mut s = session(); + let masked = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + let m = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, m.0]})).unwrap(); + let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Hi"})).unwrap()); + let band = rect(&mut s, 200.0, 200.0, 40.0, 10.0); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "Tiles"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [band.0], "swatch": "Tiles"})).unwrap(); + s.execute("brush.new", &json!({"type": "art", "name": "Band", "ids": [band.0]})).unwrap(); + let p = pattern_paint("Tiles"); + let d = doc_mut(&mut s); + let art = d.node(band).unwrap().clone(); + d.symbols.push(vectorcraft_doc::Symbol { name: "Sym".into(), art: Arc::new(art.clone()), dynamic: false }); + d.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Bar".into(), art: Arc::new(art.clone()) }); + d.graphic_styles.push(vectorcraft_doc::GraphicStyle { + name: "Style".into(), + appearance: (*art.appearance).clone(), + id: 0, + opacity: 1.0, + blend: Default::default(), + isolate: false, + knockout: Default::default(), + unit_box: true, + }); + let attrs = json!({"fill": p, "stroke": p, "size": 12}); + d.char_styles.push(vectorcraft_doc::TextStyleDef { name: "Char".into(), attrs: attrs.as_object().unwrap().clone() }); + if let Some(NodeKind::Text(text)) = d.node_mut(t).map(|n| &mut n.kind) { + text.runs[0].style.fill = p.clone(); + } + let mask = d.node_mut(masked).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()).expect("the mask"); + Arc::make_mut(&mut mask.art).appearance = vectorcraft_doc::Appearance::basic(p.clone(), Paint::None, 0.0).into(); + s.paint.fill = p.clone(); + s.paint.appearance = Some(vectorcraft_doc::Appearance::basic(Paint::None, p.clone(), 1.0)); + assert!(pattern_uses(doc(&s), "Tiles") >= 10, "{}", pattern_uses(doc(&s), "Tiles")); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + assert_eq!(pattern_uses(doc(&s), "Tiles"), 0); + assert!(doc(&s).char_styles[0].attrs["size"] == json!(12), "the style's other attributes stay"); + assert!(s.paint.fill.is_none()); + assert!(s.paint.appearance.as_ref().unwrap().items.iter().all(|it| match it { + vectorcraft_doc::AppearanceItem::Fill(f) => !is_pattern(&f.paint, "Tiles"), + vectorcraft_doc::AppearanceItem::Stroke(k) => !is_pattern(&k.paint, "Tiles"), + })); + let fresh = rect(&mut s, 300.0, 300.0, 20.0, 20.0); + let n = node(&s, fresh); + assert!(!is_pattern(&n.appearance.fill_paint(), "Tiles") && !is_pattern(&n.appearance.stroke_paint(), "Tiles")); +} + +/// Cancel is one undo step: Undo gives the pattern, its paints and the fill new art takes back, and +/// Redo clears them again. +#[test] +fn cancel_new_pattern_is_one_undo_step() { + let mut s = session(); + let other = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "Tiles"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [other.0], "swatch": "Tiles"})).unwrap(); + s.paint.fill = pattern_paint("Tiles"); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + assert!(s.paint.fill.is_none() && doc(&s).pattern("Tiles").is_none()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(is_pattern(&s.paint.fill, "Tiles")); + assert!(doc(&s).pattern("Tiles").is_some() && doc(&s).pattern_edit.is_some()); + assert!(is_pattern(&node(&s, other).appearance.fill_paint(), "Tiles")); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.paint.fill.is_none() && doc(&s).pattern("Tiles").is_none()); + assert_eq!(pattern_uses(doc(&s), "Tiles"), 0); +} + +/// Canceling the edit of a pattern that Pattern Options renamed while it was edited gives the +/// pattern its old name back, with its swatch and the paints of it, so nothing is left painted +/// with a name no pattern has. +#[test] +fn cancel_after_renaming_an_edited_pattern_restores_its_name_and_paints() { + let mut s = session(); + make_dots(&mut s); + let big = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"ids": [big.0], "swatch": "Dots"})).unwrap(); + s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap(); + s.execute("pattern.options", &json!({"newName": "Spots"})).unwrap(); + assert!(is_pattern(&node(&s, big).appearance.fill_paint(), "Spots")); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + let d = doc(&s); + assert!(d.pattern("Dots").is_some() && d.pattern("Spots").is_none()); + assert!(d.swatch("Dots").is_some_and(|w| is_pattern(&w.paint, "Dots"))); + assert!(is_pattern(&node(&s, big).appearance.fill_paint(), "Dots")); + assert_eq!(pattern_uses(d, "Spots"), 0); + // When Save a Copy has taken the old name since, the pattern keeps its new name and paints. + s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap(); + s.execute("pattern.options", &json!({"newName": "Spots"})).unwrap(); + s.execute("object.pattern.saveCopy", &json!({"name": "Dots"})).unwrap(); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + let d = doc(&s); + assert!(d.pattern("Dots").is_some() && d.pattern("Spots").is_some()); + assert!(is_pattern(&node(&s, big).appearance.fill_paint(), "Spots")); +} + #[test] fn edit_then_cancel_restores_definition() { let mut s = session(); @@ -381,6 +561,187 @@ fn delete_pattern_unpaints_objects() { assert!(s.execute("pattern.delete", &json!({"name": "Dots"})).is_err()); } +/// Puts paints of pattern `name` where the layers do not reach: a symbol definition, another +/// pattern's tile, a graphic style, a character style, a type run, a color group's swatch and the +/// fill new art takes. +fn paint_outside_the_layers(s: &mut Session, name: &str) { + let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Hi"})).unwrap()); + let p = pattern_paint(name); + let d = doc_mut(s); + let shape = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)); + let art = Node::path(d.alloc_id(), shape, vectorcraft_doc::Appearance::basic(p.clone(), Paint::None, 0.0)); + d.symbols.push(vectorcraft_doc::Symbol { name: "Sym".into(), art: Arc::new(art.clone()), dynamic: false }); + d.patterns.push(vectorcraft_doc::pattern::PatternDef::new("Other", vec![Arc::new(art.clone())])); + d.graphic_styles.push(vectorcraft_doc::GraphicStyle { + name: "Style".into(), + appearance: (*art.appearance).clone(), + id: 0, + opacity: 1.0, + blend: Default::default(), + isolate: false, + knockout: Default::default(), + unit_box: true, + }); + let attrs = json!({"fill": p}); + d.char_styles.push(vectorcraft_doc::TextStyleDef { name: "Char".into(), attrs: attrs.as_object().unwrap().clone() }); + if let Some(NodeKind::Text(text)) = d.node_mut(t).map(|n| &mut n.kind) { + text.runs[0].style.fill = p.clone(); + } + d.swatch_groups.push(vectorcraft_color::SwatchGroup { + name: "Mine".into(), + swatches: vec![vectorcraft_color::Swatch { name: "Grouped".into(), paint: p.clone(), global: false, spot: false }], + }); + s.paint.fill = p; +} + +/// Delete Pattern clears the pattern's paints outside the layers too, and in the fill new art takes. +#[test] +fn delete_pattern_forgets_paints_outside_the_layers() { + let mut s = session(); + make_dots(&mut s); + paint_outside_the_layers(&mut s, "Dots"); + assert_eq!(pattern_uses(doc(&s), "Dots"), 7); + let v = s.execute("pattern.delete", &json!({"name": "Dots"})).unwrap(); + assert_eq!(v["unpainted"], 5, "the symbol, the other tile, the graphic style, the character style and the type"); + assert_eq!(pattern_uses(doc(&s), "Dots"), 0); + assert!(doc(&s).swatch("Grouped").is_none() && doc(&s).pattern("Other").is_some()); + assert!(s.paint.fill.is_none()); +} + +/// A Pattern Options rename renames the pattern's paints outside the layers too, and in the fill +/// new art takes. +#[test] +fn rename_pattern_reaches_paints_outside_the_layers() { + let mut s = session(); + make_dots(&mut s); + paint_outside_the_layers(&mut s, "Dots"); + s.execute("pattern.options", &json!({"name": "Dots", "newName": "Spots"})).unwrap(); + assert_eq!(pattern_uses(doc(&s), "Dots"), 0); + assert_eq!(pattern_uses(doc(&s), "Spots"), 7); + assert!(is_pattern(&s.paint.fill, "Spots")); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(is_pattern(&s.paint.fill, "Dots"), "Undo gives the fill its old name back"); +} + +/// A new graph whose stored series fill and stroke and value label fill and stroke are pattern +/// `name`, as a later redraw would give them to its marks and labels. +fn graph_painted_with(s: &mut Session, name: &str) -> NodeId { + let v = s.execute("graph.create", &json!({"type": "column", "x": 200, "y": 200, "width": 60, "height": 40, "csv": ",2024\nQ1,3\nQ2,5"})); + let id = id_of(&v.unwrap()); + let p = pattern_paint(name); + let mut extras = doc_mut(s).node_mut(id).unwrap().extras_mut(); + let spec = extras.graph.as_mut().unwrap(); + spec.series_paints = vec![vectorcraft_doc::SeriesPaint { fill: Some(p.clone()), stroke: Some(p.clone()), ..Default::default() }]; + spec.label_styles.values = Some(vectorcraft_doc::CharStyle { fill: p.clone(), stroke: p, ..Default::default() }); + id +} + +/// The series and label paints a graph stores, in order: series fill and stroke, then the value +/// labels' fill and stroke. +fn stored_graph_paints(s: &Session, id: NodeId) -> Vec { + let n = node(s, id); + let g = n.extras().graph.as_deref().unwrap(); + let series = g.series_paints.iter().flat_map(|p| [p.fill.clone(), p.stroke.clone()]).flatten(); + series.chain(g.label_styles.values.iter().flat_map(|st| [st.fill.clone(), st.stroke.clone()])).collect() +} + +/// Delete Pattern clears the series and label paints a graph stores, and a rename renames them, so +/// a later `graph.setData` draws no paint of a missing pattern. +#[test] +fn delete_and_rename_reach_a_graphs_stored_paints() { + let mut s = session(); + make_dots(&mut s); + let g = graph_painted_with(&mut s, "Dots"); + s.execute("pattern.options", &json!({"name": "Dots", "newName": "Spots"})).unwrap(); + assert!(stored_graph_paints(&s, g).iter().all(|p| is_pattern(p, "Spots")), "the rename reaches the graph"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(stored_graph_paints(&s, g).iter().all(|p| is_pattern(p, "Dots"))); + let v = s.execute("pattern.delete", &json!({"name": "Dots"})).unwrap(); + assert_eq!(v["unpainted"], 4, "the series fill and stroke and the value labels' fill and stroke"); + assert!(stored_graph_paints(&s, g).iter().all(Paint::is_none)); + s.execute("graph.setData", &json!({"id": g.0, "rows": [[2], [4]]})).unwrap(); + assert_eq!(pattern_uses(doc(&s), "Dots"), 0, "the redrawn graph holds no paint of the deleted pattern"); +} + +/// Canceling a new pattern clears the series and label paints a graph stores. +#[test] +fn cancel_new_pattern_reaches_a_graphs_stored_paints() { + let mut s = session(); + // The graph is made outside the editing layer, and its paints take the new pattern's name. + let g = graph_painted_with(&mut s, "Tiles"); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "Tiles"})).unwrap(); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + assert_eq!(stored_graph_paints(&s, g).len(), 4); + assert!(stored_graph_paints(&s, g).iter().all(Paint::is_none)); + assert_eq!(pattern_uses(doc(&s), "Tiles"), 0); +} + +/// With New Art Has Basic Appearance off, Redo of Delete Pattern gives new art the paints the +/// command left, the selected object's appearance taken after the pattern's fill was cleared. +#[test] +fn redo_of_delete_pattern_keeps_the_inherited_new_art_paints() { + let mut s = session(); + let r = make_dots(&mut s); + s.prefs.new_art_basic = false; + sel(&mut s, &[r]); + s.paint.fill = pattern_paint("Dots"); + s.execute("pattern.delete", &json!({"name": "Dots"})).unwrap(); + let after = s.paint.clone(); + assert!(!is_pattern(&after.fill, "Dots")); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.paint, after); +} + +/// A Pattern Options rename tried as a preview changes the fill new art takes only while the +/// preview stands: another preview and Cancel start from the fill the interaction began with. +/// Keeping the preview keeps the rename, and Undo takes it back. +#[test] +fn rename_previews_restore_the_fill_new_art_takes() { + let mut s = session(); + make_dots(&mut s); + s.paint.fill = pattern_paint("Dots"); + s.begin_interaction("Pattern Options").unwrap(); + s.preview("pattern.options", &json!({"name": "Dots", "newName": "Spots"})).unwrap(); + assert!(is_pattern(&s.paint.fill, "Spots")); + s.preview("pattern.options", &json!({"name": "Dots", "newName": "Tiles"})).unwrap(); + assert!(is_pattern(&s.paint.fill, "Tiles")); + s.cancel_interaction().unwrap(); + assert!(is_pattern(&s.paint.fill, "Dots") && doc(&s).pattern("Dots").is_some()); + s.begin_interaction("Pattern Options").unwrap(); + s.preview("pattern.options", &json!({"name": "Dots", "newName": "Spots"})).unwrap(); + s.commit_interaction().unwrap(); + assert!(is_pattern(&s.paint.fill, "Spots") && doc(&s).pattern("Spots").is_some()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(is_pattern(&s.paint.fill, "Dots") && doc(&s).pattern("Dots").is_some()); +} + +/// With New Art Has Basic Appearance off, a canceled rename preview leaves new art with the +/// appearance of the selected object as the document has it again, so no paint of the previewed +/// name is left. +#[test] +fn canceled_rename_preview_leaves_no_inherited_paint_of_the_new_name() { + let mut s = session(); + make_dots(&mut s); + let big = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"ids": [big.0], "swatch": "Dots"})).unwrap(); + s.prefs.new_art_basic = false; + sel(&mut s, &[big]); + s.paint = vectorcraft_tools::PaintDefaults::default(); + s.begin_interaction("Pattern Options").unwrap(); + s.preview("pattern.options", &json!({"name": "Dots", "newName": "Spots"})).unwrap(); + s.cancel_interaction().unwrap(); + assert!(doc(&s).pattern("Dots").is_some() && doc(&s).pattern("Spots").is_none()); + let items = s.paint.appearance.iter().flat_map(|a| a.items.iter()).map(|it| match it { + vectorcraft_doc::AppearanceItem::Fill(f) => f.paint.clone(), + vectorcraft_doc::AppearanceItem::Stroke(k) => k.paint.clone(), + }); + let paints: Vec = [s.paint.fill.clone(), s.paint.stroke.clone()].into_iter().chain(items).collect(); + assert!(paints.iter().all(|p| !is_pattern(p, "Spots")), "{paints:?}"); +} + #[test] fn transform_patterns_only_moves_placement() { let mut s = session(); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 0224d59b38..cc4460d250 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -235,8 +235,16 @@ fn live_effect_plugins_reshape_editable_art_and_expand() { run(&mut s, "select.all", json!({})); run(&mut s, "object.move", json!({"dx": 50, "dy": 0})); assert_eq!(effected(&s), *node(&s, a).path_data().unwrap()); + // A parameter of another type than the manifest gives it is refused. + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let wrong = json!({"ids": [a.0], "effect": "plugin.test.engine.tri", "params": {"size": "4 pt"}}); + let e = s.execute("effect.apply", &wrong).unwrap_err().to_string(); + assert!(e.contains("`size` must be a number"), "{e}"); + assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before); run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "plugin.test.engine.tri", "params": {"size": 4}})); assert_eq!(effected(&s), triangle()); + let e = s.execute("effect.setParams", &json!({"ids": [a.0], "index": 1, "params": {"size": true}})).unwrap_err().to_string(); + assert!(e.contains("`size` must be a number"), "{e}"); assert_eq!(node(&s, a).appearance.effects[1].params, json!({"size": 4})); // Uninstalled: the geometry is drawn as it is. run(&mut s, "plugin.remove", json!({"id": "test.engine.tri"})); diff --git a/crates/engine/src/tests/print.rs b/crates/engine/src/tests/print.rs index 8ccd76deba..f10bf65c94 100644 --- a/crates/engine/src/tests/print.rs +++ b/crates/engine/src/tests/print.rs @@ -254,6 +254,35 @@ fn type_in_a_missing_family_warns_as_pdf_export_does() { } } +/// The warnings of `file.print` (PDF and PostScript) and `print.preview` list what the job +/// leaves out of the document or prints differently first, then the notes on the options. +#[test] +fn what_a_print_loses_comes_before_the_notes_on_the_options() { + let (mut s, _) = session(); + s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap(); + let notes = |v: &Value| -> Vec { v["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect() }; + // A fixed flatness isn't written to a PDF: a note on the options, made before the type's. + let fixed = json!({"settings": {"graphics": {"autoFlatness": false}}}); + for v in [print(&mut s, fixed.clone()).1, s.execute("print.preview", &fixed).unwrap()] { + let n = notes(&v); + assert!(n.iter().any(|w| w.contains("Nonexistent Sans Probe")), "{n:?}"); + assert!(n.last().is_some_and(|w| w.starts_with("a fixed flatness")), "{n:?}"); + } + // PostScript doesn't apply the printer profile. + let profile = json!({"format": "postscript", "settings": {"color": {"profile": vectorcraft_color::cms::SRGB}}}); + let n = notes(&s.execute("file.print", &profile).unwrap()); + assert!(n.iter().any(|w| w.contains("Nonexistent Sans Probe")), "{n:?}"); + assert!(n.last().is_some_and(|w| w.starts_with("the printer profile")), "{n:?}"); + // An artboard larger than Letter: copies per sheet that don't fit come after the art that + // doesn't print. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 700, "height": 900})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 700, "height": 900})).unwrap(); + let n = notes(&print(&mut s, json!({"settings": {"copiesPerSheet": true}})).1); + assert!(n.iter().any(|w| w.contains("part of it doesn't print")), "{n:?}"); + assert!(n.last().is_some_and(|w| w.ends_with("it prints one copy per sheet")), "{n:?}"); +} + #[test] fn type_that_does_not_fit_its_frame_is_named() { let (mut s, _) = session(); 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/engine/src/tests/stored_path.rs b/crates/engine/src/tests/stored_path.rs new file mode 100644 index 0000000000..3e3bd4ef95 --- /dev/null +++ b/crates/engine/src/tests/stored_path.rs @@ -0,0 +1,202 @@ +//! `select.storedPath`, the Actions panel's Select Path step: the step stores a path's id and a +//! fingerprint of it, and playback selects that path only while it is still there unchanged and +//! can be selected. + +use std::io::Write; + +use serde_json::{Value, json}; + +use crate::*; + +/// A document with two rectangles and an ellipse, nothing selected → the session and their ids. +fn doc() -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let mut add = |shape: &str, x: u32| s.execute(shape, &json!({"x": x, "y": 10, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let ids = [add("shape.rectangle", 10), add("shape.rectangle", 80), add("shape.ellipse", 150)]; + s.execute("select.none", &json!({})).unwrap(); + (s, ids) +} + +fn select(s: &mut Session, ids: &[u64]) { + s.execute("select.set", &json!({"ids": ids})).unwrap(); +} + +fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect() +} + +/// The Select Path step's params for `id`, selected alone. +fn step_for(s: &mut Session, id: u64) -> Value { + select(s, &[id]); + stored_path_step(s.doc().unwrap()).unwrap() +} + +#[test] +fn the_hash_is_fnv_1a_64() { + // The published FNV-1a 64-bit test values for "", "a" and "foobar". + for (bytes, want) in [(&b""[..], 0xcbf2_9ce4_8422_2325_u64), (b"a", 0xaf63_dc4c_8601_ec8c), (b"foobar", 0x8594_4171_f739_67e8)] { + let mut h = crate::cmd::select::Fnv::default(); + h.write_all(bytes).unwrap(); + assert_eq!(h.0, want, "{bytes:?}"); + } +} + +#[test] +fn the_step_stores_the_id_and_a_fingerprint_and_plays_by_selecting_the_path() { + let (mut s, [a, b, _]) = doc(); + let p = step_for(&mut s, a); + assert_eq!(p["id"], json!(a)); + let fingerprint = p["fingerprint"].as_str().unwrap(); + assert!(fingerprint.starts_with("v1:") && fingerprint.len() == 19, "{fingerprint}"); + assert_eq!(step_for(&mut s, a), p, "the same path gives the same step"); + assert_ne!(step_for(&mut s, b)["fingerprint"], p["fingerprint"], "another path gives another fingerprint"); + select(&mut s, &[b]); + let r = s.execute("select.storedPath", &p).unwrap(); + assert_eq!(r, json!({"count": 1, "ids": [a]})); + assert_eq!(selected(&s), [a], "only the stored path is selected"); +} + +#[test] +fn a_compound_path_is_one_step_and_a_path_in_a_group_is_one_too() { + let (mut s, [a, b, c]) = doc(); + select(&mut s, &[a, b]); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let p = step_for(&mut s, compound); + let member = s.doc().unwrap().doc.children(Some(vectorcraft_doc::NodeId(compound))).unwrap()[0].id.0; + select(&mut s, &[member]); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), "select one whole path or compound path", "a member alone is not stored"); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.storedPath", &p).unwrap(); + assert_eq!(selected(&s), [compound]); + + select(&mut s, &[c, compound]); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), "select one whole path or compound path", "a group is not stored"); + let inner = step_for(&mut s, c); + select(&mut s, &[group]); + s.execute("select.storedPath", &inner).unwrap(); + assert_eq!(selected(&s), [c], "the path inside the group is selected alone"); +} + +#[test] +fn only_one_whole_path_that_can_be_selected_is_stored() { + let (mut s, [a, b, _]) = doc(); + let whole = "select one whole path or compound path"; + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), "select a path"); + select(&mut s, &[a, b]); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), "select only one path"); + s.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap(); + select(&mut s, &[a]); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert_eq!(s.doc().unwrap().selection.guides.len(), 1, "the guide is selected with the path"); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), "select only one path", "a path with a guide"); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap(), step_for(&mut s, a), "the path alone again"); + s.execute("select.anchors", &json!({"id": a, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), whole, "an anchor alone"); + let t = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "Type"})).unwrap()["id"].as_u64().unwrap(); + select(&mut s, &[t]); + assert_eq!(stored_path_step(s.doc().unwrap()).unwrap_err(), whole, "type"); + select(&mut s, &[a]); + s.execute("object.lock", &json!({})).unwrap(); + let mut st = s.doc().unwrap().clone(); + st.selection.objects = vec![vectorcraft_doc::NodeId(a)]; + assert_eq!(stored_path_step(&st).unwrap_err(), "the path is hidden or locked, or cannot be selected here"); + let guide = { + let mut d = (*st.doc).clone(); + if let Some(vectorcraft_doc::NodeKind::Path { guide, .. }) = d.node_mut(vectorcraft_doc::NodeId(a)).map(|n| &mut n.kind) { + *guide = true; + } + d + }; + assert!(path_fingerprint(guide.node(vectorcraft_doc::NodeId(a)).unwrap()).is_none(), "a guide is not stored"); +} + +#[test] +fn a_changed_missing_hidden_or_other_path_is_an_error_and_keeps_the_selection() { + let (mut s, [a, b, c]) = doc(); + let p = step_for(&mut s, a); + let fails = |s: &mut Session, p: &Value, want: &str| { + select(s, &[c]); + let e = s.execute("select.storedPath", p).unwrap_err().to_string(); + assert!(e.contains(want), "{e}"); + assert_eq!(selected(s), [c], "the selection stays as it was"); + }; + select(&mut s, &[a]); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + fails(&mut s, &p, "is not the stored path"); + let moved = step_for(&mut s, a); + s.execute("object.hide", &json!({})).unwrap(); + fails(&mut s, &moved, "hidden or locked"); + s.execute("object.showAll", &json!({})).unwrap(); + let shown = step_for(&mut s, b); + s.execute("edit.clear", &json!({})).unwrap(); + fails(&mut s, &shown, "no such object id"); + // Another document: the id names another path there, or nothing. + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 7, "height": 9})).unwrap(); + let c2 = s.execute("shape.ellipse", &json!({"x": 20, "y": 20, "width": 9, "height": 7})).unwrap()["id"].as_u64().unwrap(); + select(&mut s, &[c2]); + assert!(s.execute("select.storedPath", &moved).is_err()); + assert_eq!(selected(&s), [c2]); +} + +#[test] +fn a_path_on_a_locked_artboard_is_refused_in_isolation_mode_too() { + let (mut s, [a, b, _]) = doc(); + select(&mut s, &[a, b]); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let p = step_for(&mut s, a); + s.execute("select.none", &json!({})).unwrap(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + s.execute("artboard.new", &json!({"x": 0, "y": 0, "width": 300, "height": 200})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the group stays isolated"); + assert!(s.doc().unwrap().doc.on_locked_artboard(vectorcraft_doc::NodeId(a)), "the path is on the locked artboard"); + let mut st = s.doc().unwrap().clone(); + st.selection.objects = vec![vectorcraft_doc::NodeId(a)]; + assert_eq!(stored_path_step(&st).unwrap_err(), "the path is hidden or locked, or cannot be selected here", "capture"); + let before = selected(&s); + let e = s.execute("select.storedPath", &p).unwrap_err().to_string(); + assert!(e.contains("hidden or locked"), "{e}"); + assert_eq!(selected(&s), before, "the selection stays as it was"); +} + +#[test] +fn a_failing_step_in_a_batch_undoes_the_steps_before_it() { + let (mut s, [a, _, c]) = doc(); + let p = step_for(&mut s, a); + select(&mut s, &[a]); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + select(&mut s, &[c]); + let before = s.doc().unwrap().doc.clone(); + let steps = [json!({"command": "object.move", "params": {"dx": 1, "dy": 0}}), json!({"command": "select.storedPath", "params": p})]; + assert!(s.execute("command.batch", &json!({"commands": steps})).is_err()); + assert!(s.doc().unwrap().doc == before, "the move before the step is undone"); +} + +#[test] +fn params_are_an_id_and_a_v1_fingerprint() { + let (mut s, [a, ..]) = doc(); + let p = step_for(&mut s, a); + let f = p["fingerprint"].clone(); + for bad in [ + json!({"fingerprint": f}), + json!({"id": -1, "fingerprint": f}), + json!({"id": "1", "fingerprint": f}), + json!({"id": a}), + json!({"id": a, "fingerprint": 5}), + json!({"id": a, "fingerprint": "v2:0123456789abcdef"}), + json!({"id": a, "fingerprint": "v1:0123456789ABCDEF"}), + json!({"id": a, "fingerprint": "v1:0123456789abcde"}), + json!({"id": a, "fingerprint": f, "extra": 1}), + json!([a]), + ] { + assert!(stored_path_params(&bad).is_err(), "{bad}"); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("select.storedPath", &bad).is_err(), "{bad}"); + assert!(selected(&s).is_empty(), "{bad}"); + } + assert!(stored_path_params(&p).is_ok()); +} diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 54c653e938..8e3830c81c 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -1190,6 +1190,32 @@ fn distort_rejects_malformed_coordinates_and_ids_without_editing_art() { assert_eq!(undo_len(&s), history + 1); } +/// `object.distort` with `angle` reads `from` as a box in the frame turned by it, as the Free +/// Transform tool sends a turned bounding box: corners where that box already stands leave the art. +#[test] +fn distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let original = bounds(&s, a); + let bx = vectorcraft_doc::OrientedBox { angle: 90.0, rect: Rect::new(-100.0, 0.0, 0.0, 100.0) }; + let corners: Vec = bx.corners().iter().map(|c| json!([c.x, c.y])).collect(); + let history = undo_len(&s); + for p in [ + json!({"corners": corners, "from": [-100, 0, 0, 100], "angle": "90", "ids": [a.0]}), + json!({"corners": corners, "from": [-100, 0, 0, 100], "angle": [90], "ids": [a.0]}), + ] { + assert!(s.execute("object.distort", &p).is_err(), "invalid input: {p}"); + assert!(close(bounds(&s, a), original)); + assert_eq!(undo_len(&s), history); + } + s.execute("object.distort", &json!({"corners": corners, "from": [-100, 0, 0, 100], "angle": 90, "ids": [a.0]})).unwrap(); + assert!(close(bounds(&s, a), original), "{:?}", bounds(&s, a)); + assert_eq!(undo_len(&s), history + 1); + // Without `from`, the box is the objects' bounds in the turned frame: the same box here. + s.execute("object.distort", &json!({"corners": corners, "angle": 90, "ids": [a.0]})).unwrap(); + assert!(close(bounds(&s, a), original), "{:?}", bounds(&s, a)); +} + /// `artboard.move` and `artboard.delete` take several artboards at once (#1139): one undo step /// each, the art on each moving with it, and one artboard always left. #[test] diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 4688845de4..52be19a952 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3,7 +3,8 @@ //! (`.vcflattener`) and export preset (`.vcexportpresets`) libraries, shortcut sets and action sets other apps save as text (`.kys`, `.aia`), and native files (compressed, damaged, saved for older versions), //! must load as an error or as a document that then renders and exports, without a panic; nor may //! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records -//! of every kind with random contents) opened, placed or pasted, nor EPS and PostScript files +//! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files, +//! opcodes with random contents) opened or placed, nor EPS and PostScript files //! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of //! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents //! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor the @@ -2938,6 +2939,106 @@ proptest! { } } +// ---------- PICT pictures: opened and placed ---------- + +fn be16(v: &[i16]) -> Vec { + v.iter().flat_map(|x| x.to_be_bytes()).collect() +} + +/// A version 2 PICT file of a 200 × 100 pt frame holding `ops`, each padded to an even length. +fn pict_of(ops: &[(u16, Vec)]) -> Vec { + let mut b = vec![0; 512]; + b.extend(be16(&[0, 0, 0, 100, 200])); + b.extend([0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]); + b.extend(be16(&[-1, 0])); + b.extend([0; 20]); + for (op, data) in ops { + b.extend(op.to_be_bytes()); + b.extend(data); + if b.len() % 2 == 1 { + b.push(0); + } + } + b.extend([0x00, 0xFF]); + b +} + +/// A picture with shapes, a region, text, a pattern and a packed pixel map. +fn pict_sample() -> Vec { + let region = [be16(&[36, 0, 0, 20, 20]), be16(&[0, 0, 20, 0x7FFF, 10, 10, 20, 0x7FFF, 20, 0, 10, 0x7FFF, 0x7FFF])].concat(); + let table = be16(&[0, 0, 0, 1, 0, -1, 0, 0, 1, 0, 0, -1]); + let pixmap = [ + be16(&[0x8008u16 as i16, 0, 0, 2, 8]), + be16(&[0, 0, 0, 0, 72, 0, 72, 0, 0, 8, 1, 8, 0, 0, 0, 0, 0, 0]), + table, + be16(&[0, 0, 2, 8, 10, 20, 14, 36, 0]), + vec![2, 0xF9, 0, 9, 7, 1, 0, 1, 0, 1, 0, 1, 0], + ] + .concat(); + pict_of(&[ + (0x1A, be16(&[-1, 0, 0])), + (0x07, be16(&[2, 2])), + (0x31, be16(&[10, 20, 50, 80])), + (0x30, be16(&[10, 20, 50, 80])), + (0x0B, be16(&[8, 8])), + (0x41, be16(&[0, 100, 40, 160])), + (0x51, be16(&[50, 100, 90, 160])), + (0x61, be16(&[0, 0, 60, 60, 30, 120])), + (0x71, be16(&[22, 0, 0, 40, 40, 0, 0, 40, 40, 0, 40])), + (0x81, region.clone()), + (0x01, region), + (0x20, be16(&[70, 10, 70, 190])), + (0x21, be16(&[90, 100])), + (0x0A, vec![0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55]), + (0x34, be16(&[0, 0, 10, 10])), + (0x2C, [be16(&[9, 3]), vec![6], b"Geneva".to_vec()].concat()), + (0x0D, be16(&[12])), + (0x28, [be16(&[80, 10]), vec![3], b"abc".to_vec()].concat()), + (0x98, pixmap), + ]) +} + +/// The sample the mutations start from opens with art and an image. +#[test] +fn the_pict_sample_opens() { + let l = vectorcraft_engine::cmd::fileio::load("x.pct", &pict_sample()).unwrap(); + assert_eq!(l.format.id, "pict"); + let (mut paths, mut images, mut texts) = (0, 0, 0); + l.doc.walk(|n| match n.kind { + vectorcraft_doc::NodeKind::Path { .. } => paths += 1, + vectorcraft_doc::NodeKind::Image(_) => images += 1, + vectorcraft_doc::NodeKind::Text(_) => texts += 1, + _ => {} + }); + assert!(paths > 8 && images == 1 && texts == 1, "{paths} paths, {images} images, {texts} texts, warnings {:?}", l.warnings); +} + +/// PICT opcodes VectorCraft reads, and reserved ones it skips. +const PICT_OPS: [u16; 40] = [ + 0x01, 0x03, 0x04, 0x07, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x12, 0x13, 0x14, 0x1A, 0x1B, 0x20, 0x21, 0x22, 0x23, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x30, + 0x31, 0x38, 0x41, 0x51, 0x61, 0x71, 0x81, 0x90, 0x91, 0x98, 0x99, 0x9A, 0x9B, 0xA1, 0x8200, 0x0024, +]; + +proptest! { + #![proptest_config(config())] + + #[test] + fn mutated_pict_pictures_never_panic(cut in 0usize..4096, edits in prop::collection::vec((0usize..4096, any::()), 0..16)) { + let mut bytes = pict_sample(); + let n = bytes.len(); + for &(at, b) in &edits { + bytes[512 + at % (n - 512)] = b; + } + bytes.truncate(cut.max(512)); + survive_metafile("mutated PICT", "x.pct", &bytes)?; + } + + #[test] + fn random_pict_opcodes_never_panic(ops in prop::collection::vec((prop::sample::select(PICT_OPS.to_vec()), arb_body()), 0..32)) { + survive_metafile("PICT opcodes", "x.pct", &pict_of(&ops))?; + } +} + // ---------- HP-GL plot files: opened and placed ---------- /// A plot file with every kind of instruction the reader plays, printer escapes around it. diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 43d93cec25..ed98d620bf 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -3943,6 +3943,42 @@ fn korean_line_break_anywhere_is_reported_only_for_korean_paragraphs() { } } +/// The text document holds no Mojikumi set: a paragraph with any of the predefined sets other +/// than None is reported as left out, and reads back without the set; None and Line-end +/// Punctuation Half Width are not reported. +#[test] +fn predefined_mojikumi_sets_are_reported_as_left_out() { + use vectorcraft_doc::{Mojikumi, TextObject}; + for (set, reported) in [ + (Mojikumi::None, false), + (Mojikumi::LineEndHalf, false), + (Mojikumi::YakumonoHankaku, true), + (Mojikumi::GyomatsuYakumonoHankaku, true), + (Mojikumi::GyomatsuYakumonoZenkaku, true), + (Mojikumi::YakumonoZenkaku, true), + ] { + let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "「かな」。", style(14.0, Color::BLACK)); + t.para.mojikumi = set; + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(!out.warnings.is_empty(), reported, "{set:?}: {:?}", out.warnings); + let mut all = vec![]; + paths(&read_back(&doc).layers, &mut all); + let sets: Vec = all + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.para_at(0).mojikumi), + _ => None, + }) + .collect(); + assert_eq!(sets.len(), 1, "{set:?}"); + assert!(matches!(sets[0], Mojikumi::None | Mojikumi::LineEndHalf), "{set:?} reads back as {:?}", sets[0]); + } +} + /// The text document has no Bunri-Kinshi: a paragraph with it on and an inseparable pair in it is /// reported as left out, and comes back off; with it off, or with no pair, nothing is reported. #[test] @@ -4423,7 +4459,7 @@ fn type_attributes_the_data_cant_hold_are_reported() { let back = read_back(&doc); assert!(matches!(back.layers[0].children().unwrap()[0].kind, NodeKind::Text(_))); // Any other attribute the text document doesn't hold is reported too: No Break, a paragraph's - // left-to-right direction set on it, Optical Margin Alignment, a font version, a font that isn't + // left-to-right direction set on it, Optical Margin Alignment, a font that isn't // installed whose name doesn't come back (a hyphen in its family), a Lab color, // small capitals at another size, right-to-left letters aligned to the start of a paragraph // without a direction of its own, tracking that isn't a whole number. @@ -4432,7 +4468,6 @@ fn type_attributes_the_data_cant_hold_are_reported() { |t| t.runs[0].style.tracking = 12.5, |t| t.para.direction = Some(vectorcraft_doc::ParaDirection::LeftToRight), |t| t.optical_margin = true, - |t| t.runs[0].style.font_version = Some("2.0".into()), |t| t.runs[0].style.font_family = "my-missing font".into(), |t| t.runs[0].style.fill = Paint::solid(MINT), |t| t.runs[0].style.small_caps = Some(80.0), @@ -4455,11 +4490,130 @@ fn type_attributes_the_data_cant_hold_are_reported() { missing.runs[0].style.font_family = "Missing Sans Probe".into(); missing.runs[0].style.font_style = "Bold Italic".into(); assert!(with(missing).is_empty()); + // A version that isn't installed draws in the face the font resolves to, and comes back in it. + let mut uninstalled = t.clone(); + uninstalled.runs[0].style.font_version = Some("2.0".into()); + assert!(with(uninstalled).is_empty()); edit(&mut t); assert_eq!(with(t), [writer::TYPE_ATTRIBUTES]); } } +/// Installs the copies of each font `copies` lists, the first of each loaded first. +fn install_copies(copies: &[(bool, vectorcraft_text::test_fonts::CopyNames<'_>)]) { + for (inter, names) in copies { + let font = vectorcraft_text::test_fonts::named_copy(*inter, *names).unwrap(); + assert_eq!(vectorcraft_text::FontDb::global().add_font(font), 1, "{names:?}"); + } +} + +/// A run's text, font family and font version, as [`fonts_saved`] reads them back. +type SavedRun = (String, String, Option); + +/// A 200 × 100 document of point type whose runs are `runs` (text, family, version). +fn runs_doc(runs: &[(&str, &str, Option<&str>)]) -> Document { + use vectorcraft_doc::{CharStyle, TextObject, TextRun}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut t = TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "", style(18.0, Color::BLACK)); + t.runs = runs + .iter() + .map(|(text, family, version)| { + let st = CharStyle { font_family: (*family).into(), font_version: version.map(Into::into), ..style(18.0, Color::BLACK) }; + TextRun::new(*text, st) + }) + .collect(); + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + doc +} + +/// [`runs_doc`] saved and read back: the save's warnings, and the runs read back. +fn fonts_saved(runs: &[(&str, &str, Option<&str>)]) -> (Vec, Vec) { + let doc = runs_doc(runs); + let warnings = export_ai_editing(&doc, &opts()).unwrap().warnings; + let back = read_back(&doc); + let NodeKind::Text(t) = &back.layers[0].children().unwrap()[0].kind else { panic!("type comes back as type") }; + (warnings, t.runs.iter().map(|r| (r.text.clone(), r.style.font_family.clone(), r.style.font_version.clone())).collect()) +} + +/// How many fonts the font set of [`runs_doc`] names, the hidden characters' font aside. +fn fonts_written(runs: &[(&str, &str, Option<&str>)]) -> usize { + text_document(&program(&runs_doc(runs))).matches("/CoolTypeFont").count() - 1 +} + +/// Type in a font installed beside a family spelled alike but for case and punctuation +/// (`Sample/Ink`, PostScript name `SampleInk`, beside `SAMPLE INK`), or beside a copy whose +/// PostScript name differs only in case (the type naming its version), is written under its +/// PostScript name and read back in its own family and version, so nothing about its font is +/// reported lost. +#[test] +fn type_in_a_font_beside_a_family_spelled_alike_keeps_its_font() { + install_copies(&[ + (true, ("SAVETEST INK", "Regular", "Version 1.000", "SAVETESTINK-Regular")), + (false, ("Savetest/Ink", "Regular", "Version 1.000", "SavetestInk")), + (true, ("CASESAVE INK", "Regular", "Version 1.000", "CASESAVEINK")), + (false, ("Casesave Ink", "Regular", "Version 2.000", "CasesaveInk")), + ]); + let (warnings, back) = fonts_saved(&[("Kept", "Savetest/Ink", None)]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back, [("Kept".to_string(), "Savetest/Ink".to_string(), None)]); + let (warnings, back) = fonts_saved(&[("Kept", "Casesave Ink", Some("Version 2.000"))]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back, [("Kept".to_string(), "Casesave Ink".to_string(), Some("Version 2.000".to_string()))]); +} + +/// Type in a static font's version that the family and style don't resolve to (two installed +/// copies of one PostScript name, family and style) is written with that version (`/5`) and comes +/// back in it, without a note; two runs in two versions are two fonts of the set. +#[test] +fn type_in_another_version_of_a_static_font_keeps_it() { + install_copies(&[(true, ("Rttest Ink", "Regular", "1.0", "RttestInk-Regular")), (false, ("Rttest Ink", "Regular", "1.1", "RttestInk-Regular"))]); + let (warnings, back) = fonts_saved(&[("Kept", "Rttest Ink", Some("1.1"))]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back, [("Kept".to_string(), "Rttest Ink".to_string(), Some("1.1".to_string()))]); + let (warnings, back) = fonts_saved(&[("Old", "Rttest Ink", None), ("New", "Rttest Ink", Some("1.1"))]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back, [("Old".to_string(), "Rttest Ink".to_string(), None), ("New".to_string(), "Rttest Ink".to_string(), Some("1.1".to_string()))]); + // A run naming the version its family and style resolve to anyway, or one that isn't + // installed, is in the same face as a run naming none: one font of the set, and no note. + let (warnings, back) = fonts_saved(&[("Same", "Rttest Ink", Some("1.0")), ("Gone", "Rttest Ink", Some("9.9")), ("Plain", "Rttest Ink", None)]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(back.iter().all(|(_, family, version)| family == "Rttest Ink" && version.is_none()), "{back:?}"); + assert_eq!(fonts_written(&[("Same", "Rttest Ink", Some("1.0")), ("Gone", "Rttest Ink", Some("9.9")), ("Plain", "Rttest Ink", None)]), 1); +} + +/// Type in the copy of a font that its family names, beside a copy of the same PostScript name in +/// another family that the name alone gives first, is written with its version (`/5`), so it comes +/// back in its own copy and family, without a note. +#[test] +fn type_in_a_copy_its_postscript_name_alone_doesnt_give_keeps_it() { + install_copies(&[ + (true, ("RvdupsaveInk", "Regular", "2.0", "RvdupsaveInk-Regular")), + (false, ("Rvdupsave Ink", "Regular", "1.0", "RvdupsaveInk-Regular")), + ]); + let (warnings, back) = fonts_saved(&[("Kept", "Rvdupsave Ink", None)]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back.iter().map(|r| r.1.as_str()).collect::>(), ["Rvdupsave Ink"]); + let (warnings, back) = fonts_saved(&[("Kept", "RvdupsaveInk", None)]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(back.iter().map(|r| r.1.as_str()).collect::>(), ["RvdupsaveInk"]); +} + +/// A version string longer than the reader takes (256 bytes) isn't one it can pick a copy by: type +/// in such a copy, which its name alone doesn't give back, is reported as losing its font. +#[test] +fn a_version_longer_than_the_reader_takes_is_reported() { + let long = "9".repeat(300); + install_copies(&[ + (true, ("Longtest Ink", "Regular", "1.0", "LongtestInk-Regular")), + (false, ("Longtest Ink", "Regular", &long, "LongtestInk-Regular")), + ]); + let (warnings, back) = fonts_saved(&[("Long", "Longtest Ink", Some(&long))]); + assert_eq!(warnings, [writer::TYPE_ATTRIBUTES]); + assert_eq!(back, [("Long".to_string(), "Longtest Ink".to_string(), None)]); +} + /// On a large canvas, area type, threaded frames and type on a path stay type: the frames and /// lengths are written at the canvas's scale. Frames of a thread at two scales, and area type /// scaled by two factors, are written as outlines. 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/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 1e47ca1564..b161ec636f 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -338,6 +338,8 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { CharStyle { font_family: s.font_family.clone(), font_style: s.font_style.clone(), + // The font record's version (`/5`) names the face; whether it comes back is `font_kept`'s. + font_version: s.font_version.clone(), size: s.size, leading: s.leading, tracking: s.tracking.round(), @@ -452,15 +454,17 @@ struct FontRecord { /// the font's order, in the axis's own units. Empty for a static font, which has none: without /// it, an app that opens the file takes a variable font's default instance (#6388). design: Vec, - /// For a variable font, its version string (`/5`, name ID 5); empty for a static font. + /// Its version string (`/5`, name ID 5): for a variable font, and for a static font whose + /// PostScript name alone gives the reader another installed copy (two copies of one font, see + /// the reader's `document_font`); else empty. version: String, } -/// The font the font set names for style `st`: an installed face's PostScript name, and for a -/// variable font the setting of each of its axes (the named instance's, or the style's own -/// Variable Font setting, clamped to the axis as layout clamps it) and its version; else its family -/// and style as `family-style` (the family alone for Regular), the form the reader's -/// `family_style` splits. +/// The font the font set names for style `st`: an installed face's PostScript name, its version +/// for a variable font or when the name alone gives the reader another installed copy, and for a +/// variable font the setting of each of its axes (the named instance's, or the style's own Variable +/// Font setting, clamped to the axis as layout clamps it); else its family and style as +/// `family-style` (the family alone for Regular), the form the reader's `family_style` splits. fn font_name(st: &CharStyle) -> FontRecord { let db = vectorcraft_text::FontDb::global(); // The face of that family and style (the font database gives a fallback face for others). @@ -479,8 +483,11 @@ fn font_name(st: &CharStyle) -> FontRecord { set.map_or(own, |v| (v as f32).clamp(a.min.min(a.max), a.max.max(a.min))) }) .collect(); - let version = if design.is_empty() { String::new() } else { face.version.clone() }; - FontRecord { name: face.postscript_name(), truetype: face.is_truetype(), design, version } + let name = face.postscript_name(); + // The reader takes the face of a name alone as `postscript_face` finds it. + let by_name = crate::import::postscript_face(&name, None).is_some_and(|f| f.id() == face.id()); + let version = if design.is_empty() && by_name { String::new() } else { face.version.clone() }; + FontRecord { name, truetype: face.is_truetype(), design, version } } None if st.font_style.is_empty() || st.font_style == "Regular" => record(st.font_family.clone()), None => record(format!("{}-{}", st.font_family, st.font_style.replace(' ', ""))), @@ -518,12 +525,19 @@ fn fixed(v: f32) -> i64 { if v.is_finite() { (f64::from(v) * 65536.0).round() as i64 } else { 0 } } -/// Does the font of style `st` come back as itself: the family and style the reader makes of the -/// name it is written under (as its `char_style` does)? +/// Does the font of style `st` come back as itself: are the family and style the reader makes of +/// the record it is written as (its name, and its version as the reader takes it, as its +/// `char_style` does) the style's own, and the face they and the version read back resolve to the +/// face of the style? A version that isn't installed draws in the face the font resolves to anyway. fn font_kept(st: &CharStyle) -> bool { - let (family, style) = crate::family_style(&font_name(st).name); - let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); - family == st.font_family && style == st.font_style + let record = font_name(st); + let version = crate::import::record_version(&record.version); + let (family, style, read) = crate::import::document_font(&record.name, version); + let db = vectorcraft_text::FontDb::global(); + let face = |family: &str, style: &str, version: Option<&str>| db.face_version(family, style, version).map(|f| f.id()); + family == st.font_family + && style == st.font_style + && face(&family, &style, read.as_deref()) == face(&st.font_family, &st.font_style, st.font_version.as_deref()) } /// Whether `c` is a strong right-to-left letter (`Some(true)`: Hebrew, Arabic, Syriac, Thaana, NKo @@ -1022,13 +1036,13 @@ impl TextDoc { .iter() .map(|f| { let mut font = vec![(0, V::Str(f.name.clone())), (2, V::Int(i64::from(f.truetype)))]; - // A variable font's place in its design space and its version (#6388); a static - // font has neither. + // A variable font's place in its design space (#6388), and the version of a + // variable font or of a static one its name alone doesn't give back. if !f.design.is_empty() { font.push((4, V::List(f.design.iter().map(|v| V::Int(fixed(*v))).collect()))); - if !f.version.is_empty() { - font.push((5, V::Str(f.version.clone()))); - } + } + if !f.version.is_empty() { + font.push((5, V::Str(f.version.clone()))); } dict(vec![(99, V::Name("CoolTypeFont")), (0, dict(font))]) }) diff --git a/crates/eps/src/dcs.rs b/crates/eps/src/dcs.rs new file mode 100644 index 0000000000..1de21a4afe --- /dev/null +++ b/crates/eps/src/dcs.rs @@ -0,0 +1,491 @@ +//! DCS files (Desktop Color Separation): an EPS file whose header comments point at one EPS +//! program per printing plate. A DCS 2.0 file names each plate with `%%PlateFile: (name) EPS +//! #offset size`, the plate inside the file `offset` bytes from its start, or `%%PlateFile: (name) +//! EPS Local file`, the plate in a file of its own; a DCS 1.0 file names the four process plates' +//! files with `%%CyanPlate:`, `%%MagentaPlate:`, `%%YellowPlate:` and `%%BlackPlate:`. Spot inks +//! take their process equivalents from `%%CMYKCustomColor:` (else `%%RGBCustomColor:`). The comments +//! are described at http://www.telegraphics.net/doc/DCS.txt. +//! +//! [`read`] finds those comments; [`place`] reads every plate's image (its ink amounts: a dark +//! plate pixel is ink) into one [`Separated`] image, with the clipping path the main file's +//! composite is drawn through. + +use vectorcraft_color::cms::PROCESS_PLATES; +use vectorcraft_doc::separated::{InkPlate, MAX_NAME, MAX_PLATES, MAX_SAMPLES, Separated}; +use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_geom::{Affine, Rect}; + +/// Where a plate's program is. +#[derive(Clone, Debug, PartialEq)] +pub enum PlateAt { + /// In the DCS file itself: `len` bytes from byte `offset` of the file. + Here { offset: usize, len: usize }, + /// In a file of its own, as the DCS file names it (a path or a file name). + File(String), +} + +/// One plate a DCS file names. +#[derive(Clone, Debug, PartialEq)] +pub struct PlateRef { + /// "Cyan", "Magenta", "Yellow", "Black" or a spot ink's name. + pub name: String, + pub at: PlateAt, +} + +/// The DCS comments of a file. +#[derive(Clone, Debug, PartialEq)] +pub struct Dcs { + /// 1 or 2. + pub version: u8, + pub plates: Vec, + /// Spot inks' process equivalents (C, M, Y, K, 0..1), by name. + pub equivalents: Vec<(String, [f32; 4])>, +} + +impl Dcs { + /// The names of the plate files kept apart from the DCS file. + pub fn plate_files(&self) -> impl Iterator { + self.plates.iter().filter_map(|p| match &p.at { + PlateAt::File(f) => Some(f.as_str()), + PlateAt::Here { .. } => None, + }) + } +} + +/// The DCS comments of EPS file `bytes` (behind its binary header, if it has one); `None` when it +/// names no plate. +pub fn read(bytes: &[u8]) -> Option { + let (ps, _) = crate::sections(bytes)?; + if !ps.starts_with(b"%!") { + return None; + } + // The plates of the DCS 2.0 comments and of the DCS 1.0 ones. + let mut plates: Vec = vec![]; + let mut old: Vec = vec![]; + let mut equivalents: Vec<(String, [f32; 4])> = vec![]; + let mut rgb: Vec<(String, [f32; 4])> = vec![]; + // The comment a `%%+` line continues. + let mut last = String::new(); + for raw in ps.split(|b| matches!(b, b'\n' | b'\r')).filter(|l| !l.is_empty()).take(MAX_HEADER_LINES) { + let line = header_line(raw); + let line = line.trim_end(); + if line.starts_with("%%EndComments") || !line.starts_with('%') { + break; + } + let (key, value) = match line.strip_prefix("%%+") { + Some(v) => (last.clone(), v.trim()), + None => match line.split_once(':') { + Some((k, v)) => (k.to_string(), v.trim()), + None => (line.to_string(), ""), + }, + }; + match key.as_str() { + "%%PlateFile" => { + if let Some(p) = plate_file(value) + && !plates.iter().any(|q| q.name == p.name) + { + plates.push(p); + } + } + "%%CyanPlate" | "%%MagentaPlate" | "%%YellowPlate" | "%%BlackPlate" => { + let name = key.trim_start_matches("%%").trim_end_matches("Plate").to_string(); + if !value.is_empty() && !old.iter().any(|q| q.name == name) { + old.push(PlateRef { name, at: PlateAt::File(value.to_string()) }); + } + } + "%%CMYKCustomColor" => equivalents.extend(custom_colors(value, false)), + "%%RGBCustomColor" => rgb.extend(custom_colors(value, true)), + _ => {} + } + last = key; + } + // A file is one version or the other; the plate comments of DCS 2.0 win. + let version = if plates.is_empty() { + plates = old; + 1 + } else { + 2 + }; + if plates.is_empty() { + return None; + } + for (name, c) in rgb { + if !equivalents.iter().any(|(n, _)| *n == name) { + equivalents.push((name, c)); + } + } + Some(Dcs { version, plates, equivalents }) +} + +/// Most header lines looked at for the DCS comments. +const MAX_HEADER_LINES: usize = 10_000; + +/// Header line `raw` as text: UTF-8 when it is, else Latin-1 (each byte one character), as the +/// octal escapes of names are read. +fn header_line(raw: &[u8]) -> std::borrow::Cow<'_, str> { + match std::str::from_utf8(raw) { + Ok(s) => std::borrow::Cow::Borrowed(s), + Err(_) => std::borrow::Cow::Owned(raw.iter().copied().map(char::from).collect()), + } +} + +/// `s` without its first word and the whitespace around that word. +fn after_word(s: &str) -> &str { + s.trim_start().split_once(char::is_whitespace).map_or("", |(_, rest)| rest.trim_start()) +} + +/// A `%%PlateFile:` comment's plate: `(name) EPS #offset size` or `(name) EPS Local file`; `None` +/// for other locations, which only a print server reads. +fn plate_file(v: &str) -> Option { + let (name, rest) = ps_string(v)?; + let mut words = rest.split_whitespace(); + let _kind = words.next()?; + let location = words.next()?; + let name = canonical(name)?; + if let Some(offset) = location.strip_prefix('#') { + let len = words.next()?.parse().ok()?; + return Some(PlateRef { name, at: PlateAt::Here { offset: offset.parse().ok()?, len } }); + } + if !location.eq_ignore_ascii_case("Local") { + return None; + } + // The file name as it is written, its spaces kept. + let file = after_word(after_word(rest)); + (!file.is_empty()).then(|| PlateRef { name, at: PlateAt::File(file.to_string()) }) +} + +/// A plate's name as it is kept: a process ink's in its usual case ("cyan" is "Cyan"); `None` when +/// it is empty or longer than [`MAX_NAME`]. +fn canonical(name: String) -> Option { + if name.is_empty() || name.len() > MAX_NAME { + return None; + } + Some(PROCESS_PLATES.iter().find(|p| p.eq_ignore_ascii_case(&name)).map_or(name, |p| p.to_string())) +} + +/// The custom colours of a `%%CMYKCustomColor:` (four numbers then a name, repeated) or, with +/// `rgb`, a `%%RGBCustomColor:` comment (three numbers), the RGB ones as the process inks that +/// take their light away (`1 − r`, `1 − g`, `1 − b`, no black). Names may be bare words. +fn custom_colors(v: &str, rgb: bool) -> Vec<(String, [f32; 4])> { + let mut out = vec![]; + let mut rest = v.trim(); + let n = if rgb { 3 } else { 4 }; + while !rest.is_empty() && out.len() < MAX_PLATES { + let mut nums = [0.0f32; 4]; + for v in nums.iter_mut().take(n) { + let Some((word, after)) = rest.split_once(char::is_whitespace) else { return out }; + let Some(x) = word.parse::().ok().filter(|x| (0.0..=1.0).contains(x)) else { return out }; + *v = x; + rest = after.trim_start(); + } + let (name, after) = match ps_string(rest) { + Some((s, a)) => (s, a), + None => { + let (w, a) = rest.split_once(char::is_whitespace).unwrap_or((rest, "")); + (w.to_string(), a) + } + }; + rest = after.trim_start(); + let cmyk = if rgb { [1.0 - nums[0], 1.0 - nums[1], 1.0 - nums[2], 0.0] } else { nums }; + if let Some(name) = canonical(name) { + out.push((name, cmyk)); + } + } + out +} + +/// The PostScript string at the start of `v` (`(…)`, with nested parentheses and backslash +/// escapes) and what follows it. +fn ps_string(v: &str) -> Option<(String, &str)> { + let body = v.trim_start().strip_prefix('(')?; + let mut out = String::new(); + let mut depth = 0usize; + let mut chars = body.char_indices().peekable(); + while let Some((i, c)) = chars.next() { + match c { + '\\' => match chars.next()?.1 { + 'n' => out.push('\n'), + 'r' => out.push('\r'), + 't' => out.push('\t'), + d @ '0'..='7' => { + let mut code = d.to_digit(8)?; + for _ in 0..2 { + match chars.peek().and_then(|(_, e)| e.to_digit(8)) { + Some(e) => { + chars.next(); + code = code * 8 + e; + } + None => break, + } + } + // Octal escapes name bytes; names are read as Latin-1. + out.push(char::from_u32(code & 0xff)?); + } + e => out.push(e), + }, + '(' => { + depth += 1; + out.push(c); + } + ')' if depth == 0 => return Some((out, body.get(i + 1..)?)), + ')' => { + depth -= 1; + out.push(c); + } + _ => out.push(c), + } + } + None +} + +/// The main part of DCS file `bytes`: its PostScript (behind its binary header, if it has one), up +/// to the first plate it holds. +pub fn main_program<'a>(bytes: &'a [u8], dcs: &Dcs) -> Option<&'a [u8]> { + let (ps, _) = crate::sections(bytes)?; + let start = ps.as_ptr() as usize - bytes.as_ptr() as usize; + let first = dcs.plates.iter().filter_map(|p| match p.at { + PlateAt::Here { offset, .. } if offset > start => Some(offset - start), + _ => None, + }); + Some(&ps[..first.min().unwrap_or(ps.len()).min(ps.len())]) +} + +/// A DCS file read for placing. +#[derive(Debug)] +pub struct Placed { + pub separated: Separated, + /// The file's page (its bounding box) with its top-left corner at the origin. + pub page: Rect, + /// The image's pixels onto the page. + pub xf: Affine, + /// The clipping path the composite is drawn through, on the page. + pub clip: Option, + /// The resolution of the plates (pixels per inch), from how large they print. + pub ppi: Option<(f64, f64)>, + pub warnings: Vec, +} + +/// One plate's image: its ink amounts, one byte a pixel, and where its pixels print on its page. +struct PlateImage { + width: u32, + height: u32, + data: Vec, + xf: Affine, +} + +/// Read DCS file `bytes` (its comments `dcs`) for placing: every plate's image, the plates kept +/// apart read with `file` (the name the file gives → the plate file's bytes). The plates are put on +/// the pixel grid of the first plate's image, grown to hold every plate's image where it prints; +/// another plate is resampled onto it. An error when the file names more than [`MAX_PLATES`] +/// plates or a plate can't be read. +pub fn place(bytes: &[u8], dcs: &Dcs, file: &mut dyn FnMut(&str) -> Result, String>) -> Result { + if dcs.plates.len() > MAX_PLATES { + return Err(format!("it names {} plates, and at most {MAX_PLATES} are read", dcs.plates.len())); + } + let main = main_program(bytes, dcs).ok_or("the file's preview header points outside the file")?; + let page = crate::page(main)?; + let mut warnings = vec![]; + let (mut images, mut samples) = (vec![], 0u64); + for p in &dcs.plates { + let read = match &p.at { + PlateAt::Here { offset, len } => { + let eps = offset.checked_add(*len).and_then(|end| bytes.get(*offset..end)); + let eps = eps.ok_or_else(|| format!("the {} plate lies outside the file", p.name))?; + plate_image(eps) + } + PlateAt::File(f) => file(f).and_then(|eps| plate_image(&eps)), + }; + let img = read.map_err(|e| format!("the {} plate can't be read: {e}", p.name))?; + // Checked before the other plates are read. + samples += u64::from(img.width) * u64::from(img.height); + if samples > MAX_SAMPLES { + return Err(format!("its plates are too large: more than {MAX_SAMPLES} pixels together")); + } + images.push((p, img)); + } + let Some((w, h, xf)) = grid(images.iter().map(|(_, img)| img)) else { return Err("the file names no plate".into()) }; + if !Separated::fits(w, h, images.len()) { + return Err(format!("its plates are too large: {} plates of {w} × {h} pixels", images.len())); + } + let mut plates = vec![]; + for (p, img) in images { + let name = p.name.clone(); + let aligned = img.xf.as_coeffs().iter().zip(xf.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9); + let data = if (img.width, img.height) == (w, h) && aligned { img.data } else { resample(&img, w, h, xf) }; + let cmyk = match dcs.equivalents.iter().find(|(n, _)| *n == name) { + Some((_, c)) => *c, + None if PROCESS_PLATES.contains(&name.as_str()) => [0.0; 4], + None => { + warnings.push(format!("the file gives no process equivalent for the {name} ink: it shows as black")); + [0.0, 0.0, 0.0, 1.0] + } + }; + plates.push(InkPlate { name, cmyk, data }); + } + let separated = Separated::new(w, h, plates).ok_or("its plates can't be kept together")?; + let clip = clip_path(main); + // Points one pixel spans along each axis. + let [a, b, c, d, ..] = xf.as_coeffs(); + let ppi = [a.hypot(b), c.hypot(d)].map(|l| (l > 1e-12).then(|| 72.0 / l)); + let ppi = match ppi { + [Some(x), Some(y)] => Some((x, y)), + _ => None, + }; + Ok(Placed { separated, page, xf, clip, ppi, warnings }) +} + +/// The pixel grid the plates `images` go on: the first image's pixels, grown by whole pixels to +/// hold where every image prints, as its width, height and where its pixels print; `None` without +/// an image. It is the first image's own when its transform can't be inverted. +fn grid<'a>(mut images: impl Iterator) -> Option<(u32, u32, Affine)> { + let first = images.next()?; + let own = Some((first.width, first.height, first.xf)); + if first.xf.determinant().abs() <= 1e-12 { + return own; + } + let to_first = first.xf.inverse(); + let mut r = Rect::new(0.0, 0.0, f64::from(first.width), f64::from(first.height)); + for img in images { + r = r.union((to_first * img.xf).transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(img.width), f64::from(img.height)))); + } + // Edges within a millionth of a pixel of a whole one are on it. + let snap = |v: f64, up: bool| { + let n = v.round(); + if (v - n).abs() < 1e-6 { + n + } else if up { + v.ceil() + } else { + v.floor() + } + }; + let (x0, y0, x1, y1) = (snap(r.x0, false), snap(r.y0, false), snap(r.x1, true), snap(r.y1, true)); + let size = |a: f64, b: f64| Some(b - a).filter(|n| n.is_finite() && (1.0..=f64::from(u32::MAX)).contains(n)).map(|n| n as u32); + match (size(x0, x1), size(y0, y1)) { + (Some(w), Some(h)) => Some((w, h, first.xf * Affine::translate((x0, y0)))), + // Larger than any separated image may be ([`Separated::fits`]). + _ => Some((u32::MAX, u32::MAX, first.xf)), + } +} + +/// The ink amounts of `img` on the `w` × `h` pixels that `onto` puts on the page (each the +/// nearest pixel of `img` where it prints there, none outside it). When either transform can't be +/// inverted, the pixels are stretched over one another instead. +fn resample(img: &PlateImage, w: u32, h: u32, onto: Affine) -> Vec { + let (sw, sh) = (img.width as usize, img.height as usize); + let mut out = Vec::with_capacity(w as usize * h as usize); + let invertible = |m: Affine| m.determinant().abs() > 1e-12; + // From a pixel of the image made to a pixel of `img`. + let to_plate = (invertible(img.xf) && invertible(onto)).then(|| img.xf.inverse() * onto); + for y in 0..h as usize { + for x in 0..w as usize { + let at = match to_plate { + Some(m) => { + let p = m * vectorcraft_geom::Point::new(x as f64 + 0.5, y as f64 + 0.5); + let inside = p.x >= 0.0 && p.y >= 0.0 && p.x < sw as f64 && p.y < sh as f64; + inside.then(|| (p.y as usize).min(sh - 1) * sw + (p.x as usize).min(sw - 1)) + } + None => Some((y * sh / h as usize).min(sh - 1) * sw + (x * sw / w as usize).min(sw - 1)), + }; + out.push(at.and_then(|i| img.data.get(i).copied()).unwrap_or(0)); + } + } + out +} + +/// Is an image under `n` (itself included) drawn through a clipping path: inside a clipping group +/// or layer, or `inside` one already? +fn clips_an_image(n: &Node, inside: bool) -> bool { + let inside = inside || matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }); + match &n.kind { + NodeKind::Image(_) => inside, + _ => n.children().is_some_and(|ch| ch.iter().any(|c| clips_an_image(c, inside))), + } +} + +/// The image plate program `eps` draws, as ink amounts (how dark each pixel is: 255 less its +/// luma), and where it prints on its page; an error when it draws more than one image, or art +/// besides it. +fn plate_image(eps: &[u8]) -> Result { + let r = crate::import_with(eps, false)?; + if r.preview { + return Err(r.warnings.first().cloned().unwrap_or_else(|| "its PostScript can't be read".into())); + } + // A plate is one image: one that draws more (several images, or art) would lose ink. + let (mut found, mut images, mut art) = (None, 0usize, false); + r.document.walk(|n| match &n.kind { + NodeKind::Image(im) => { + images += 1; + found.get_or_insert((im.key.clone(), im.xf, im.width, im.height)); + } + NodeKind::Path { clipping: true, .. } | NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::RulerGuide { .. } => {} + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + art |= n.visible && n.appearance.items.iter().any(|i| i.visible() && !matches!(i.paint(), vectorcraft_color::Paint::None)) + } + _ => art |= n.visible, + }); + if images > 1 || (art && images == 1) { + return Err(if images > 1 { "it draws more than one image".into() } else { "it draws art besides its image".into() }); + } + // Ink outside a clipping path would print: a plate whose image is clipped is refused. + if images == 1 && r.document.layers.iter().any(|l| clips_an_image(l, false)) { + return Err("it draws its image through a clipping path".into()); + } + let (key, xf, iw, ih) = found.ok_or("it draws no image")?; + let blob = r.document.images.get(&key).ok_or("it draws no image")?; + let (width, height, data) = blob.coverage().ok_or("its image is too large to read")?; + // The object's pixel space may differ from the pixels it keeps. + let xf = xf * Affine::scale_non_uniform(f64::from(iw) / f64::from(width.max(1)), f64::from(ih) / f64::from(height.max(1))); + Ok(PlateImage { width, height, data, xf }) +} + +/// The clipping path the first image of `main` is drawn through, when it is drawn through one. +fn clip_path(main: &[u8]) -> Option { + let r = crate::import_with(main, false).ok().filter(|r| !r.preview)?; + first_clip(&r.document) +} + +/// The clipping path the first image of `d` is drawn through: the clipping path of the innermost +/// clipping group that holds an image, cut to the clipping paths of the clipping groups around it. +fn first_clip(d: &Document) -> Option { + /// The clipping paths around the innermost clipping group under `n` that holds an image, + /// outermost first. + fn find(n: &Node) -> Option> { + let NodeKind::Group { children, clip } = &n.kind else { + return n.children().and_then(|ch| ch.iter().find_map(|c| find(c))); + }; + let first = children.first().filter(|f| *clip && matches!(f.kind, NodeKind::Path { clipping: true, .. })); + if let Some(mut inner) = children.iter().find_map(|c| find(c)) { + if let Some(f) = first { + inner.insert(0, (**f).clone()); + } + return Some(inner); + } + let holds_image = || { + let mut any = false; + n.walk(&mut |c: &Node| any |= matches!(c.kind, NodeKind::Image(_))); + any + }; + first.filter(|_| holds_image()).map(|f| vec![(**f).clone()]) + } + let mut clips = d.layers.iter().find_map(|l| find(l))?; + let mut innermost = clips.pop()?; + // The clipping paths together clip to where they overlap. + for outer in clips.iter().rev() { + if let (NodeKind::Path { path: o, rule: or, .. }, NodeKind::Path { path, rule, .. }) = (&outer.kind, &mut innermost.kind) { + *path = vectorcraft_pathops::boolean(path, *rule, o, *or, vectorcraft_pathops::BoolOp::Intersect); + *rule = vectorcraft_geom::FillRule::NonZero; + } + } + // An even-odd clipping path is kept as the same area under the nonzero rule, the rule of the + // clip groups the Links commands make and match again. + if let NodeKind::Path { path, rule: rule @ vectorcraft_geom::FillRule::EvenOdd, .. } = &mut innermost.kind + && let Ok(nonzero) = vectorcraft_pathops::try_boolean_n(&[(&*path, vectorcraft_geom::FillRule::EvenOdd)], |inside| !inside.is_empty()) + { + (*path, *rule) = (nonzero, vectorcraft_geom::FillRule::NonZero); + } + Some(innermost) +} + +#[cfg(test)] +mod tests; diff --git a/crates/eps/src/dcs/tests.rs b/crates/eps/src/dcs/tests.rs new file mode 100644 index 0000000000..b55fea0b84 --- /dev/null +++ b/crates/eps/src/dcs/tests.rs @@ -0,0 +1,283 @@ +//! DCS files made from scratch as http://www.telegraphics.net/doc/DCS.txt describes them: a main +//! EPS file whose header names its plates, each plate an EPS program drawing one grayscale image. + +use std::collections::HashMap; + +use vectorcraft_doc::NodeKind; + +use super::*; + +/// A plate program: one `w` × `h` grayscale image (`gray`, row by row from the top) on a 20 × 10 +/// pt page. +pub(crate) fn plate_eps(w: u32, h: u32, gray: &[u8]) -> String { + let hex: String = gray.iter().map(|g| format!("{g:02x}")).collect(); + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n20 10 scale\n{w} {h} 8 [{w} 0 0 -{h} 0 {h}] <{hex}> image\nshowpage\n%%Trailer\n%%EOF\n" + ) +} + +/// The composite: the image `w` × `h` drawn through a clipping path, the left half of the page. +fn composite(w: u32, h: u32) -> String { + let hex = "80".repeat((w * h * 3) as usize); + format!( + "gsave newpath 0 0 moveto 10 0 lineto 10 10 lineto 0 10 lineto closepath clip newpath\n20 10 scale\n{w} {h} 8 [{w} 0 0 -{h} 0 {h}] <{hex}> false 3 colorimage\ngrestore\nshowpage\n%%EOF\n" + ) +} + +/// A single-file DCS 2.0 file of `plates` (name, plate program), with the header lines `extra`. +pub(crate) fn single_file(plates: &[(&str, String)], extra: &str) -> Vec { + // Offsets and sizes are written ten digits wide, so the header's length is known first. + let header = |offsets: &[usize]| { + let mut s = String::from("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n"); + s.push_str(extra); + for ((name, eps), at) in plates.iter().zip(offsets) { + s.push_str(&format!("%%PlateFile: ({name}) EPS #{at:010} {:010}\n", eps.len())); + } + s.push_str("%%EndComments\n"); + s.push_str(&composite(2, 2)); + s + }; + let main = header(&vec![0; plates.len()]).len(); + let mut offsets = vec![]; + let mut at = main; + for (_, eps) in plates { + offsets.push(at); + at += eps.len(); + } + let mut out = header(&offsets).into_bytes(); + assert_eq!(out.len(), main); + for (_, eps) in plates { + out.extend(eps.as_bytes()); + } + out +} + +#[test] +fn single_file_plates_and_equivalents_are_read() { + let plate = plate_eps(1, 1, &[0]); + let extra = "%%DocumentCustomColors: (PANTONE 185 C)\n%%+ (Gr\\374n \\(A\\))\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n%%+ .5 0 1 0 (Gr\\374n \\(A\\))\n%%RGBCustomColor: 1 1 0 (Lemon)\n"; + let bytes = single_file(&[("cyan", plate.clone()), ("PANTONE 185 C", plate.clone()), ("Grün (A)", plate.clone())], extra); + let dcs = read(&bytes).unwrap(); + assert_eq!(dcs.version, 2); + let names: Vec<&str> = dcs.plates.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["Cyan", "PANTONE 185 C", "Grün (A)"], "a process ink in its usual case; escapes read"); + let PlateAt::Here { offset, len } = dcs.plates[1].at else { panic!("in the file: {:?}", dcs.plates[1]) }; + assert_eq!(&bytes[offset..offset + len], plate.as_bytes()); + assert_eq!( + dcs.equivalents, + [ + ("PANTONE 185 C".to_string(), [0.0, 0.91, 0.76, 0.0]), + ("Grün (A)".to_string(), [0.5, 0.0, 1.0, 0.0]), + ("Lemon".to_string(), [0.0, 0.0, 1.0, 0.0]) + ] + ); + assert_eq!(dcs.plate_files().count(), 0); + let main = main_program(&bytes, &dcs).unwrap(); + assert!(main.ends_with(b"%%EOF\n"), "up to the first plate"); + let PlateAt::Here { offset: first, .. } = dcs.plates[0].at else { panic!("in the file") }; + assert_eq!(main.len(), first); +} + +#[test] +fn plate_files_of_both_versions_are_read() { + let two = "%!PS-Adobe-3.0 EPSF-3.0\n%%PlateFile: (Black) EPS Local pic.K\n%%PlateFile: (Black) TIFF NewServe c:\\scans\\a0K.scn\n%%PlateFile: (TRUMATCH 1-a5) EPS Local my pic.9\n%%EndComments\n"; + let dcs = read(two.as_bytes()).unwrap(); + assert_eq!(dcs.version, 2); + assert_eq!( + dcs.plates, + [ + PlateRef { name: "Black".into(), at: PlateAt::File("pic.K".into()) }, + PlateRef { name: "TRUMATCH 1-a5".into(), at: PlateAt::File("my pic.9".into()) }, + ] + ); + let one = "%!PS-Adobe-2.0 EPSF-1.2\n%%CyanPlate: pic.C\n%%MagentaPlate: pic.M\n%%YellowPlate: pic.Y\n%%BlackPlate: pic.K\n%%EndComments\n"; + let dcs = read(one.as_bytes()).unwrap(); + assert_eq!(dcs.version, 1); + assert_eq!(dcs.plate_files().collect::>(), ["pic.C", "pic.M", "pic.Y", "pic.K"]); + let both = "%!PS-Adobe-2.0 EPSF-1.2\n%%CyanPlate: old.C\n%%PlateFile: (Cyan) EPS Local new.C\n%%EndComments\n"; + assert_eq!(read(both.as_bytes()).unwrap().plate_files().collect::>(), ["new.C"], "the DCS 2.0 comments win"); + // Comments after the header are not the file's. + assert!(read(b"%!PS-Adobe-3.0 EPSF-3.0\n%%EndComments\n%%PlateFile: (Cyan) EPS Local a.C\n").is_none()); + assert!(read(plate_eps(1, 1, &[0]).as_bytes()).is_none(), "a plain EPS file"); + assert!(read(b"\x89PNG").is_none()); +} + +#[test] +fn a_plate_program_drawing_more_than_its_image_is_an_error() { + let plate = plate_eps(1, 1, &[0]); + // Two image tiles, and an image with a filled square beside it. + let tiles = plate.replacen("showpage", "1 1 8 [1 0 0 -1 0 1] <00> image\nshowpage", 1); + let art = plate.replacen("20 10 scale", "0 0 moveto 5 0 lineto 5 5 lineto closepath fill\n20 10 scale", 1); + for (eps, why) in [(tiles, "more than one image"), (art, "art besides its image")] { + let bytes = single_file(&[("Cyan", eps)], ""); + let err = place(&bytes, &read(&bytes).unwrap(), &mut |_| Err("no files".into())).unwrap_err(); + assert!(err.contains("the Cyan plate can't be read") && err.contains(why), "{err}"); + } + let bytes = single_file(&[("Cyan", plate)], ""); + assert!(place(&bytes, &read(&bytes).unwrap(), &mut |_| Err("no files".into())).is_ok(), "one image alone"); +} + +#[test] +fn a_plate_program_clipping_its_image_is_an_error() { + let clipped = plate_eps(1, 1, &[0]).replacen("20 10 scale", "newpath 0 0 moveto 5 0 lineto 5 5 lineto closepath clip newpath\n20 10 scale", 1); + let bytes = single_file(&[("Cyan", clipped)], ""); + let err = place(&bytes, &read(&bytes).unwrap(), &mut |_| Err("no files".into())).unwrap_err(); + assert!(err.contains("the Cyan plate can't be read") && err.contains("clipping path"), "{err}"); +} + +#[test] +fn only_an_image_inside_a_clipping_group_or_layer_is_clipped() { + use std::sync::Arc; + use vectorcraft_color::Paint; + use vectorcraft_doc::NodeId; + let clip_path = || { + let rect = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)); + let mut p = Node::path(NodeId(1), rect, vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 0.0)); + if let NodeKind::Path { clipping, .. } = &mut p.kind { + *clipping = true; + } + Arc::new(p) + }; + let image = || { + let im = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 1, + height: 1, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + Arc::new(Node::new(NodeId(2), NodeKind::Image(Box::new(im)))) + }; + let group = |children: Vec>, clip| Node::new(NodeId(3), NodeKind::Group { children, clip }); + let beside = group(vec![Arc::new(group(vec![clip_path()], true)), image()], false); + assert!(!clips_an_image(&beside, false), "a clipping group beside the image"); + assert!(clips_an_image(&group(vec![clip_path(), image()], true), false), "the image inside the clipping group"); + assert!(clips_an_image(&group(vec![image()], false), true), "inside a clipping layer"); +} + +#[test] +fn nested_clips_around_the_composite_clip_it_together() { + // The left two thirds of the page, then the right three quarters inside it: 5 to 13 pt. + let main = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n\ + gsave newpath 0 0 moveto 13 0 lineto 13 10 lineto 0 10 lineto closepath clip newpath\n\ + gsave newpath 5 0 moveto 20 0 lineto 20 10 lineto 5 10 lineto closepath clip newpath\n\ + 20 10 scale 2 2 8 [2 0 0 -2 0 2] <808080808080808080808080> false 3 colorimage grestore grestore showpage\n%%EOF\n"; + let clip = clip_path(main.as_bytes()).expect("a clipping path"); + let b = clip.geometric_bounds().expect("bounds"); + assert!((b.x0 - 5.0).abs() < 1e-6 && (b.x1 - 13.0).abs() < 1e-6, "where both clips overlap: {b:?}"); +} + +#[test] +fn plate_file_names_keep_their_spaces() { + let two = "%!PS-Adobe-3.0 EPSF-3.0\n%%PlateFile: (Cyan) EPS Local my pic .C\n%%EndComments\n"; + assert_eq!(read(two.as_bytes()).unwrap().plate_files().collect::>(), ["my pic .C"]); +} + +#[test] +fn header_bytes_that_are_not_utf8_are_latin1() { + // `Grün` with a raw Latin-1 ü (0xFC), in a plate name and in a custom color's name. + let mut two = b"%!PS-Adobe-3.0 EPSF-3.0\n%%CMYKCustomColor: .5 0 1 0 (Gr\xfcn)\n%%PlateFile: (Gr\xfcn) EPS Local a.9\n".to_vec(); + two.extend(b"%%PlateFile: (Grau \xc3\xa9) EPS Local b.9\n%%EndComments\n"); + let dcs = read(&two).unwrap(); + let names: Vec<&str> = dcs.plates.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["Grün", "Grau é"], "a line that is UTF-8 is read as UTF-8"); + assert_eq!(dcs.equivalents, [("Grün".to_string(), [0.5, 0.0, 1.0, 0.0])]); +} + +#[test] +fn every_plate_is_read_with_the_clipping_path() { + // 2 × 2 pixels: cyan solid on the top row, the spot ink at 50% on the first column. + let bytes = single_file( + &[("Cyan", plate_eps(2, 2, &[0, 0, 255, 255])), ("PANTONE 185 C", plate_eps(2, 2, &[127, 255, 127, 255]))], + "%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n", + ); + let dcs = read(&bytes).unwrap(); + let p = place(&bytes, &dcs, &mut |_| Err("no files".into())).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + assert_eq!(p.page, Rect::new(0.0, 0.0, 20.0, 10.0)); + let s = &p.separated; + assert_eq!((s.width, s.height), (2, 2)); + assert_eq!(s.plates[0].data, [255, 255, 0, 0], "a dark plate pixel is ink"); + assert_eq!(s.plates[1].data, [128, 0, 128, 0]); + assert_eq!(s.plates[1].cmyk, [0.0, 0.91, 0.76, 0.0]); + assert_eq!(p.xf * vectorcraft_geom::Point::new(2.0, 2.0), vectorcraft_geom::Point::new(20.0, 10.0)); + assert_eq!(p.ppi, Some((7.2, 14.4))); + let clip = p.clip.expect("the composite's clipping path"); + assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. })); + assert_eq!(clip.geometric_bounds().map(|b| b.width().round()), Some(10.0), "the left half of the page"); +} + +#[test] +fn plate_files_are_read_with_the_callback() { + let main = "%!PS-Adobe-2.0 EPSF-1.2\n%%BoundingBox: 0 0 20 10\n%%CyanPlate: pic.C\n%%BlackPlate: pic.K\n%%EndComments\nshowpage\n"; + let files: HashMap<&str, String> = [("pic.C", plate_eps(1, 1, &[0])), ("pic.K", plate_eps(2, 1, &[255, 0]))].into(); + let dcs = read(main.as_bytes()).unwrap(); + let mut asked = vec![]; + let p = place(main.as_bytes(), &dcs, &mut |f| { + asked.push(f.to_string()); + files.get(f).map(|e| e.as_bytes().to_vec()).ok_or_else(|| "missing".into()) + }) + .unwrap(); + assert_eq!(asked, ["pic.C", "pic.K"]); + assert!(p.clip.is_none(), "no composite, no clipping path"); + assert_eq!((p.separated.width, p.separated.height), (1, 1), "the first plate's size"); + assert_eq!(p.separated.plates[1].data, [255], "resampled to it: the pixel at its centre"); + let err = place(main.as_bytes(), &dcs, &mut |_| Err("not found".into())).unwrap_err(); + assert_eq!(err, "the Cyan plate can't be read: not found"); +} + +#[test] +fn plates_printing_elsewhere_on_the_page_stay_in_register() { + // The Black plate's one solid pixel prints on the right half of the page only. + let right = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n10 0 translate 10 10 scale\n1 1 8 [1 0 0 -1 0 1] <00> image\nshowpage\n%%EOF\n"; + let bytes = single_file(&[("Cyan", plate_eps(2, 1, &[255, 255])), ("Black", right.to_string())], ""); + let p = place(&bytes, &read(&bytes).unwrap(), &mut |_| Err("no files".into())).unwrap(); + assert_eq!((p.separated.width, p.separated.height), (2, 1)); + assert_eq!(p.separated.plates[1].data, [0, 255], "the ink lands on the right pixel only"); +} + +/// A plate program whose one solid pixel prints on a 10 × 10 pt square `x` pt from the page's left. +fn square_at(x: u32) -> String { + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n{x} 0 translate 10 10 scale\n1 1 8 [1 0 0 -1 0 1] <00> image\nshowpage\n%%EOF\n" + ) +} + +#[test] +fn the_plates_grid_grows_to_hold_every_plate() { + let bytes = single_file(&[("Cyan", square_at(0)), ("Black", square_at(10))], ""); + let p = place(&bytes, &read(&bytes).unwrap(), &mut |_| Err("no files".into())).unwrap(); + assert_eq!((p.separated.width, p.separated.height), (2, 1), "the first plate's pixels, grown over the second"); + assert_eq!(p.separated.plates[0].data, [255, 0]); + assert_eq!(p.separated.plates[1].data, [0, 255], "nothing of the second plate is cut off"); + assert_eq!(p.xf * vectorcraft_geom::Point::new(2.0, 1.0), vectorcraft_geom::Point::new(20.0, 10.0)); +} + +#[test] +fn a_file_naming_more_plates_than_are_read_is_an_error() { + let plate = plate_eps(1, 1, &[0]); + let names: Vec = (0..=MAX_PLATES).map(|i| format!("Ink {i}")).collect(); + let plates: Vec<(&str, String)> = names.iter().map(|n| (n.as_str(), plate.clone())).collect(); + let bytes = single_file(&plates, ""); + let dcs = read(&bytes).unwrap(); + assert_eq!(dcs.plates.len(), MAX_PLATES + 1, "every plate named"); + let err = place(&bytes, &dcs, &mut |_| Err("no files".into())).unwrap_err(); + assert_eq!(err, "it names 65 plates, and at most 64 are read"); +} + +#[test] +fn bad_plates_are_errors_and_missing_equivalents_warnings() { + let mut bytes = single_file(&[("Cyan", plate_eps(1, 1, &[0]))], ""); + let dcs = read(&bytes).unwrap(); + bytes.truncate(bytes.len() - 5); + assert_eq!(place(&bytes, &dcs, &mut |_| Err(String::new())).unwrap_err(), "the Cyan plate lies outside the file"); + let text = single_file(&[("Cyan", "%!PS-Adobe-3.0\n0 0 moveto 1 1 lineto stroke\n".to_string())], ""); + let err = place(&text, &read(&text).unwrap(), &mut |_| Err(String::new())).unwrap_err(); + assert_eq!(err, "the Cyan plate can't be read: it draws no image"); + let spot = single_file(&[("Mystery", plate_eps(1, 1, &[0]))], ""); + let p = place(&spot, &read(&spot).unwrap(), &mut |_| Err(String::new())).unwrap(); + assert_eq!(p.separated.plates[0].cmyk, [0.0, 0.0, 0.0, 1.0]); + assert_eq!(p.warnings, ["the file gives no process equivalent for the Mystery ink: it shows as black"]); +} diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index b750efbc20..2cc4bed521 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -89,10 +89,11 @@ pub(crate) use ai::{ BRUSH_MANAGER, BrushesRead, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept, read_art_style, read_brush_object, read_style_list, style_moves_with, symbol_art_member, warp_number, }; -pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES}; +pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; pub(crate) use native::{MAX_TEXT, scale_document}; pub use text::family_style; +pub(crate) use text::{document_font, postscript_face}; /// The page of a PostScript file without a bounding box (US Letter). const LETTER: [f64; 4] = [0.0, 0.0, 612.0, 792.0]; diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index 6cdbb96747..043d6f2e4d 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -508,10 +508,16 @@ impl Reader<'_> { None => (full.as_str(), None), }; st.cmap = cmap; - let (family, style) = super::super::super::text::family_style(name); + // The installed face of that PostScript name, as type from a text document + // takes it; else the name split into a family and style. + let text = super::super::super::text::named_font(name, None); + let (family, style, version) = text.unwrap_or_else(|| { + let (family, style) = super::super::super::text::family_style(name); + (family, style, None) + }); st.style.font_family = family; st.style.font_style = style; - st.style.font_version = None; + st.style.font_version = version; } if let Some(size) = vals.get(at + 1).and_then(V::num).filter(|s| s.is_finite() && *s > 0.0) { st.style.size = size.min(MAX_SIZE); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index c6a6041212..3c0ac39a05 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -3930,6 +3930,28 @@ fn point_type(attrs: &str, text: &str) -> String { format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n{attrs}\n({text}) Tx\nTO\n") } +/// Legacy type is set in the installed face of exactly the PostScript name its `Tf` gives, as type +/// from a text document is: not a face whose name differs only in case and loads first, nor the +/// copy the family and style resolve to when the name's own is another (it names its version). +#[test] +fn legacy_type_takes_the_face_of_its_exact_postscript_name() { + use vectorcraft_text::test_fonts::named_copy; + let db = vectorcraft_text::FontDb::global(); + for (inter, names) in [ + (true, ("TWINLEGACY INK", "Regular", "Version 1.000", "TWINLEGACYINK-Regular")), + (false, ("Twinlegacy Ink", "Regular", "Version 2.000", "TwinlegacyInk-Regular")), + ] { + assert_eq!(db.add_font(named_copy(inter, names).unwrap()), 1, "{names:?}"); + } + let face = |font: &str| { + let texts = legacy_texts(&point_type("", "Hi").replace("/_Helvetica 12 Tf", &format!("/_{font} 12 Tf"))); + let f = db.style_face(&texts[0].runs[0].style).unwrap(); + (f.postscript_name(), f.version.clone()) + }; + assert_eq!(face("TwinlegacyInk-Regular"), ("TwinlegacyInk-Regular".to_string(), "Version 2.000".to_string())); + assert_eq!(face("TWINLEGACYINK-Regular"), ("TWINLEGACYINK-Regular".to_string(), "Version 1.000".to_string())); +} + /// `TC` and `TW` (§15.4.7) set the paragraph's letter and word spacing, `Tq` its hanging /// punctuation and `Th` (§22) its hyphenation; each paragraph keeps the values in force at its /// first character, and they last into the next text object. diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index efaed14199..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 @@ -451,7 +459,8 @@ fn spend_tabs(tabs: &mut Vec, budget: &mut usize) -> bool { #[derive(Clone, Debug)] struct Style { - font: Option, + /// The font its record names, as the fonts the app has set it ([`DocFont::font`]). + font: Option, size: f64, /// `None`: auto. leading: Option, @@ -482,10 +491,44 @@ struct Style { standard_vertical_roman: bool, } +/// The longest font version string read from a font record: name ID 5 strings are short (`Version +/// 7.200`, or with the tools that built the font, some 80 characters). +const MAX_FONT_VERSION: usize = 256; + +/// The version a font record's key 5 gives `v`, as the reader takes it: `None` when it is empty or +/// longer than [`MAX_FONT_VERSION`] bytes. The `.ai` save checks a record it writes against this. +pub(crate) fn record_version(v: &str) -> Option<&str> { + (!v.is_empty() && v.len() <= MAX_FONT_VERSION).then_some(v) +} + +/// A font as type is set in it: family, style and the version it names +/// ([`super::text::document_font`]). +type Font = (String, String, Option); + +/// A font of a text document's font list, as its record (a `CoolTypeFont`) names it. +#[derive(Debug, Default)] +struct DocFont { + /// Key 0: the PostScript name. + name: String, + /// Key 5, when the record keeps it: the font's version string (name ID 5), which tells installed + /// copies of one font apart. + version: Option, + /// [`Self::font`]'s answer, found once for every run that names the record. + font: std::sync::OnceLock, +} + +impl DocFont { + /// The font type set in this record's font takes: the installed copy it names + /// ([`super::text::document_font`]). + fn font(&self) -> &Font { + self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref())) + } +} + /// The text document of an editing copy. pub(super) struct Texts { stories: Vec, - fonts: Vec, + fonts: Vec, /// The character and paragraph styles a story starts from. defaults: Val, para_defaults: Val, @@ -544,7 +587,15 @@ impl Texts { .get("0")? .list() .iter() - .map(|f| f.get("0").and_then(|f| f.get("0")).and_then(|f| f.get("0")).and_then(Val::str).unwrap_or_default().to_string()) + .map(|f| { + let record = f.get("0").and_then(|f| f.get("0")); + let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str); + DocFont { + name: text("0").unwrap_or_default().to_string(), + version: text("5").and_then(record_version).map(str::to_string), + font: std::sync::OnceLock::new(), + } + }) .collect(); let main = doc.get("1")?; let sheets = |key: &str| -> Vec { @@ -675,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 @@ -765,12 +817,12 @@ impl Texts { let pick = |k: &str| chain.iter().find_map(|s| s.get(k)).or_else(|| self.defaults.get(k)); let num = |k: &str| pick(k).and_then(Val::num); let on = |k: &str| !matches!(pick(k), Some(Val::Bool(false))); - let font = num("0").and_then(|i| self.fonts.get(i as usize)).filter(|f| !f.is_empty()).cloned(); + let font = num("0").and_then(|i| self.fonts.get(i as usize)).filter(|f| !f.name.is_empty()); let size = num("1").filter(|v| *v > 0.0 && *v < 1e5).unwrap_or(12.0); // Key 5 of a paint names the art style that paints it ([`Self::with_patterns`]). let pattern = |k: &str| pick(k).and_then(|p| p.get("5")).and_then(Val::str).and_then(|name| self.patterns.get(name)).cloned(); Style { - font, + font: font.map(|f| f.font().clone()), size, leading: if on("4") { None } else { num("5").filter(|v| *v > 0.0 && *v < 1e5) }, tracking: num("8").filter(|v| v.abs() < 1e5).unwrap_or(0.0), @@ -1139,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); @@ -1287,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 { @@ -1322,13 +1429,12 @@ fn para_style(p: &Para, scale: f64) -> ParaStyle { } } -/// The character style of character attributes `s`: its font from the fonts the app has, its -/// lengths (size, leading, baseline shift, stroke width) scaled by `scale`, and its patterns placed -/// in the type's text space by `to_text` (the document → its text space), where they stay as the -/// document has them. +/// The character style of character attributes `s`: its font from the fonts the app has (the +/// installed copy its font record names, [`DocFont::font`]), its lengths (size, leading, baseline +/// shift, stroke width) scaled by `scale`, and its patterns placed in the type's text space by +/// `to_text` (the document → its text space), where they stay as the document has them. fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle { - let (family, style) = s.font.as_deref().map_or_else(|| (CharStyle::default().font_family, "Regular".to_string()), crate::family_style); - let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); + let (family, style, version) = s.font.clone().unwrap_or_else(|| (CharStyle::default().font_family, "Regular".to_string(), None)); // A fill or stroke that is on takes its pattern in place of its colour. let paint = |color: Option, pattern: &Option| match (color, pattern) { // A pattern that can't be placed (the type's text space out of range) keeps the colour. @@ -1343,6 +1449,7 @@ fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle { CharStyle { font_family: family, font_style: style, + font_version: version, size: s.size * scale, // Auto leading stays auto: the layout gives each line the paragraph's share of the largest // type on it, as the file's own layout does ("The largest leading value in a line of type @@ -1768,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. @@ -2047,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_fontnames.rs b/crates/eps/src/import/tests_fontnames.rs index d925905ee7..a2a8d45641 100644 --- a/crates/eps/src/import/tests_fontnames.rs +++ b/crates/eps/src/import/tests_fontnames.rs @@ -63,3 +63,37 @@ fn abbreviated_styles_in_postscript_names_are_spelled_out() { fn an_installed_face_of_the_postscript_name_names_the_font() { assert_eq!(crate::family_style("ABCDEF+SourceSans3-Semibold"), ("Source Sans 3".to_string(), "Semibold".to_string())); } + +/// The PostScript name and version of the face each `show` of a program that sets `fonts` in turn +/// draws its type in. +fn faces_shown(fonts: &[&str]) -> Vec<(String, String)> { + let body: String = fonts.iter().map(|f| format!("/{f} findfont 12 scalefont setfont 10 20 moveto (Hi) show\n")).collect(); + let eps = format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n{body}showpage\n%%EOF\n"); + let r = import(eps.as_bytes()).unwrap(); + let mut faces = vec![]; + r.document.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + let face = FontDb::global().style_face(&t.runs[0].style).unwrap(); + faces.push((face.postscript_name(), face.version.clone())); + } + }); + faces +} + +/// Type a PostScript program sets is drawn in the installed face of exactly the font's PostScript +/// name, as type from a text document is: not another family spelled alike but for case and +/// punctuation, nor a face whose name differs only in case and loads first. +#[test] +fn shown_type_takes_the_face_of_its_exact_postscript_name() { + use vectorcraft_text::test_fonts::named_copy; + for (inter, names) in [ + (true, ("FUZZSHOW INK", "Regular", "Version 1.000", "FUZZSHOWINK-Regular")), + (false, ("Fuzzshow/Ink", "Regular", "Version 1.000", "FuzzshowInk")), + (true, ("CASESHOW INK", "Regular", "Version 1.000", "CASESHOWINK")), + (false, ("Caseshow Ink", "Regular", "Version 2.000", "CaseshowInk")), + ] { + assert_eq!(FontDb::global().add_font(named_copy(inter, names).unwrap()), 1, "{names:?}"); + } + let names: Vec = faces_shown(&["FuzzshowInk", "CaseshowInk", "CASESHOWINK"]).into_iter().map(|f| f.0).collect(); + assert_eq!(names, ["FuzzshowInk", "CaseshowInk", "CASESHOWINK"]); +} diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 8ddd9b8f14..c7cdf20e11 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3128,6 +3128,73 @@ fn type_from_the_text_document_takes_its_character_styles_attributes() { assert_eq!(style(2), (solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Some(18.0)), "the run's own colour"); } +/// The PostScript name and version of the face that type from a text document whose font record is +/// `record` (in place of `/0 (Helvetica)`) is set in. +fn face_set_from(record: &str) -> (String, String) { + let doc = text_document(&[("Hamburg\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]).replacen("/0 (Helvetica)", record, 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, "{record}: {:?}", r.warnings); + let face = vectorcraft_text::FontDb::global().style_face(&texts[0].runs[0].style).unwrap(); + (face.postscript_name(), face.version.clone()) +} + +/// Installs the copies of each font `copies` lists, the first of each loaded first. +fn install(copies: &[(bool, vectorcraft_text::test_fonts::CopyNames<'_>)]) { + for (inter, names) in copies { + let font = vectorcraft_text::test_fonts::named_copy(*inter, *names).unwrap(); + assert_eq!(vectorcraft_text::FontDb::global().add_font(font), 1, "{names:?}"); + } +} + +/// Type from the text document is set in the installed face of exactly the PostScript name its +/// font record gives, whatever other installed copies answer to that name too: one whose family +/// is spelled alike but for case and punctuation (`SAMPLE INK` beside `Sample/Ink`, PostScript name +/// `SampleInk`), one whose PostScript name differs only in case or punctuation (in its own family or +/// another), or another copy of the same family and style under another PostScript name (an older +/// build of the font: the type names its version). Those copies set the type at other widths. +#[test] +fn type_from_the_text_document_takes_the_face_of_its_exact_postscript_name() { + install(&[ + (true, ("FUZZTEST INK", "Regular", "Version 1.000", "FUZZTESTINK-Regular")), + (false, ("Fuzztest/Ink", "Regular", "Version 1.000", "FuzztestInk")), + (true, ("CASETEST INK", "Regular", "Version 1.000", "CASETESTINK")), + (false, ("Casetest Ink", "Regular", "Version 2.000", "CasetestInk")), + (true, ("Copytest Ink", "Regular", "Version 1.000", "CopytestInk-Light")), + (false, ("Copytest Ink", "Regular", "Version 2.000", "CopytestInk-Regular")), + (true, ("NeuetestInk", "Bold", "Version 1.000", "NeuetestInkBold")), + (false, ("Neuetest Ink", "Bold", "Version 1.000", "NeuetestInk-Bold")), + ]); + assert_eq!(face_set_from("/0 (FuzztestInk)").0, "FuzztestInk", "not the family spelled alike"); + assert_eq!(face_set_from("/0 (FUZZTESTINK-Regular)").0, "FUZZTESTINK-Regular"); + assert_eq!(face_set_from("/0 (CasetestInk)").0, "CasetestInk", "not the name in other case, loaded first"); + assert_eq!(face_set_from("/0 (CASETESTINK)").0, "CASETESTINK"); + assert_eq!(face_set_from("/0 (CopytestInk-Regular)"), ("CopytestInk-Regular".to_string(), "Version 2.000".to_string())); + assert_eq!(face_set_from("/0 (CopytestInk-Light)"), ("CopytestInk-Light".to_string(), "Version 1.000".to_string())); + assert_eq!(face_set_from("/0 (NeuetestInk-Bold)").0, "NeuetestInk-Bold", "not the name without its hyphen, in another family"); + // A name in a case no installed face has still finds the font. + assert_eq!(face_set_from("/0 (casetestink)").0, "CASETESTINK"); +} + +/// A font record may keep the font's version string (key 5, name ID 5): of two installed copies +/// with one PostScript name, family and style, the type is set in that version, also when the +/// record spells the name with other punctuation. A version that isn't installed, or a record +/// without one, gives the copy the family and style resolve to. +#[test] +fn type_from_the_text_document_takes_the_version_its_font_record_keeps() { + install(&[(true, ("Vertest Ink", "Regular", "1.0", "VertestInk-Regular")), (false, ("Vertest Ink", "Regular", "1.1", "VertestInk-Regular"))]); + let version = |record: &str| face_set_from(record).1; + assert_eq!(version("/0 (VertestInk-Regular) /5 (1.1)"), "1.1"); + assert_eq!(version("/0 (VertestInk-Regular) /5 (1.0)"), "1.0"); + assert_eq!(version("/0 (VertestInk-Regular)"), "1.0"); + assert_eq!(version("/0 (VertestInk-Regular) /5 (9.9)"), "1.0"); + assert_eq!(version("/0 (VertestInk-Regular) /5 ()"), "1.0"); + // A record whose name differs from the copies' in punctuation alone still picks its version. + assert_eq!(version("/0 (Vertest-Ink-Regular) /5 (1.1)"), "1.1"); + assert_eq!(version("/0 (Vertest-Ink-Regular)"), "1.0"); +} + /// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character /// Style]` and `[Normal Paragraph Style]` before the text document's base attributes. A Large /// Canvas copy (1:10) writes the styles at the art's scale (1.2 for 12 points, 0.6 for a 6-point @@ -3431,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/import/text.rs b/crates/eps/src/import/text.rs index 989450f440..515e0b12ec 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -42,20 +42,75 @@ fn style_word(w: &str) -> String { .to_string() } +/// A font's PostScript name without a subset prefix (`ABCDEF+`) or the `*1` of a re-encoded copy +/// (`ABCDEF+RollerBabyBV*1` is `RollerBabyBV`). +fn bare_name(name: &str) -> &str { + let name = match name.split_once('+') { + Some((prefix, rest)) if prefix.len() == 6 && prefix.bytes().all(|b| b.is_ascii_uppercase()) => rest, + _ => name, + }; + match name.rsplit_once('*') { + Some((base, n)) if !base.is_empty() && !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base, + _ => name, + } +} + +/// The font of type that a text document's font record names: by `name`, its PostScript name, and +/// `version`, the version string (name ID 5) the record keeps, if any. An installed face of that +/// name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) and the +/// family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is +/// Microsoft YaHei). → (family, style, version). +/// +/// [`FontDb::find_family`]: vectorcraft_text::FontDb::find_family +pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, String, Option) { + named_font(name, version).unwrap_or_else(|| { + let (family, style) = family_style(name); + let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); + (family, style, None) + }) +} + +/// The font of type set in the installed face of PostScript name `name` (a subset prefix and a +/// re-encoded copy's `*1` aside) in `version` ([`postscript_face`]): that face's own family and +/// style, and its version when the family and style alone resolve to another installed copy of +/// the font. A library can keep two copies under one family and style that differ in their +/// PostScript names or their versions, and draw the same text at different widths. → (family, +/// style, version); `None` when no installed face has the name. +pub(crate) fn named_font(name: &str, version: Option<&str>) -> Option<(String, String, Option)> { + let face = postscript_face(bare_name(name), version)?; + // As the PDF import names a version: only one that the family and style don't resolve to. + let default = vectorcraft_text::FontDb::global().face(&face.family, &face.style); + let version = default.filter(|d| d.version != face.version).map(|_| face.version.clone()); + Some((face.family.clone(), face.style.clone(), version)) +} + +/// The installed face of PostScript name `name` (without a subset prefix), among the installed +/// faces that answer to it ([`FontDb::postscript_faces`]): those of exactly that name when there +/// are any (PostScript names are case-sensitive, so `SampleSans` isn't the face named +/// `SAMPLESANS`, and `SampleSerif-Bold` isn't `SampleSerifBold`), and of those the one in +/// `version` when it is installed, else the first. `None` when no installed face has the name. +/// +/// [`FontDb::postscript_faces`]: vectorcraft_text::FontDb::postscript_faces +pub(crate) fn postscript_face(name: &str, version: Option<&str>) -> Option> { + let db = vectorcraft_text::FontDb::global(); + let found = db.find_postscript(name)?; + if found.postscript_name() == name && version.is_none_or(|v| v == found.version) { + return Some(found); + } + let faces = db.postscript_faces(name); + let named: Vec<_> = faces.iter().filter(|f| f.postscript_name() == name).cloned().collect(); + let pool = if named.is_empty() { faces } else { named }; + let in_version = version.and_then(|v| pool.iter().find(|f| f.version == v).cloned()); + Some(in_version.or_else(|| pool.into_iter().next()).unwrap_or(found)) +} + /// A font's family and style from its PostScript name, without a subset prefix (`ABCDEF+`) or the /// `*1` of a re-encoded copy (`ABCDEF+RollerBabyBV*1`): an installed or bundled face of that /// exact name gives its own (a family can hold hyphens: `rounded-x-mplus-1c-black` is Rounded-X /// M+ 1c, black); else the name is split, `Helvetica-BoldOblique` → (`Helvetica`, `Bold /// Oblique`), `TimesNewRomanPS-BoldMT` → (`Times New Roman`, `Bold`). pub fn family_style(name: &str) -> (String, String) { - let name = match name.split_once('+') { - Some((prefix, rest)) if prefix.len() == 6 && prefix.bytes().all(|b| b.is_ascii_uppercase()) => rest, - _ => name, - }; - let name = match name.rsplit_once('*') { - Some((base, n)) if !base.is_empty() && !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base, - _ => name, - }; + let name = bare_name(name); if let Some(face) = vectorcraft_text::FontDb::global().find_postscript(name) { return (face.family.clone(), face.style.clone()); } @@ -551,11 +606,11 @@ impl Interp<'_> { if !(size.is_finite() && size > 1e-3 && size < 1e5) { return ps_err("undefinedresult", "a font size"); } - let (family, font_style) = family_style(&name); - // The available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei". - let font_family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); + // The installed face of that PostScript name, as type from a text document takes it; else + // the available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei". + let (font_family, font_style, font_version) = document_font(&name, None); let fill = if self.g.paint.is_none() { Paint::solid(vectorcraft_color::Color::BLACK) } else { self.g.paint.clone() }; - let style = CharStyle { font_family, font_style, size, fill, stroke: Paint::None, ..CharStyle::default() }; + let style = CharStyle { font_family, font_style, font_version, size, fill, stroke: Paint::None, ..CharStyle::default() }; let mut t = TextObject::point(Point::ZERO, text, style); t.vertical = vertical; let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); 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/lib.rs b/crates/eps/src/lib.rs index f6b7fba609..44ec49c190 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -31,9 +31,11 @@ //! - `ai_editing`: the editing copy of the art a PDF-compatible `.ai` file carries //! ([`export_ai_editing`], [`ai_private_data`]). //! - `ai_ops`: the path and line style operators those two write. +//! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing. mod ai_editing; mod ai_ops; +pub mod dcs; mod import; mod latin; mod legacy_ai; 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..1175779777 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", @@ -945,6 +945,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. OK runs layer.setProps (one undo step); for several rows it sends only the fields set in the dialog", ), + ( + "ui.layerDelete", + "Delete Selection", + "", + "{ids?|id?, doc?, confirmed?: bool} Delete Selection as the Layers panel runs it (its trash button, rows dropped on the trash, its menu, Delete and Backspace), on the rows layer.delete takes (default: the highlighted rows, else the current layer). When a layer or sublayer among them holds art (an object other than a guide; hidden, locked and nested objects count) it asks first: dialog `confirm` with `message`; OK deletes those rows by id with layer.delete (one undo step), Cancel keeps them. OK runs ui.layerDelete again with the rows, `doc` (the document's uid) and `confirmed: true`: with another document active then, nothing is deleted. Other rows (an empty layer, groups and objects alone) and rows layer.delete refuses go to layer.delete at once → layer.delete's {deleted}, or null while the question is open", + ), ( "ui.rename", "Rename", @@ -1439,6 +1445,18 @@ 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.insertSelectPath", + "Insert Select Path", + "", + "{set?: index, action?: index, step?: index} insert a Select Path step for the path selected in the active document, without changing the selection: the step `select.storedPath {id, fingerprint}` stores the path's id and a fingerprint of its kind, fill rule and anchors, and playback selects only that path while it is still there unchanged and can be selected, else the step is an error. The selection must be one whole path or compound path that can be selected: not anchors or segments alone, several objects, a group, type or another kind of object, a guide, a member of a compound path, or a hidden or locked object. 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. No document, a selection that is not such a path, 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 Select Path runs this, for the selected step or action or the recording in progress → {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/Cargo.toml b/crates/metafile/Cargo.toml index fe54a67f6e..01b5d6434a 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -3,7 +3,7 @@ name = "vectorcraft-metafile" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft Windows metafiles: hand-written EMF and WMF writers and readers" +description = "VectorCraft metafiles: hand-written EMF and WMF writers and readers, and a QuickDraw picture (PICT) reader" [lints] workspace = true diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs index a0e95498c3..4aeb5b4381 100644 --- a/crates/metafile/src/dib.rs +++ b/crates/metafile/src/dib.rs @@ -11,8 +11,8 @@ const MAX_SIDE: u32 = 8192; /// Most pixels an image the writers store holds. const MAX_PIXELS: u64 = 1 << 24; /// Most pixels along a side, and in all, of a bitmap the reader decodes. -const MAX_READ_SIDE: u32 = 1 << 15; -const MAX_READ_PIXELS: u64 = 1 << 26; +pub(crate) const MAX_READ_SIDE: u32 = 1 << 15; +pub(crate) const MAX_READ_PIXELS: u64 = 1 << 26; /// Most pixels the bitmaps of one file may decode to together (four of the largest one), so a small /// file of many image records can't cost minutes of decoding (#3600). pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28; @@ -164,7 +164,7 @@ fn png_without_metadata(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> { } /// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded. -fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { +pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> { let n = u64::from(w) * u64::from(h); *left = left.checked_sub(n).ok_or(OVER_BUDGET)?; Ok(()) diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index 0a3d791ee2..da7816663e 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -1,6 +1,7 @@ -//! The metafile reader: the format parsers (`emf`, `wmf`) play their records on a [`Player`], a -//! small model of the device context they draw into (objects, transforms, the current position, -//! the path bracket, the clip), which turns what they draw into document objects. +//! The metafile reader: the format parsers (`emf`, `wmf`, and `pict` for QuickDraw pictures) play +//! their records on a [`Player`], a small model of the device context they draw into (objects, +//! transforms, the current position, the path bracket, the clip), which turns what they draw into +//! document objects. //! //! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the //! same pen join into one path. Clips become clipping groups around what they clip. Images keep @@ -8,6 +9,7 @@ //! doesn't know are counted and skipped, with one warning. mod emf; +pub(crate) mod pict; mod wmf; use std::sync::Arc; @@ -787,15 +789,25 @@ impl Player { if img.width == 0 || img.height == 0 { return; } + let (w, h) = (f64::from(img.width), f64::from(img.height)); + self.image_xf(img, Affine::translate((dest.x0, dest.y0)) * Affine::scale_non_uniform(dest.width() / w, dest.height() / h), opacity); + } + + /// An image placed by `xf` (its pixels, from the top-left, → logical), at `opacity`. An image + /// that `xf` flattens or sends past finite numbers is left out, and adds nothing to the + /// document's images. + pub(crate) fn image_xf(&mut self, img: Rgba, xf: Affine, opacity: f64) { + if img.width == 0 || img.height == 0 { + return; + } + let xf = self.xf() * xf; + if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + return; + } let Ok(png) = img.to_png() else { return self.warn(BAD_IMAGE) }; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); - let (w, h) = (f64::from(img.width), f64::from(img.height)); - let xf = self.xf() * Affine::translate((dest.x0, dest.y0)) * Affine::scale_non_uniform(dest.width() / w, dest.height() / h); - if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { - return; - } let im = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None }; let mut n = Node::new(vectorcraft_doc::NodeId(0), NodeKind::Image(Box::new(im))); n.opacity = opacity.clamp(0.0, 1.0) as f32; diff --git a/crates/metafile/src/import/pict.rs b/crates/metafile/src/import/pict.rs new file mode 100644 index 0000000000..a9b4cae9da --- /dev/null +++ b/crates/metafile/src/import/pict.rs @@ -0,0 +1,1173 @@ +//! QuickDraw pictures (PICT, versions 1 and 2), played on the [`Player`] by the opcodes and data +//! lengths of Apple's *Imaging With QuickDraw*, appendix A. +//! +//! A PICT file holds 512 bytes of application data before the picture; a picture on its own (as +//! a `PICT` resource holds it) reads too. A unit is a point, and the artboard is the picture's +//! frame; an extended version 2 header's source rectangle is mapped onto the frame. +//! +//! - Lines, rectangles, rounded rectangles, ovals, arcs and wedges, polygons and regions become +//! paths. A framed shape is stroked inside its outline at the pen's size, and a line below and +//! to the right of its points, where the pen draws; painted, filled and erased shapes are filled +//! with the pen, fill or background pattern. A pattern of two colors is filled with their +//! average. +//! - Text becomes point type in the font the picture names, read as Mac Roman. +//! - Bitmaps and pixel maps (1 to 8 bits with their color table, 16 and 32 bits, packed or not) +//! become images, clipped to their mask region; QuickTime JPEG images become images. +//! - The clip region clips what follows it. +//! +//! What isn't read (inverted shapes, transfer modes other than a copy, other QuickTime formats) +//! comes back as one warning each. Apple's table gives every opcode's length, so opcodes that draw +//! nothing VectorCraft reads are skipped; a picture cut short keeps what came before. + +use std::collections::HashMap; +use std::io::Cursor; + +use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect, Shape, Vec2, shapes}; + +use super::{BAD_IMAGE, BrushObj, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect}; +use crate::dib::{self, Rgba}; +use crate::{Imported, Kind}; + +/// What a file that holds no picture is refused with. +const NOT_PICT: &str = "not a PICT file"; +/// The application data before the picture in a PICT file. +const FILE_HEADER: usize = 512; +/// Most opcodes one picture plays (a small file can't keep the reader busy for minutes). +const MAX_OPS: usize = 1 << 22; +/// Most rectangles one region breaks into. +const MAX_RECTS: usize = 1 << 16; +/// Steps the regions of one picture may take to read (each inversion point and band costs some). +const MAX_REGION_WORK: u64 = 1 << 28; +/// Most bytes the unpacked rows of one image may hold. +const MAX_ROW_BYTES: u64 = 1 << 28; +/// Most bytes the unpacked rows of one picture's images and patterns may hold together. +const MAX_FILE_ROW_BYTES: u64 = 1 << 30; +/// Most bytes a row may hold past what its pixels need. +const ROW_SLACK: usize = 64; +/// Most pixels, and bytes of unpacked rows, a pixel pattern may hold. +const MAX_PATTERN_PIXELS: usize = 1 << 16; +const MAX_PATTERN_ROW_BYTES: usize = 1 << 20; +/// Curves made for ovals and arcs are this close to the true curve, points. +const TOLERANCE: f64 = 0.01; +/// GDI text alignment on the baseline, which QuickDraw's text location is. +const TA_BASELINE: u32 = 0x18; +/// Pen style flags: square and flat ends, mitered joins. +const SQUARE: u32 = 0x100; +const FLAT: u32 = 0x200; +const MITER: u32 = 0x2000; + +const CUT_SHORT: &str = "the picture is cut short or damaged: what came before was imported"; +const TOO_MANY_OPS: &str = "the picture holds more opcodes than one file may: the rest was left out"; +const INVERTED: &str = "inverted shapes were left out"; +const PATTERNS: &str = "patterns are filled with the average of their colors"; +const MODES: &str = "art drawn in transfer modes other than a copy is drawn as a copy"; +const FRAMED_REGIONS: &str = "framed regions are outlined rectangle by rectangle"; +const BIG_REGIONS: &str = "regions larger than one picture may hold were left out"; +const CODECS: &str = "QuickTime images in formats other than JPEG were left out"; +const NOTHING: &str = "the picture draws nothing VectorCraft reads"; + +/// Big-endian reads from a slice, never past its end. +struct Be<'a> { + data: &'a [u8], + pos: usize, +} + +impl<'a> Be<'a> { + fn new(data: &'a [u8], pos: usize) -> Self { + Self { data, pos } + } + fn bytes(&mut self, n: usize) -> Option<&'a [u8]> { + let b = self.data.get(self.pos..self.pos.checked_add(n)?)?; + self.pos += n; + Some(b) + } + fn array(&mut self) -> Option<[u8; N]> { + self.bytes(N)?.try_into().ok() + } + fn skip(&mut self, n: usize) -> Option<()> { + self.bytes(n).map(drop) + } + fn u8(&mut self) -> Option { + self.array().map(|[b]: [u8; 1]| b) + } + fn u16(&mut self) -> Option { + self.array().map(u16::from_be_bytes) + } + fn i16(&mut self) -> Option { + self.array().map(i16::from_be_bytes) + } + fn u32(&mut self) -> Option { + self.array().map(u32::from_be_bytes) + } + fn i32(&mut self) -> Option { + self.array().map(i32::from_be_bytes) + } + /// A QuickDraw point: vertical, then horizontal. + fn point(&mut self) -> Option { + let v = self.i16()?; + let h = self.i16()?; + Some(Point::new(h.into(), v.into())) + } + /// A size stored as a point (a pen or an oval: height, then width). + fn size(&mut self) -> Option { + self.point().map(Point::to_vec2) + } + /// A QuickDraw rectangle: top, left, bottom, right. + fn rect(&mut self) -> Option { + let (top, left, bottom, right) = (self.i16()?, self.i16()?, self.i16()?, self.i16()?); + Some(Rect::new(left.into(), top.into(), right.into(), bottom.into())) + } + /// An `RGBColor` (16 bits a component), 8 bits a component. + fn rgb(&mut self) -> Option<[u8; 3]> { + let [r, g, b] = [self.u16()?, self.u16()?, self.u16()?]; + Some([r, g, b].map(|c| (c >> 8) as u8)) + } +} + +/// Where a picture is, its frame and whether it is version 2. +struct Header { + frame: Rect, + v2: bool, + /// Where its first opcode starts. + ops: usize, +} + +/// The picture whose `picSize` is at `at`, if a version opcode follows its frame. +fn header(bytes: &[u8], at: usize) -> Option
{ + let mut r = Be::new(bytes, at.checked_add(2)?); + let frame = r.rect()?; + let (v2, ops) = match r.array::<2>()? { + [0x11, 0x01] => (false, r.pos), + [0x00, 0x11] if r.array::<4>()? == [0x02, 0xFF, 0x0C, 0x00] => (true, at + 10), + _ => return None, + }; + (frame.width() > 0.0 && frame.height() > 0.0).then_some(Header { frame, v2, ops }) +} + +/// The picture of a file (after its application data), else the picture `bytes` start with. +fn find(bytes: &[u8]) -> Option
{ + header(bytes, FILE_HEADER).or_else(|| header(bytes, 0)) +} + +/// Do `bytes` hold a version 2 picture, after a file's application data or on their own? The +/// version 1 signature is two bytes, too short to tell a file by. +pub(crate) fn is_pict(bytes: &[u8]) -> bool { + [FILE_HEADER, 0].into_iter().any(|at| header(bytes, at).is_some_and(|h| h.v2)) +} + +/// A pattern: eight rows of eight bits (set bits in the foreground color, the others in the +/// background color), or one color. +#[derive(Clone, Copy)] +enum Pat { + Bits([u8; 8]), + Rgb([u8; 3]), +} + +/// What a shape opcode does with its shape. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Verb { + Frame, + Paint, + Erase, + Invert, + Fill, +} + +/// The verb of a shape opcode (its low three bits; 5 to 7 are reserved). +fn verb(op: u16) -> Option { + match op & 7 { + 0 => Some(Verb::Frame), + 1 => Some(Verb::Paint), + 2 => Some(Verb::Erase), + 3 => Some(Verb::Invert), + 4 => Some(Verb::Fill), + _ => None, + } +} + +/// An old-style QuickDraw color (`blackColor` 33 … `blueColor` 409) as RGB. +fn old_color(c: u32) -> [u8; 3] { + match c { + 30 => [255; 3], + 69 => [255, 255, 0], + 137 => [255, 0, 255], + 205 => [255, 0, 0], + 273 => [0, 255, 255], + 341 => [0, 255, 0], + 409 => [0, 0, 255], + _ => [0; 3], + } +} + +/// `a` and `b` mixed: `t` of `a`. +fn mix(a: [u8; 3], b: [u8; 3], t: f64) -> [u8; 3] { + let m = |x: u8, y: u8| (f64::from(x) * t + f64::from(y) * (1.0 - t)).round() as u8; + [m(a[0], b[0]), m(a[1], b[1]), m(a[2], b[2])] +} + +/// Byte `b` of Mac Roman. +fn mac_roman(b: u8) -> char { + const HIGH: [char; 128] = [ + 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', // + 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', // + '†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', // + '∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', // + '¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', // + '–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', // + '‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', // + '\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ', + ]; + match b { + 0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER), + _ => char::from(b), + } +} + +/// The family name of a classic Macintosh font number. +fn font_family(id: u16) -> &'static str { + match id { + 0 => "Chicago", + 1 | 3 => "Geneva", + 2 => "New York", + 4 => "Monaco", + 20 => "Times", + 21 => "Helvetica", + 22 => "Courier", + 23 => "Symbol", + _ => "", + } +} + +/// The arc of the oval in `r` from `start` degrees clockwise from 12 o'clock, over `sweep` +/// degrees (clockwise when positive). Angles are measured on the rectangle, so 45° runs through +/// its top-right corner. A wedge closes through the center. +fn arc(r: Rect, start: i16, sweep: i16, wedge: bool) -> BezPath { + let c = r.center(); + let radii = Vec2::new(r.width() / 2.0, r.height() / 2.0); + let mut bp = BezPath::new(); + if sweep == 0 { + return bp; + } + let a0 = (f64::from(start) - 90.0).to_radians(); + let sweep = f64::from(sweep).clamp(-360.0, 360.0).to_radians(); + let arc = kurbo::Arc { center: c, radii, start_angle: a0, sweep_angle: sweep, x_rotation: 0.0 }; + if wedge { + bp.move_to(c); + bp.line_to(c + Vec2::new(radii.x * a0.cos(), radii.y * a0.sin())); + arc.append_iter(TOLERANCE).for_each(|el| bp.push(el)); + bp.close_path(); + } else { + kurbo::Shape::path_elements(&arc, TOLERANCE).for_each(|el| bp.push(el)); + } + bp +} + +/// The outlines of `rects`, as one path. +fn rects_path(rects: &[Rect]) -> BezPath { + let mut bp = BezPath::new(); + for r in rects { + bp.extend(shapes::rectangle(*r).to_bezpath()); + } + bp +} + +/// Take `n` steps from `work`; false when too few are left. +fn spend(work: &mut u64, n: usize) -> bool { + match work.checked_sub(n as u64) { + Some(left) => { + *work = left; + true + } + None => false, + } +} + +/// A region (its size, bounding box and inversion points), read at `r`, as rectangles: `None` +/// when the data runs past the end; the flag is false when the region is larger than `work` or +/// [`MAX_RECTS`] allows, and then no rectangles are given. +fn region(r: &mut Be, work: &mut u64) -> Option<(Vec, bool)> { + let size = usize::from(r.u16()?); + let mut b = Be::new(r.bytes(size.checked_sub(2)?)?, 0); + let bbox = b.rect()?; + if size <= 10 { + let whole = bbox.width() > 0.0 && bbox.height() > 0.0; + return Some((if whole { vec![bbox] } else { vec![] }, true)); + } + Some(bands(&mut b, work).map_or((vec![], false), |rects| (rects, true))) +} + +/// The rectangles of a region's scanlines: each lists the x coordinates where being inside the +/// region changes from the scanline before. Bands of the same spans one after another are one +/// rectangle. +fn bands(b: &mut Be, work: &mut u64) -> Option> { + let mut out: Vec = vec![]; + let mut active: Vec = vec![]; + let mut last_band = 0; + let mut prev_y = 0.0; + while let Some(y) = b.i16().filter(|y| *y != 0x7FFF) { + let y = f64::from(y); + let spans: Vec<(f64, f64)> = active.as_chunks::<2>().0.iter().map(|[a, b]| (f64::from(*a), f64::from(*b))).collect(); + if !spans.is_empty() && y > prev_y { + if !spend(work, spans.len() + 1) { + return None; + } + let prev = out.get_mut(last_band..).unwrap_or_default(); + let same = prev.len() == spans.len() && prev.iter().zip(&spans).all(|(r, (x0, x1))| r.x0 == *x0 && r.x1 == *x1 && r.y1 == prev_y); + if same { + prev.iter_mut().for_each(|r| r.y1 = y); + } else { + last_band = out.len(); + out.extend(spans.iter().map(|&(x0, x1)| Rect::new(x0, prev_y, x1, y))); + if out.len() > MAX_RECTS { + return None; + } + } + } + prev_y = y; + while let Some(x) = b.i16().filter(|x| *x != 0x7FFF) { + if !spend(work, active.len() + 1) { + return None; + } + match active.binary_search(&x) { + Ok(i) => { + active.remove(i); + } + Err(i) => active.insert(i, x), + } + } + } + Some(out) +} + +/// Skip the data of opcode `op`, by the length Apple's table gives it. +fn skip(op: u16, r: &mut Be) -> Option<()> { + let n = match op { + 0x00 | 0x17..=0x19 | 0x1C | 0x1E | 0xB0..=0xCF | 0x8000..=0x80FF => 0, + 0x04 => 1, + 0x03 | 0x05 | 0x08 | 0x0D | 0x11 | 0x15 | 0x16 | 0xA0 => 2, + 0x06 | 0x07 | 0x0B | 0x0C | 0x0E | 0x0F => 4, + 0x1A | 0x1B | 0x1D | 0x1F => 6, + 0x02 | 0x09 | 0x0A | 0x10 => 8, + // Reserved opcodes with a 16-bit length, and the font name. + 0x24..=0x27 | 0x2C..=0x2F | 0x92..=0x97 | 0x9C..=0x9F | 0xA2..=0xAF => usize::from(r.u16()?), + // Reserved for Apple: two bytes for each unit of the high byte (the 24-byte header 0x0C00). + 0x0100..=0x7FFF => usize::from(op >> 8) * 2, + // 0xD0–0xFE and 0x8100–0xFFFF (QuickTime images among them): a 32-bit length. + _ => usize::try_from(r.u32()?).ok()?, + }; + r.skip(n) +} + +/// How a bitmap's or pixel map's pixels are stored. +struct PixMap { + row_bytes: usize, + bounds: Rect, + /// Bits a pixel. + size: u16, + pack: u16, + cmps: u16, + /// Indexed pixels' colors; a bitmap has none (its set bits are the foreground color). + palette: Option>, + /// Rows of 8 bytes or more may be packed with PackBits, as the packing says. + packed: bool, +} + +impl PixMap { + /// From `rowBytes` on: a pixel map when `rowBytes` has its high bit set or `pixmap` says so, + /// else a bitmap; a pixel map's color table follows unless `direct`. + fn read(r: &mut Be, pixmap: bool, direct: bool) -> Option { + let raw = r.u16()?; + let mut pm = PixMap { row_bytes: usize::from(raw & 0x3FFF), bounds: r.rect()?, size: 1, pack: 0, cmps: 1, palette: None, packed: true }; + if pixmap || raw & 0x8000 != 0 { + r.skip(2)?; + pm.pack = r.u16()?; + r.skip(14)?; + pm.size = r.u16()?; + pm.cmps = r.u16()?; + r.skip(14)?; + if !direct { + pm.palette = Some(color_table(r)?); + } + } + Some(pm) + } + + /// The width and height of its pixels. + fn dims(&self) -> Option<(usize, usize)> { + let (w, h) = (self.bounds.width(), self.bounds.height()); + (w > 0.0 && h > 0.0).then_some((w as usize, h as usize)) + } + + /// The packing: 0 is 4 for 32-bit pixels and 3 for 16-bit ones. + fn packing(&self) -> u16 { + match (self.size, self.pack) { + (32, 0) => 4, + (16, 0) => 3, + (_, p) => p, + } + } + + /// Rows are stored as they are (no byte count, no PackBits). + fn raw_rows(&self) -> bool { + !self.packed || self.row_bytes < 8 || self.packing() == 1 || (self.size == 32 && self.packing() == 2) + } + + /// Bytes of an unpacked row: a component plane each for packing 4, three bytes a pixel for + /// packing 2, else `rowBytes`. + fn row_len(&self, w: usize) -> usize { + match self.packing() { + 4 if self.size == 32 && self.row_bytes >= 8 => w * usize::from(self.cmps), + 2 if self.size == 32 => w * 3, + _ => self.row_bytes, + } + } + + /// Whether its pixels can be read: a depth QuickDraw has, and rows long enough for them and at + /// most [`ROW_SLACK`] bytes longer. + fn decodable(&self, w: usize) -> bool { + let need = match self.size { + 1 | 2 | 4 | 8 => (w * usize::from(self.size)).div_ceil(8), + 16 => 2 * w, + 32 if self.packing() == 4 && self.row_bytes >= 8 => { + if !matches!(self.cmps, 3 | 4) { + return false; + } + w * usize::from(self.cmps) + } + 32 if self.packing() == 2 => 3 * w, + 32 => 4 * w, + _ => return false, + }; + (need..=need + ROW_SLACK).contains(&self.row_len(w)) + } + + /// Read `h` rows of pixel data, unpacked into one buffer when `keep`, else only stepped over. + /// `None` when the data runs past the end; the flag is false when a row didn't unpack to its + /// length. + fn rows(&self, r: &mut Be, w: usize, h: usize, keep: bool) -> Option<(Vec, bool)> { + let len = self.row_len(w); + let unit = if self.packing() == 3 { 2 } else { 1 }; + let mut out = vec![]; + let mut ok = true; + let mut keep = keep; + for _ in 0..h { + if self.raw_rows() { + let row = r.bytes(len)?; + if keep { + out.extend_from_slice(row); + } + continue; + } + let n = if self.row_bytes > 250 { usize::from(r.u16()?) } else { usize::from(r.u8()?) }; + let packed = r.bytes(n)?; + // After a row that doesn't unpack, the rest are only stepped over. + if keep && !unpack(packed, len, unit, &mut out) { + ok = false; + keep = false; + out = vec![]; + } + } + Some((out, ok)) + } + + /// The color of pixel `x` of `row` (the foreground and background colors for a bitmap's bits). + fn pixel(&self, row: &[u8], x: usize, w: usize, fg: [u8; 3], bg: [u8; 3]) -> Option<[u8; 3]> { + let at = |i: usize| row.get(i).copied(); + match self.size { + 1 | 2 | 4 | 8 => { + let bits = usize::from(self.size); + let shift = 8 - bits - x * bits % 8; + let index = usize::from((at(x * bits / 8)? >> shift) & ((1u16 << bits) - 1) as u8); + match &self.palette { + Some(p) => p.get(index).copied(), + None => Some(if index == 0 { bg } else { fg }), + } + } + 16 => { + let v = u16::from_be_bytes([at(2 * x)?, at(2 * x + 1)?]); + let c = |s: u16| (((v >> s) & 31) * 255 / 31) as u8; + Some([c(10), c(5), c(0)]) + } + _ if self.packing() == 4 && self.row_bytes >= 8 => { + // Component planes, alpha first when there are four (QuickDraw doesn't draw it). + let first = usize::from(self.cmps) - 3; + Some([at(first * w + x)?, at((first + 1) * w + x)?, at((first + 2) * w + x)?]) + } + _ if self.packing() == 2 => Some([at(3 * x)?, at(3 * x + 1)?, at(3 * x + 2)?]), + _ => Some([at(4 * x + 1)?, at(4 * x + 2)?, at(4 * x + 3)?]), + } + } + + /// Unpacked rows as opaque pixels. + fn to_rgba(&self, data: &[u8], w: usize, h: usize, fg: [u8; 3], bg: [u8; 3]) -> Option { + let len = self.row_len(w); + let mut pixels = Vec::with_capacity(w * h * 4); + for y in 0..h { + let row = data.get(y * len..(y + 1) * len)?; + for x in 0..w { + pixels.extend(self.pixel(row, x, w, fg, bg)?); + pixels.push(255); + } + } + Some(Rgba { width: u32::try_from(w).ok()?, height: u32::try_from(h).ok()?, pixels }) + } +} + +/// A `ColorTable`: indexed pixels' colors (entry by entry for a device table, else by each +/// entry's value). +fn color_table(r: &mut Be) -> Option> { + r.skip(4)?; + let flags = r.u16()?; + let n = usize::from(r.u16()?) + 1; + let mut palette = vec![[0u8; 3]; 256]; + for i in 0..n { + let value = usize::from(r.u16()?); + let c = r.rgb()?; + if let Some(e) = palette.get_mut(if flags & 0x8000 != 0 { i } else { value }) { + *e = c; + } + } + Some(palette) +} + +/// Unpack PackBits `data` (runs of `unit`-byte elements) onto `out`, `len` bytes; false when the +/// data is damaged or short (the row is padded with zeros). +fn unpack(data: &[u8], len: usize, unit: usize, out: &mut Vec) -> bool { + let start = out.len(); + let mut i = 0; + let mut ok = true; + while out.len() - start < len { + let Some(&n) = data.get(i) else { + ok = false; + break; + }; + i += 1; + let n = n as i8; + if n >= 0 { + let k = (n as usize + 1) * unit; + let Some(lit) = data.get(i..i + k) else { + ok = false; + break; + }; + out.extend_from_slice(lit); + i += k; + } else if n != -128 { + let Some(v) = data.get(i..i + unit) else { + ok = false; + break; + }; + for _ in 0..(1 - isize::from(n)) { + out.extend_from_slice(v); + } + i += unit; + } + } + out.resize(start + len, 0); + ok +} + +/// The picture being played: QuickDraw's drawing state, and the player that makes the objects. +struct Pict { + p: Player, + frame: Rect, + /// Picture space → document. + base: Affine, + origin: Vec2, + fg: [u8; 3], + bg: [u8; 3], + pen: Vec2, + pen_mode: u16, + pen_pat: Pat, + fill_pat: Pat, + back_pat: Pat, + oval: Vec2, + pen_loc: Point, + font: u16, + face: u8, + text_size: i16, + text_loc: Point, + /// Font numbers the picture names. + names: HashMap, + /// The last rectangle of the rectangle, rounded rectangle, oval and arc opcodes. + last: [Rect; 4], + region_work: u64, + /// Bytes of unpacked rows the picture's images and patterns may still take. + row_bytes_left: u64, +} + +impl Pict { + fn new(frame: Rect) -> Self { + let base = Affine::translate(-frame.origin().to_vec2()); + let artboard = Rect::new(0.0, 0.0, frame.width(), frame.height()); + // A picture's coordinates map straight onto the document, as a WMF's do. + let p = Player::new(Kind::Wmf, base, 25.4 / 72.0, artboard); + Self { + p, + frame, + base, + origin: Vec2::ZERO, + fg: [0; 3], + bg: [255; 3], + pen: Vec2::new(1.0, 1.0), + pen_mode: 8, + pen_pat: Pat::Bits([0xFF; 8]), + fill_pat: Pat::Bits([0xFF; 8]), + back_pat: Pat::Bits([0; 8]), + oval: Vec2::ZERO, + pen_loc: Point::ZERO, + font: 0, + face: 0, + text_size: 0, + text_loc: Point::ZERO, + names: HashMap::new(), + last: [Rect::ZERO; 4], + region_work: MAX_REGION_WORK, + row_bytes_left: MAX_FILE_ROW_BYTES, + } + } + + /// Charge the `w` × `h` pixels of `pm`, and the bytes of its unpacked rows, to the picture's + /// budgets: false, and nothing charged, when either is spent. + fn charge(&mut self, pm: &PixMap, w: usize, h: usize) -> bool { + let bytes = (pm.row_len(w) as u64).saturating_mul(h as u64); + let Some(rows_left) = self.row_bytes_left.checked_sub(bytes) else { return false }; + let (Ok(wide), Ok(high)) = (u32::try_from(w), u32::try_from(h)) else { return false }; + if dib::charge(wide, high, &mut self.p.pixels_left).is_err() { + return false; + } + self.row_bytes_left = rows_left; + true + } + + /// Play opcode `op`, its data at `r`; `None` when the data runs past the end. + fn op(&mut self, op: u16, r: &mut Be) -> Option<()> { + if !matches!(op, 0x20..=0x23) { + self.p.flush(); + } + match op { + 0x01 => self.clip(r), + 0x0C => self.move_origin(r), + 0x20..=0x23 => self.line(op, r), + 0x28..=0x2B => self.text(op, r), + 0x2C => self.font_name(r), + 0x30..=0x6F => self.shape(op, r), + 0x70..=0x77 => self.poly(verb(op), r), + 0x80..=0x87 => self.region_shape(verb(op), r), + // The same polygon and region: Apple's table gives them no data and no drawing. + 0x78..=0x7F | 0x88..=0x8F => Some(()), + 0x90 | 0x91 | 0x98..=0x9B => self.bits(op, r), + 0xA1 => { + r.skip(2)?; + let n = usize::from(r.u16()?); + r.skip(n) + } + 0x0C00 => self.header(r), + 0x8200 => self.quicktime(r), + _ => self.state(op, r), + } + } + + /// The opcodes that set the drawing state; the others are skipped. + fn state(&mut self, op: u16, r: &mut Be) -> Option<()> { + match op { + 0x02 => self.back_pat = Pat::Bits(r.array()?), + 0x03 => self.font = r.u16()?, + 0x04 => self.face = r.u8()?, + 0x07 => self.pen = r.size()?, + 0x08 => self.pen_mode = r.u16()?, + 0x09 => self.pen_pat = Pat::Bits(r.array()?), + 0x0A => self.fill_pat = Pat::Bits(r.array()?), + 0x0B => self.oval = r.size()?, + 0x0D => self.text_size = r.i16()?, + 0x0E => self.fg = old_color(r.u32()?), + 0x0F => self.bg = old_color(r.u32()?), + 0x12 => self.back_pat = self.pix_pat(r)?, + 0x13 => self.pen_pat = self.pix_pat(r)?, + 0x14 => self.fill_pat = self.pix_pat(r)?, + 0x1A => self.fg = r.rgb()?, + 0x1B => self.bg = r.rgb()?, + _ => return skip(op, r), + } + Some(()) + } + + /// The version 2 header: an extended one's source rectangle maps onto the frame. + fn header(&mut self, r: &mut Be) -> Option<()> { + let mut b = Be::new(r.bytes(24)?, 0); + if b.i16() == Some(-2) + && let Some(src) = b.skip(10).and_then(|()| b.rect()) + && src.width() > 0.0 + && src.height() > 0.0 + { + let k = Vec2::new(self.frame.width() / src.width(), self.frame.height() / src.height()); + self.base = Affine::scale_non_uniform(k.x, k.y) * Affine::translate(-src.origin().to_vec2()); + self.p.dev_to_doc = self.base * Affine::translate(-self.origin); + } + Some(()) + } + + /// The origin moves by (dh, dv): a point drawn after it is that much nearer the top left. + fn move_origin(&mut self, r: &mut Be) -> Option<()> { + let (dh, dv) = (r.i16()?, r.i16()?); + self.origin += Vec2::new(dh.into(), dv.into()); + self.p.dev_to_doc = self.base * Affine::translate(-self.origin); + Some(()) + } + + /// A pixel pattern: its color (the average of a color pattern's pixels), else its bitmap. + fn pix_pat(&mut self, r: &mut Be) -> Option { + let kind = r.u16()?; + let bits: [u8; 8] = r.array()?; + match kind { + 1 => { + let pm = PixMap::read(r, true, false)?; + let (w, h) = pm.dims()?; + let small = w * h <= MAX_PATTERN_PIXELS && pm.row_len(w) * h <= MAX_PATTERN_ROW_BYTES; + let keep = small && pm.decodable(w) && self.charge(&pm, w, h); + let (data, _) = pm.rows(r, w, h, keep)?; + let avg = keep.then(|| pm.to_rgba(&data, w, h, self.fg, self.bg)).flatten().map(|img| self.average(&img)); + Some(avg.map_or(Pat::Bits(bits), Pat::Rgb)) + } + 2 => Some(Pat::Rgb(r.rgb()?)), + _ => Some(Pat::Bits(bits)), + } + } + + /// The average color of `img`, with a warning when its pixels differ. + fn average(&mut self, img: &Rgba) -> [u8; 3] { + let px = img.pixels.as_chunks::<4>().0; + if px.windows(2).any(|w| w[0] != w[1]) { + self.p.warn(PATTERNS); + } + let n = px.len().max(1) as u64; + let sum = |i: usize| (px.iter().map(|p| u64::from(p[i])).sum::() / n) as u8; + [sum(0), sum(1), sum(2)] + } + + /// The color a pattern fills with: its own, or its two colors mixed as its bits are. + fn pat_color(&mut self, pat: Pat) -> [u8; 3] { + match pat { + Pat::Rgb(c) => c, + Pat::Bits(b) => { + let ones: u32 = b.iter().map(|x| x.count_ones()).sum(); + if ones != 0 && ones != 64 { + self.p.warn(PATTERNS); + } + mix(self.fg, self.bg, f64::from(ones) / 64.0) + } + } + } + + /// The pen's color (a warning when its mode isn't a copy). + fn pen_color(&mut self) -> [u8; 3] { + if !matches!(self.pen_mode, 0 | 8) { + self.p.warn(MODES); + } + self.pat_color(self.pen_pat) + } + + /// The color painting, erasing or filling an area takes; `None` for the other verbs. + fn area_color(&mut self, verb: Verb) -> Option<[u8; 3]> { + match verb { + Verb::Paint => Some(self.pen_color()), + Verb::Erase => Some(self.pat_color(self.back_pat)), + Verb::Fill => Some(self.pat_color(self.fill_pat)), + Verb::Frame | Verb::Invert => None, + } + } + + fn has_pen(&self) -> bool { + self.pen.x > 0.0 && self.pen.y > 0.0 + } + + /// Fill `bp` (picture space) with `color`. + fn fill(&mut self, mut bp: BezPath, color: [u8; 3], rule: FillRule) { + bp.apply_affine(self.p.xf()); + self.p.dc.brush = BrushObj::Solid(color); + self.p.dc.fill_rule = rule; + self.p.draw(bp, true, false); + } + + /// The pen as a stroke of `color` with `ends`, as wide as the pen's average side. + fn set_pen(&mut self, color: [u8; 3], ends: u32) { + let width = (self.pen.x + self.pen.y) / 2.0; + self.p.dc.pen = PenObj { style: PS_GEOMETRIC | ends | MITER, width, color, entries: vec![] }; + } + + /// Stroke `bp` (picture space) with the pen in `color`. + fn stroke(&mut self, mut bp: BezPath, color: [u8; 3], ends: u32) { + self.set_pen(color, ends); + bp.apply_affine(self.p.xf()); + self.p.draw(bp, false, true); + } + + /// Draw a framed shape: its outline (from `outline` of a rectangle and an oval size) stroked + /// inside `r`, or filled when the pen is as large as the shape. + fn frame(&mut self, r: Rect, outline: impl Fn(Rect, Vec2) -> BezPath, ends: u32) { + if !self.has_pen() { + return; + } + let color = self.pen_color(); + let half = self.pen / 2.0; + let inner = Rect::new(r.x0 + half.x, r.y0 + half.y, r.x1 - half.x, r.y1 - half.y); + if inner.width() <= 0.0 || inner.height() <= 0.0 { + return self.fill(outline(r, self.oval), color, FillRule::NonZero); + } + self.stroke(outline(inner, self.oval - self.pen), color, ends); + } + + /// The rectangle, rounded rectangle, oval and arc opcodes. + fn shape(&mut self, op: u16, r: &mut Be) -> Option<()> { + let family = op >> 4; + let slot = usize::from(family - 3); + let rect = if op & 8 != 0 { self.last.get(slot).copied()? } else { r.rect()? }; + let angles = if family == 6 { Some((r.i16()?, r.i16()?)) } else { None }; + let Some(verb) = verb(op) else { return Some(()) }; + if let Some(l) = self.last.get_mut(slot) { + *l = rect; + } + if rect.width() <= 0.0 || rect.height() <= 0.0 { + return Some(()); + } + let outline = move |r: Rect, oval: Vec2, wedge: bool| match family { + 3 => shapes::rectangle(r).to_bezpath(), + 4 => round_rect(r, oval.x, oval.y), + 5 => kurbo::Ellipse::from_rect(r).to_path(TOLERANCE), + _ => angles.map_or_else(BezPath::new, |(start, sweep)| arc(r, start, sweep, wedge)), + }; + match verb { + Verb::Frame => self.frame(rect, |r, oval| outline(r, oval, false), if family == 6 { FLAT } else { SQUARE }), + Verb::Invert => self.p.warn(INVERTED), + _ => { + if let Some(c) = self.area_color(verb) { + self.fill(outline(rect, self.oval, true), c, FillRule::NonZero); + } + } + } + Some(()) + } + + /// A polygon opcode: framed along its points, else filled. + fn poly(&mut self, verb: Option, r: &mut Be) -> Option<()> { + let size = usize::from(r.u16()?); + let mut b = Be::new(r.bytes(size.checked_sub(2)?)?, 8); + let Some(verb) = verb else { return Some(()) }; + let mut pts = vec![]; + while let Some(p) = b.point() { + pts.push(p); + } + let Some((first, rest)) = pts.split_first() else { return Some(()) }; + let closed = pts.len() > 2 && pts.first() == pts.last(); + match verb { + Verb::Frame if self.has_pen() => { + let half = self.pen / 2.0; + let mut bp = BezPath::new(); + bp.move_to(*first + half); + rest.iter().for_each(|p| bp.line_to(*p + half)); + if closed { + bp.close_path(); + } + let color = self.pen_color(); + self.stroke(bp, color, SQUARE); + } + Verb::Frame => {} + Verb::Invert => self.p.warn(INVERTED), + _ => { + let mut bp = BezPath::new(); + bp.move_to(*first); + rest.iter().for_each(|p| bp.line_to(*p)); + bp.close_path(); + if let Some(c) = self.area_color(verb) { + self.fill(bp, c, FillRule::EvenOdd); + } + } + } + Some(()) + } + + /// A region's rectangles, with a warning when it was too large to read. + fn read_region(&mut self, r: &mut Be) -> Option> { + let (rects, whole) = region(r, &mut self.region_work)?; + if !whole { + self.p.warn(BIG_REGIONS); + } + Some(rects) + } + + /// A region opcode: each rectangle framed, else the region filled. + fn region_shape(&mut self, verb: Option, r: &mut Be) -> Option<()> { + let rects = self.read_region(r)?; + let Some(verb) = verb.filter(|_| !rects.is_empty()) else { return Some(()) }; + match verb { + Verb::Frame if self.has_pen() => { + if rects.len() > 1 { + self.p.warn(FRAMED_REGIONS); + } + let half = self.pen / 2.0; + let inner: Vec = rects.iter().map(|r| Rect::new(r.x0 + half.x, r.y0 + half.y, r.x1 - half.x, r.y1 - half.y)).collect(); + let color = self.pen_color(); + self.stroke(rects_path(&inner), color, SQUARE); + } + Verb::Frame => {} + Verb::Invert => self.p.warn(INVERTED), + _ => { + if let Some(c) = self.area_color(verb) { + self.fill(rects_path(&rects), c, FillRule::NonZero); + } + } + } + Some(()) + } + + /// The clip region: it replaces the clip. An empty region clips away everything after it, as + /// a clip of no area at the frame's corner; one too large to read leaves the clip as it was. + fn clip(&mut self, r: &mut Be) -> Option<()> { + let (mut rects, whole) = region(r, &mut self.region_work)?; + if !whole { + self.p.warn(BIG_REGIONS); + return Some(()); + } + if rects.is_empty() { + let corner = Point::new(self.frame.x0, self.frame.y0); + rects.push(Rect::from_points(corner, corner)); + } + let mut bp = rects_path(&rects); + bp.apply_affine(self.p.xf()); + self.p.push_clip(bp, FillRule::NonZero, true); + Some(()) + } + + /// The line opcodes: the pen drawn from point to point, hanging below and to the right of + /// the line; lines one after another join into one path. + fn line(&mut self, op: u16, r: &mut Be) -> Option<()> { + let delta = |r: &mut Be| Some(Vec2::new(f64::from(r.u8()? as i8), f64::from(r.u8()? as i8))); + let (from, to) = match op { + 0x20 => (r.point()?, r.point()?), + 0x21 => (self.pen_loc, r.point()?), + 0x22 => { + let a = r.point()?; + (a, a + delta(r)?) + } + _ => (self.pen_loc, self.pen_loc + delta(r)?), + }; + self.pen_loc = to; + if !self.has_pen() { + return Some(()); + } + let color = self.pen_color(); + if from == to { + // A dot: the pen's rectangle. + self.p.flush(); + self.fill(shapes::rectangle(Rect::from_points(from, from + self.pen)).to_bezpath(), color, FillRule::NonZero); + return Some(()); + } + let pen = PenObj { style: PS_GEOMETRIC | SQUARE | MITER, width: (self.pen.x + self.pen.y) / 2.0, color, entries: vec![] }; + if self.p.dc.pen != pen { + self.p.flush(); + self.p.dc.pen = pen; + } + let half = self.pen / 2.0; + let xf = self.p.xf(); + let (a, b) = (xf * (from + half), xf * (to + half)); + if self.p.pending.elements().last().and_then(|e| e.end_point()) != Some(a) { + self.p.pending.move_to(a); + } + self.p.pending.line_to(b); + Some(()) + } + + /// The text opcodes: a string at the text location, moved to or by the opcode's data. + fn text(&mut self, op: u16, r: &mut Be) -> Option<()> { + match op { + 0x28 => self.text_loc = r.point()?, + 0x29 => self.text_loc.x += f64::from(r.u8()?), + 0x2A => self.text_loc.y += f64::from(r.u8()?), + _ => { + self.text_loc.x += f64::from(r.u8()?); + self.text_loc.y += f64::from(r.u8()?); + } + } + let n = usize::from(r.u8()?); + let s: String = r.bytes(n)?.iter().map(|&b| mac_roman(b)).filter(|c| !c.is_control()).collect(); + let size = if self.text_size > 0 { self.text_size } else { 12 }; + let face = self.names.get(&self.font).cloned().unwrap_or_else(|| font_family(self.font).to_string()); + self.p.dc.font = FontObj { + height: -f64::from(size), + escapement: 0.0, + weight: if self.face & 1 != 0 { 700 } else { 400 }, + italic: self.face & 2 != 0, + face, + }; + self.p.dc.text_color = self.fg; + self.p.dc.text_align = TA_BASELINE; + self.p.text(self.text_loc, &s); + Some(()) + } + + /// A font's name for its number. + fn font_name(&mut self, r: &mut Be) -> Option<()> { + let n = usize::from(r.u16()?); + let mut b = Be::new(r.bytes(n)?, 0); + if let Some(id) = b.u16() + && let Some(len) = b.u8() + && let Some(name) = b.bytes(usize::from(len)) + { + let name: String = name.iter().map(|&c| mac_roman(c)).collect(); + self.names.insert(id, name.trim().to_string()); + } + Some(()) + } + + /// A bitmap or pixel map copied into a rectangle (`Rgn` opcodes: clipped to a mask region). + fn bits(&mut self, op: u16, r: &mut Be) -> Option<()> { + let direct = matches!(op, 0x9A | 0x9B); + if direct { + r.skip(4)?; + } + let mut pm = PixMap::read(r, direct, direct)?; + // BitsRect and BitsRgn store their rows unpacked. + pm.packed = op >= 0x98; + let (src, dst, mode) = (r.rect()?, r.rect()?, r.u16()?); + let mask = if op & 1 != 0 { Some(self.read_region(r)?) } else { None }; + let (w, h) = pm.dims()?; + let (wide, high) = (w as u64, h as u64); + let fits = wide * high <= dib::MAX_READ_PIXELS && pm.row_len(w) as u64 * high <= MAX_ROW_BYTES; + let readable = pm.decodable(w); + let keep = fits && readable && self.charge(&pm, w, h); + let (data, ok) = pm.rows(r, w, h, keep)?; + if !keep { + self.p.warn(if readable { TOO_MANY_PIXELS } else { BAD_IMAGE }); + return Some(()); + } + let Some(mut img) = pm.to_rgba(&data, w, h, self.fg, self.bg).filter(|_| ok) else { + self.p.warn(BAD_IMAGE); + return Some(()); + }; + self.transfer(&mut img, mode, pm.size == 1 && pm.palette.is_none()); + if dst.width() <= 0.0 || dst.height() <= 0.0 || mask.as_ref().is_some_and(Vec::is_empty) { + return Some(()); + } + let saved = self.p.dc.clips.clone(); + if let Some(rects) = &mask { + let mut bp = rects_path(rects); + bp.apply_affine(self.p.xf()); + self.p.push_clip(bp, FillRule::NonZero, false); + } + self.p.image(Ok(img), src - pm.bounds.origin().to_vec2(), dst, SRCCOPY, 1.0); + self.p.dc.clips = saved; + Some(()) + } + + /// Transfer mode `mode` on copied pixels: OR of a bitmap and the transparent mode leave the + /// background color out; the others are copied, with a warning. + fn transfer(&mut self, img: &mut Rgba, mode: u16, bitmap: bool) { + // 64 dithers, which doesn't change what is copied. + let clear = match mode & !64 { + 0 => false, + 1 if bitmap => true, + 36 => true, + _ => { + self.p.warn(MODES); + false + } + }; + if clear { + let bg = self.bg; + img.pixels.as_chunks_mut::<4>().0.iter_mut().filter(|p| [p[0], p[1], p[2]] == bg).for_each(|p| p[3] = 0); + } + } + + /// A compressed QuickTime image: a JPEG one becomes an image placed by its matrix. + fn quicktime(&mut self, r: &mut Be) -> Option<()> { + let n = usize::try_from(r.u32()?).ok()?; + let data = r.bytes(n)?; + match qt_image(data) { + Some((ctype, xf, src, image)) if &ctype == b"jpeg" => match self.jpeg(image) { + Ok(img) => { + let img = crop(img, src); + self.p.image_xf(img, xf * Affine::translate(src.origin().to_vec2()), 1.0); + } + Err(w) => self.p.warn(w), + }, + Some(_) => self.p.warn(CODECS), + None => self.p.warn(BAD_IMAGE), + } + Some(()) + } + + /// A JPEG stream's pixels, taken from the file's pixel budget. + fn jpeg(&mut self, data: &[u8]) -> Result { + let reader = || image::ImageReader::with_format(Cursor::new(data), image::ImageFormat::Jpeg); + let (w, h) = reader().into_dimensions().map_err(|_| BAD_IMAGE)?; + if w > dib::MAX_READ_SIDE || h > dib::MAX_READ_SIDE || u64::from(w) * u64::from(h) > dib::MAX_READ_PIXELS { + return Err(TOO_MANY_PIXELS); + } + dib::charge(w, h, &mut self.p.pixels_left).map_err(|_| TOO_MANY_PIXELS)?; + let img = reader().decode().map_err(|_| BAD_IMAGE)?.to_rgba8(); + Ok(Rgba { width: img.width(), height: img.height(), pixels: img.into_raw() }) + } +} + +/// A QuickTime image's compressor type, matrix (image → picture space), source rectangle and +/// compressed data, from its header and image description. +fn qt_image(d: &[u8]) -> Option<([u8; 4], Affine, Rect, &[u8])> { + let mut b = Be::new(d, 2); + let mut m = [0.0; 9]; + for v in &mut m { + *v = f64::from(b.i32()?) / 65536.0; + } + let matte = usize::try_from(b.u32()?).ok()?; + b.skip(10)?; + let src = b.rect()?; + b.skip(4)?; + let mask = usize::try_from(b.u32()?).ok()?; + b.skip(matte)?; + b.skip(mask)?; + let start = b.pos; + let id_size = usize::try_from(b.u32()?).ok()?; + let ctype = b.array::<4>()?; + b.skip(36)?; + let size = usize::try_from(b.u32()?).ok()?; + let at = start.checked_add(id_size)?; + let data = d.get(at..at.checked_add(size)?).or_else(|| d.get(at..))?; + // The rows of a QuickTime matrix are [a b u] [c d v] [tx ty w]; u, v and w (perspective) are + // left out. + let xf = Affine::new([m[0], m[1], m[3], m[4], m[6], m[7]]); + Some((ctype, xf, src, data)) +} + +/// Read a picture. +pub(crate) fn play(bytes: &[u8]) -> Result { + let h = find(bytes).ok_or(NOT_PICT)?; + let mut q = Pict::new(h.frame); + let mut r = Be::new(bytes, h.ops); + // Why the picture stopped before its end opcode, if it did. + let mut stopped = Some(TOO_MANY_OPS); + for _ in 0..MAX_OPS { + // Version 2 opcodes start on even bytes. + if h.v2 && r.pos % 2 == 1 && r.skip(1).is_none() { + stopped = Some(CUT_SHORT); + break; + } + let Some(op) = (if h.v2 { r.u16() } else { r.u8().map(u16::from) }) else { + stopped = Some(CUT_SHORT); + break; + }; + if op == 0x00FF { + stopped = None; + break; + } + if q.op(op, &mut r).is_none() { + stopped = Some(CUT_SHORT); + break; + } + } + if let Some(why) = stopped { + q.p.warn(why); + } + q.p.flush(); + if q.p.out.is_empty() { + q.p.warn(NOTHING); + } + Ok(q.p.finish()) +} diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index a517d516a6..0e699236d7 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -15,13 +15,14 @@ //! //! [`import`] reads either format back into a document of one artboard (the picture's frame) and //! one layer: paths with fills and strokes, clipping, images and text. Records it doesn't read are -//! skipped, with one warning. +//! skipped, with one warning. [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) +//! into the same kind of document. //! //! - `bytes`: little-endian writing and bounds-checked reading. //! - `dib`: device-independent bitmaps, both ways. //! - `scene`: the document walk both writers share. //! - `emf`, `wmf`: the writers. -//! - `import`: the reader. +//! - `import`: the readers. mod bytes; mod dib; @@ -107,5 +108,28 @@ pub fn import(bytes: &[u8]) -> Result { Ok(i) } +/// A QuickDraw picture read into a document. +#[derive(Clone, Debug)] +pub struct Picture { + pub document: Document, + /// What was approximated or skipped. + pub warnings: Vec, +} + +/// Do `bytes` hold a version 2 QuickDraw picture, after a PICT file's 512 bytes of application +/// data or on their own? A version 1 picture is known by its file's name. +pub fn is_pict(bytes: &[u8]) -> bool { + import::pict::is_pict(bytes) +} + +/// Read a QuickDraw picture (version 1 or 2; a PICT file, or a picture on its own) into a document +/// whose one artboard is the picture's frame. +pub fn import_pict(bytes: &[u8]) -> Result { + let i = import::pict::play(bytes)?; + let mut p = Picture { document: i.document, warnings: i.warnings }; + p.document.limit_depth_noting(&mut p.warnings); + Ok(p) +} + #[cfg(test)] mod tests; 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/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 23bcfdc672..602db3d55f 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -12,6 +12,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes}; use crate::*; mod import; +mod pict; /// Add `n` (with a fresh id) on top of `d`'s first layer. pub(crate) fn add(d: &mut Document, mut n: Node) { diff --git a/crates/metafile/src/tests/pict.rs b/crates/metafile/src/tests/pict.rs new file mode 100644 index 0000000000..055e88c95b --- /dev/null +++ b/crates/metafile/src/tests/pict.rs @@ -0,0 +1,466 @@ +//! QuickDraw pictures read from hand-built opcodes: versions 1 and 2, with and without the file's +//! application data; shapes, lines, regions, patterns, text, bitmaps, pixel maps and QuickTime +//! JPEG images; and pictures that are cut short, damaged or never end. + +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind}; +use vectorcraft_geom::{Point, Rect}; + +use crate::import_pict; + +/// Big-endian words. +fn be(v: &[i16]) -> Vec { + v.iter().flat_map(|x| x.to_be_bytes()).collect() +} + +/// A QuickDraw rectangle: top, left, bottom, right. +fn rect(top: i16, left: i16, bottom: i16, right: i16) -> Vec { + be(&[top, left, bottom, right]) +} + +/// A version 2 PICT file: 512 bytes of application data, then a picture of `frame` (top, left, +/// bottom, right) holding `ops`, each padded to an even length, and the end opcode. +fn v2(frame: [i16; 4], ops: &[(u16, Vec)]) -> Vec { + let mut b = vec![0xA5; 512]; + b.extend([0, 0]); + b.extend(be(&frame)); + b.extend([0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]); + b.extend(be(&[-1, 0])); + b.extend([0; 20]); + for (op, data) in ops { + b.extend(op.to_be_bytes()); + b.extend(data); + if b.len() % 2 == 1 { + b.push(0); + } + } + b.extend([0x00, 0xFF]); + b +} + +/// An RGB foreground color. +fn fg(r: u16, g: u16, b: u16) -> (u16, Vec) { + (0x1A, [r, g, b].iter().flat_map(|c| c.to_be_bytes()).collect()) +} + +/// Every object of the imported document, depth first. +fn all(d: &Document) -> Vec { + let mut v = vec![]; + for l in &d.layers { + for c in l.children().into_iter().flatten() { + c.walk(&mut |n| v.push(n.clone())); + } + } + v +} + +fn paths(d: &Document) -> Vec { + all(d).into_iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })).collect() +} + +fn near(a: Rect, b: Rect, tol: f64) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() <= tol) +} + +fn fill_rgb(n: &Node) -> Option<[u8; 3]> { + n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => f.paint.color().map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b] + }), + _ => None, + }) +} + +fn stroke(n: &Node) -> Option<([u8; 3], f64)> { + n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Stroke(s) => s.paint.color().map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + ([r, g, b], s.width) + }), + _ => None, + }) +} + +/// The images of `d` with their pixels. +fn images(d: &Document) -> Vec<(Node, image::RgbaImage)> { + all(d) + .into_iter() + .filter_map(|n| match &n.kind { + NodeKind::Image(im) => { + let png = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8(); + Some((n.clone(), png)) + } + _ => None, + }) + .collect() +} + +#[test] +fn a_version_2_picture_opens_as_shapes_in_its_frame() { + let bytes = v2( + [10, 20, 110, 220], + &[ + fg(0xFFFF, 0, 0), + // paintRect + (0x31, rect(20, 30, 60, 80)), + (0x07, be(&[4, 4])), + fg(0, 0, 0xFFFF), + // frameRect: stroked inside the rectangle. + (0x30, rect(20, 120, 80, 200)), + // A line, and one from its end: one path. + (0x20, be(&[90, 40, 90, 140])), + (0x21, be(&[100, 140])), + ], + ); + assert!(crate::is_pict(&bytes)); + let p = import_pict(&bytes).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let a = p.document.artboards[0].rect; + assert!(near(a, Rect::new(0.0, 0.0, 200.0, 100.0), 1e-9), "{a:?}"); + let v = paths(&p.document); + assert_eq!(v.len(), 3, "{v:?}"); + assert_eq!(fill_rgb(&v[0]), Some([255, 0, 0])); + assert!(near(v[0].geometric_bounds().unwrap(), Rect::new(10.0, 10.0, 60.0, 50.0), 1e-6)); + assert!(v[0].appearance.stroke().is_none()); + // The pen's outer edge is the rectangle. + assert_eq!(stroke(&v[1]), Some(([0, 0, 255], 4.0))); + assert!(near(v[1].geometric_bounds().unwrap(), Rect::new(102.0, 12.0, 178.0, 68.0), 1e-6)); + assert!(fill_rgb(&v[1]).is_none()); + // The pen hangs below and to the right of the line. + assert_eq!(stroke(&v[2]), Some(([0, 0, 255], 4.0))); + assert!(near(v[2].geometric_bounds().unwrap(), Rect::new(22.0, 82.0, 122.0, 92.0), 1e-6)); +} + +#[test] +fn a_bare_picture_and_a_version_1_picture_open() { + // A version 2 picture without the file's application data. + let file = v2([0, 0, 50, 50], &[(0x31, rect(10, 10, 20, 20))]); + let bare = &file[512..]; + assert!(crate::is_pict(bare)); + assert_eq!(paths(&import_pict(bare).unwrap().document).len(), 1); + // Version 1: byte opcodes, known by name only. + let mut v1 = vec![0, 0]; + v1.extend(rect(0, 0, 40, 60)); + v1.extend([0x11, 0x01, 0x31]); + v1.extend(rect(5, 5, 15, 25)); + v1.extend([0xA0, 0x00, 0x05, 0x50]); + v1.extend(rect(20, 20, 30, 30)); + v1.push(0xFF); + assert!(!crate::is_pict(&v1)); + let p = import_pict(&v1).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + assert_eq!(p.document.artboards[0].rect.size(), (60.0, 40.0).into()); + let v = paths(&p.document); + assert_eq!(v.len(), 2); + assert!(near(v[0].geometric_bounds().unwrap(), Rect::new(5.0, 5.0, 25.0, 15.0), 1e-6)); + // The default pen: one point, black. + assert_eq!(stroke(&v[1]), Some(([0, 0, 0], 1.0))); + // Inside a file's application data too. + let mut file = vec![0; 512]; + file.extend(&v1); + assert_eq!(paths(&import_pict(&file).unwrap().document).len(), 2); +} + +#[test] +fn files_that_are_not_pictures_are_refused() { + assert_eq!(import_pict(&[0; 600]).unwrap_err(), "not a PICT file"); + assert_eq!(import_pict(b"").unwrap_err(), "not a PICT file"); + // An empty frame. + let mut b = vec![0, 0]; + b.extend(rect(10, 10, 10, 50)); + b.extend([0x11, 0x01, 0xFF]); + assert!(import_pict(&b).is_err()); +} + +#[test] +fn rounded_rectangles_ovals_arcs_and_same_shapes() { + let bytes = v2( + [0, 0, 100, 100], + &[ + (0x0B, be(&[20, 20])), + (0x41, rect(0, 0, 50, 50)), + (0x51, rect(50, 0, 100, 50)), + // A wedge from 12 to 3 o'clock. + (0x61, [rect(0, 50, 100, 150), be(&[0, 90])].concat()), + fg(0, 0xFFFF, 0), + // paintSameRect after paintRect: the same rectangle. + (0x31, rect(60, 60, 70, 80)), + (0x39, vec![]), + ], + ); + let p = import_pict(&bytes).unwrap(); + let v = paths(&p.document); + assert_eq!(v.len(), 5, "{v:?}"); + assert!(near(v[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 50.0, 50.0), 1e-6)); + assert!(near(v[1].geometric_bounds().unwrap(), Rect::new(0.0, 50.0, 50.0, 100.0), 1e-3)); + assert!(near(v[2].geometric_bounds().unwrap(), Rect::new(100.0, 0.0, 150.0, 50.0), 1e-3), "{:?}", v[2].geometric_bounds()); + assert_eq!(v[3].geometric_bounds(), v[4].geometric_bounds()); + assert_eq!(fill_rgb(&v[4]), Some([0, 255, 0])); +} + +#[test] +fn polygons_and_regions_fill_and_clip() { + // An L: the top band 20 wide, the bottom band 10. + let region = [be(&[36]), rect(0, 0, 20, 20), be(&[0, 0, 20, 0x7FFF, 10, 10, 20, 0x7FFF, 20, 0, 10, 0x7FFF, 0x7FFF])].concat(); + let poly = [be(&[22]), rect(0, 0, 40, 40), be(&[0, 0, 40, 40, 0, 40])].concat(); + let bytes = v2([0, 0, 100, 100], &[(0x81, region.clone()), (0x71, poly), (0x01, region), (0x31, rect(0, 0, 100, 100))]); + let p = import_pict(&bytes).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let v = paths(&p.document); + assert_eq!(v.len(), 3); + let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") }; + assert_eq!(path.subpaths.len(), 2, "two bands"); + assert!(near(v[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 20.0, 20.0), 1e-9)); + assert!(near(v[1].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 40.0, 40.0), 1e-9)); + // The rectangle after the clip region is clipped to it. + let layer = p.document.layers[0].children().unwrap(); + let NodeKind::Group { children, clip: true } = &layer[2].kind else { panic!("a clipping group: {:?}", layer[2].kind) }; + assert!(near(children[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 20.0, 20.0), 1e-9)); +} + +#[test] +fn patterns_fill_with_their_average_color() { + let gray = vec![0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55]; + let bytes = v2( + [0, 0, 10, 10], + &[(0x0A, gray), (0x34, rect(0, 0, 10, 10)), (0x12, [be(&[2]), vec![0; 8], be(&[0, -1, 0])].concat()), (0x32, rect(0, 0, 5, 5))], + ); + let p = import_pict(&bytes).unwrap(); + let v = paths(&p.document); + assert_eq!(fill_rgb(&v[0]), Some([128, 128, 128])); + // eraseRect with an RGB background pattern. + assert_eq!(fill_rgb(&v[1]), Some([0, 255, 0])); + assert!(p.warnings.iter().any(|w| w.contains("average of their colors")), "{:?}", p.warnings); +} + +#[test] +fn text_comes_in_as_point_type_in_the_named_font() { + let name = [be(&[9, 300]), vec![6], b"Geneva".to_vec()].concat(); + let bytes = v2( + [0, 0, 100, 200], + &[(0x2C, name), (0x03, be(&[300])), (0x0D, be(&[18])), (0x04, vec![1]), (0x28, [be(&[50, 10]), vec![4], b"Caf\x8E".to_vec()].concat())], + ); + let p = import_pict(&bytes).unwrap(); + let texts: Vec<_> = all(&p.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).collect(); + let NodeKind::Text(t) = &texts[0].kind else { panic!("text") }; + assert_eq!(t.plain_text(), "Café"); + let st = &t.runs[0].style; + assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Geneva", "Bold", 18.0)); + // The text location is the baseline's start. + assert_eq!(t.xf.translation(), Point::new(10.0, 50.0).to_vec2()); +} + +/// A pixel map's fields after `rowBytes` and its bounds: version, packing, resolution, depth and +/// components. +fn pixmap_fields(pack: i16, size: i16, cmps: i16) -> Vec { + be(&[0, pack, 0, 0, 72, 0, 72, 0, 0, size, cmps, 8, 0, 0, 0, 0, 0, 0]) +} + +#[test] +fn a_packed_indexed_pixel_map_becomes_an_image() { + let table = be(&[0, 0, 0, 1, 0, -1, 0, 0, 1, 0, 0, -1]); + // An 8 × 2 map: a run of red, then blue and red by turns. + let rows = [vec![2, 0xF9, 0], vec![9, 7, 1, 0, 1, 0, 1, 0, 1, 0]].concat(); + let data = + [be(&[0x8008u16 as i16]), rect(0, 0, 2, 8), pixmap_fields(0, 8, 1), table, rect(0, 0, 2, 8), rect(10, 20, 14, 36), be(&[0]), rows].concat(); + let p = import_pict(&v2([0, 0, 50, 50], &[(0x98, data)])).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let imgs = images(&p.document); + assert_eq!(imgs.len(), 1); + let (n, px) = &imgs[0]; + assert_eq!(px.dimensions(), (8, 2)); + assert_eq!(px.get_pixel(0, 0).0, [255, 0, 0, 255]); + assert_eq!(px.get_pixel(0, 1).0, [0, 0, 255, 255]); + assert_eq!(px.get_pixel(1, 1).0, [255, 0, 0, 255]); + // Drawn into its destination, twice its size. + assert!(near(n.geometric_bounds().unwrap(), Rect::new(20.0, 10.0, 36.0, 14.0), 1e-9)); +} + +#[test] +fn direct_pixel_maps_and_masked_bitmaps() { + // 32-bit, packed by component planes: red, then green. + let row = vec![7, 5, 255, 0, 0, 255, 0, 0]; + let direct = + [be(&[0, 0xFF, 0x8008u16 as i16]), rect(0, 0, 1, 2), pixmap_fields(4, 32, 3), rect(0, 0, 1, 2), rect(0, 0, 1, 2), be(&[0]), row].concat(); + // A one-bit bitmap ORed in (its clear bits left out), masked by a region. + let mask = [be(&[10]), rect(0, 0, 1, 1)].concat(); + let bitmap = [be(&[2]), rect(0, 0, 1, 2), rect(0, 0, 1, 2), rect(5, 0, 6, 2), be(&[1]), mask, vec![0x80, 0]].concat(); + let p = import_pict(&v2([0, 0, 10, 10], &[(0x9A, direct), (0x91, bitmap)])).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let imgs = images(&p.document); + assert_eq!(imgs.len(), 2); + assert_eq!(imgs[0].1.get_pixel(0, 0).0, [255, 0, 0, 255]); + assert_eq!(imgs[0].1.get_pixel(1, 0).0, [0, 255, 0, 255]); + assert_eq!(imgs[1].1.get_pixel(0, 0).0, [0, 0, 0, 255]); + assert_eq!(imgs[1].1.get_pixel(1, 0).0[3], 0, "the clear bit is left out"); + let layer = p.document.layers[0].children().unwrap(); + assert!(matches!(layer[1].kind, NodeKind::Group { clip: true, .. }), "the mask region clips the bitmap"); +} + +/// A pixel map's rows may be only a little longer than its pixels need: a map one pixel wide +/// with rows of 16,383 bytes is left out, and a pixel pattern like it fills with its bitmap. +#[test] +fn rows_far_longer_than_their_pixels_are_refused() { + let table = be(&[0, 0, 0, 1, 0, -1, 0, 0, 1, -1, 0, 0]); + // A row of 16,383 ones: 127 runs of 128 and one of 127, after its byte count. + let mut row = be(&[256]); + (0..127).for_each(|_| row.extend([0x81, 1])); + row.extend([0x82, 1]); + let rows = row.repeat(4); + let map = [be(&[0xBFFFu16 as i16]), rect(0, 0, 4, 1), pixmap_fields(0, 8, 1), table.clone()].concat(); + let data = [map, rect(0, 0, 4, 1), rect(0, 0, 4, 1), be(&[0]), rows].concat(); + let p = import_pict(&v2([0, 0, 10, 10], &[(0x98, data)])).unwrap(); + assert!(images(&p.document).is_empty()); + assert!(p.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", p.warnings); + + let pattern = [be(&[1]), vec![0xFF; 8], be(&[0xBFFFu16 as i16]), rect(0, 0, 1, 1), pixmap_fields(0, 8, 1), table, row].concat(); + let p = import_pict(&v2([0, 0, 10, 10], &[(0x12, pattern), (0x32, rect(0, 0, 5, 5))])).unwrap(); + assert_eq!(fill_rgb(&paths(&p.document)[0]), Some([0, 0, 0]), "the pattern's bitmap in the foreground color"); +} + +/// BitsRect rows are stored unpacked, also when a row is 8 bytes or longer. +#[test] +fn bitmap_rows_of_eight_bytes_or_more_are_read_unpacked() { + let row = vec![0x80, 0, 0, 0, 0, 0, 0, 0]; + let bitmap = [be(&[8]), rect(0, 0, 1, 16), rect(0, 0, 1, 16), rect(0, 0, 1, 16), be(&[0]), row].concat(); + let p = import_pict(&v2([0, 0, 10, 20], &[(0x90, bitmap), (0x31, rect(2, 2, 4, 4))])).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let imgs = images(&p.document); + assert_eq!(imgs.len(), 1); + assert_eq!(imgs[0].1.dimensions(), (16, 1)); + assert_eq!(imgs[0].1.get_pixel(0, 0).0, [0, 0, 0, 255]); + assert_eq!(imgs[0].1.get_pixel(1, 0).0, [255, 255, 255, 255]); + assert_eq!(paths(&p.document).len(), 1, "the rectangle after it"); +} + +/// An empty clip region clips away what follows it. +#[test] +fn an_empty_clip_region_hides_what_follows() { + let empty = [be(&[10]), rect(0, 0, 0, 0)].concat(); + let p = import_pict(&v2([0, 0, 50, 50], &[(0x01, empty), (0x31, rect(0, 0, 10, 10))])).unwrap(); + let layer = p.document.layers[0].children().unwrap(); + let NodeKind::Group { children, clip: true } = &layer[0].kind else { panic!("a clipping group: {:?}", layer[0].kind) }; + let b = children[0].geometric_bounds().unwrap(); + assert_eq!((b.width(), b.height()), (0.0, 0.0), "{b:?}"); +} + +/// A QuickTime image of `ctype` with `matrix` (a, b, c, d, tx, ty in points) and source rectangle +/// `w` × `h`, holding `data`. +fn quicktime(ctype: &[u8; 4], matrix: [f64; 6], w: i16, h: i16, data: &[u8]) -> Vec { + let fixed = |v: f64| ((v * 65536.0) as i32).to_be_bytes(); + let [a, b, c, d, tx, ty] = matrix; + let mut q = be(&[0]); + for v in [a, b, 0.0, c, d, 0.0, tx, ty] { + q.extend(fixed(v)); + } + q.extend((1i32 << 30).to_be_bytes()); + q.extend([0; 4]); + q.extend([0; 8]); + q.extend(be(&[0])); + q.extend(rect(0, 0, h, w)); + q.extend([0; 4]); + q.extend([0; 4]); + let mut desc = vec![]; + desc.extend(86u32.to_be_bytes()); + desc.extend(ctype); + desc.extend([0; 24]); + desc.extend(be(&[w, h])); + desc.extend([0; 8]); + desc.extend((data.len() as u32).to_be_bytes()); + desc.resize(86, 0); + q.extend(desc); + q.extend(data); + [(q.len() as u32).to_be_bytes().to_vec(), q].concat() +} + +fn red_jpeg() -> Vec { + let img = image::RgbImage::from_pixel(4, 2, image::Rgb([255, 0, 0])); + let mut out = std::io::Cursor::new(vec![]); + img.write_to(&mut out, image::ImageFormat::Jpeg).unwrap(); + out.into_inner() +} + +#[test] +fn quicktime_jpeg_images_are_placed_by_their_matrix() { + let jpeg = red_jpeg(); + let ops = [ + (0x8200, quicktime(b"jpeg", [2.0, 0.0, 0.0, 2.0, 10.0, 5.0], 4, 2, &jpeg)), + (0x8200, quicktime(b"rle ", [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], 4, 2, &[1, 2, 3])), + ]; + let p = import_pict(&v2([0, 0, 50, 50], &ops)).unwrap(); + let imgs = images(&p.document); + assert_eq!(imgs.len(), 1); + let (n, px) = &imgs[0]; + assert_eq!(px.dimensions(), (4, 2)); + let [r, g, b, _] = px.get_pixel(1, 1).0; + assert!(r > 240 && g < 16 && b < 16, "{r} {g} {b}"); + assert!(near(n.geometric_bounds().unwrap(), Rect::new(10.0, 5.0, 18.0, 9.0), 1e-9)); + assert!(p.warnings.iter().any(|w| w.contains("other than JPEG")), "{:?}", p.warnings); +} + +/// An image whose matrix flattens it is left out, and adds nothing to the document's images. +#[test] +fn a_flattened_image_adds_no_image_data() { + let p = import_pict(&v2([0, 0, 50, 50], &[(0x8200, quicktime(b"jpeg", [0.0; 6], 4, 2, &red_jpeg()))])).unwrap(); + assert!(images(&p.document).is_empty()); + assert!(p.document.images.is_empty(), "{:?}", p.document.images.keys().collect::>()); +} + +#[test] +fn pictures_cut_short_keep_what_came_before() { + let full = v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10)), (0x31, rect(20, 20, 30, 30))]); + // Cut inside the second rectangle. + let cut = &full[..full.len() - 6]; + let p = import_pict(cut).unwrap(); + assert_eq!(paths(&p.document).len(), 1); + assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings); + // A long comment longer than the file. + let p = import_pict(&v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10)), (0xA1, be(&[100, 5000]))])).unwrap(); + assert_eq!(paths(&p.document).len(), 1); + assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings); + // Nothing drawn. + let p = import_pict(&v2([0, 0, 50, 50], &[(0xA0, be(&[100]))])).unwrap(); + assert!(p.warnings.iter().any(|w| w.contains("draws nothing")), "{:?}", p.warnings); +} + +#[test] +fn reserved_opcodes_are_skipped_by_their_lengths() { + let ops = [ + // A 16-bit length, a fixed length for Apple's reserved words, and a 32-bit length. + (0x0024, be(&[4, 1, 2])), + (0x0200, be(&[1, 2])), + (0x00D0, [8u32.to_be_bytes().to_vec(), vec![9; 8]].concat()), + (0x8201, [2u32.to_be_bytes().to_vec(), vec![9; 2]].concat()), + (0x31, rect(0, 0, 10, 10)), + ]; + let p = import_pict(&v2([0, 0, 50, 50], &ops)).unwrap(); + assert_eq!(paths(&p.document).len(), 1, "{:?}", p.warnings); +} + +/// A picture of nothing but no-ops stops at the opcode limit. +#[test] +fn a_picture_that_never_ends_stops_at_the_opcode_limit() { + let mut b = v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10))]); + b.truncate(b.len() - 2); + b.resize(b.len() + 2 * ((1 << 22) + 1), 0); + let p = import_pict(&b).unwrap(); + assert_eq!(paths(&p.document).len(), 1); + assert!(p.warnings.iter().any(|w| w.contains("more opcodes")), "{:?}", p.warnings); +} + +/// Regions share one budget of inversion points per picture: past it, a region is left out. +#[test] +fn regions_past_the_picture_budget_are_left_out() { + // One scanline of 16,000 inversion points: 8,000 rectangles. + let mut words = vec![0]; + words.extend(0..16_000i16); + words.extend([0x7FFF, 1, 0x7FFF, 0x7FFF]); + let body = [rect(0, 0, 1, 16_000), be(&words)].concat(); + let region = [be(&[(body.len() + 2) as i16]), body].concat(); + let p = import_pict(&v2([0, 0, 300, 300], &[(0x81, region.clone()), (0x81, region.clone()), (0x81, region)])).unwrap(); + assert!(p.warnings.iter().any(|w| w.contains("regions larger")), "{:?}", p.warnings); + let v = paths(&p.document); + assert_eq!(v.len(), 2); + let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") }; + assert_eq!(path.subpaths.len(), 8_000); +} 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.rs b/crates/pdf/src/print.rs index 0bad9d9f60..12c71756c8 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -81,7 +81,10 @@ pub struct PrintOptions { pub struct PrintReport { pub bytes: Vec, pub pages: usize, + /// What the job leaves out of the document or prints differently. pub warnings: Vec, + /// Notes on the options: one the job didn't apply or applied another way. + pub setting_notes: Vec, } /// One page of a job, as [`preview`] lists it (one copy). @@ -129,7 +132,12 @@ pub struct PrintPreview { pub tiles: Vec, /// The inks of a separation (empty for composite output). pub inks: Vec, + /// What the job leaves out of the document or prints differently. pub warnings: Vec, + /// Notes on the options: one the job doesn't apply or applies another way. They aren't + /// serialized: a reply lists them in `warnings`, after what the job leaves out. + #[serde(skip)] + pub setting_notes: Vec, } /// A laid-out job. @@ -144,7 +152,10 @@ struct Job<'a> { plates: Vec, /// One copy's pages: (layout, plate). sheets: Vec<(usize, Option)>, + /// What the job leaves out of the document or prints differently. warnings: Vec, + /// Notes on the options: one the job doesn't apply or applies another way. + setting_notes: Vec, } /// Keep the layers of `nodes` that print as `which` says, shown (hidden ones print with All), @@ -223,11 +234,11 @@ impl<'a> Job<'a> { fn new(doc: &'a Document, set: &PrintSettings, postscript: bool) -> Result { set.check()?; let doc = printed_document(doc, set); - let mut warnings = vec![]; - let (layouts, tiles) = layout::layout(&doc, set, &mut warnings)?; + let (mut warnings, mut setting_notes) = (vec![], vec![]); + let (layouts, tiles) = layout::layout(&doc, set, &mut warnings, &mut setting_notes)?; let separations = set.output.mode == OutputMode::Separations; let (inks, more) = if separations { print_inks(&doc, set) } else { Default::default() }; - warnings.extend(more); + setting_notes.extend(more); let plates: Vec = (0..inks.len()).filter(|i| inks[*i].print).collect(); let printed: Vec> = if separations { (0..plates.len()).map(Some).collect() } else { vec![None] }; if printed.is_empty() { @@ -245,18 +256,18 @@ impl<'a> Job<'a> { warnings.push("the document is RGB: separations convert its colours to CMYK with the colour settings".into()); } if !postscript && separations && set.output.inks.iter().any(|i| i.frequency.is_some() || i.angle.is_some()) { - warnings.push("ink frequencies and angles are not written as halftone screens yet: the output device's screens apply".into()); + setting_notes.push("ink frequencies and angles are not written as halftone screens yet: the output device's screens apply".into()); } if separations && set.advanced.print_as_bitmap { - warnings.push("Print as Bitmap is for composite output: separations print the art as it is".into()); + setting_notes.push("Print as Bitmap is for composite output: separations print the art as it is".into()); } if separations && cms::profile(set.color.profile.trim()).is_some_and(|p| p.kind != ProfileKind::Cmyk) { - warnings.push("separations separate with a CMYK profile: the RGB printer profile is left out".into()); + setting_notes.push("separations separate with a CMYK profile: the RGB printer profile is left out".into()); } if !postscript && !set.graphics.auto_flatness { - warnings.push("a fixed flatness is not written yet: the output device flattens curves".into()); + setting_notes.push("a fixed flatness is not written yet: the output device flattens curves".into()); } - Ok(Self { doc, layouts, tiles, inks, plates, sheets, warnings }) + Ok(Self { doc, layouts, tiles, inks, plates, sheets, warnings, setting_notes }) } /// The ink of plate `plate` (`None`: composite). @@ -303,7 +314,14 @@ pub fn preview(doc: &Document, set: &PrintSettings) -> Result { pub title: String, /// When the job ran (Unix seconds, UTC). pub created: Option, + /// What the job leaves out of the document or prints differently. pub warnings: Vec, + /// Notes on the options: one the job doesn't apply or applies another way. + pub setting_notes: Vec, } /// Lay out printing `doc` as `opts` say, for a writer to draw. @@ -415,7 +436,7 @@ pub fn plan<'a>(doc: &'a Document, opts: &PrintOptions) -> Result, }) .collect(); let order = job.order(set); - Ok(PrintPlan { plates, sheets, order, title, created, warnings: job.warnings, doc: job.doc }) + Ok(PrintPlan { plates, sheets, order, title, created, warnings: job.warnings, setting_notes: job.setting_notes, doc: job.doc }) } /// Landscape sheet `s` upright on the paper ([`PrintOptions::for_printer`]): a page wider than @@ -473,12 +494,18 @@ fn print_inner(doc: &Document, opts: &PrintOptions, left_out: &mut HashSet = vec![]; + for m in plan.setting_notes.into_iter().chain(settings) { + if !warnings.contains(&m) && !setting_notes.contains(&m) { + setting_notes.push(m); + } + } + Ok(PrintReport { bytes, pages: plan.order.len(), warnings, setting_notes }) } /// The printer's marks of page `l` (`None` without marks), with its page information: the diff --git a/crates/pdf/src/print/layout.rs b/crates/pdf/src/print/layout.rs index 3d404abab9..a88dd89950 100644 --- a/crates/pdf/src/print/layout.rs +++ b/crates/pdf/src/print/layout.rs @@ -184,8 +184,14 @@ fn too_many_pages() -> PdfError { } /// The pages of `doc` (whose layers are those that print) as `set` lays them out, the tiles of -/// each artboard when tiling, and warnings (art that doesn't fit the imageable area). -pub(crate) fn layout(doc: &Document, set: &PrintSettings, warnings: &mut Vec) -> Result<(Vec, Vec), PdfError> { +/// each artboard when tiling. `warnings` gets what doesn't print (art outside the imageable area, +/// an artboard with no area), and `setting_notes` the copies per sheet that don't fit. +pub(crate) fn layout( + doc: &Document, + set: &PrintSettings, + warnings: &mut Vec, + setting_notes: &mut Vec, +) -> Result<(Vec, Vec), PdfError> { let marks = set.marks.printer_marks(); let bleed = set.bleed.of(doc); let (pw, ph) = set.paper(); @@ -278,7 +284,7 @@ pub(crate) fn layout(doc: &Document, set: &PrintSettings, warnings: &mut Vec { - warnings.push(format!("{what} with its bleed and marks doesn't fit the imageable area: it prints one copy per sheet")); + setting_notes.push(format!("{what} with its bleed and marks doesn't fit the imageable area: it prints one copy per sheet")); None } Some((cols, rows)) if cols * rows > MAX_COPIES_PER_SHEET as f64 => { diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index a46d1137a7..ce6c5b336e 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -1,5 +1,6 @@ //! Separations: the inks of a job ([`print_inks`]) and the document as one ink's plate, every -//! colour (and image pixel) replaced by the grey of that ink's coverage. +//! colour (and image pixel) replaced by the grey of that ink's coverage. An image placed from a +//! DCS file prints its own plates ([`vectorcraft_doc::separated`]). use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; @@ -130,7 +131,30 @@ impl<'a> Separator<'a> { kept.insert(colorized_key(&key), blob.clone()); } } + // A DCS file's image prints its own plates: a spot plate on its ink when the job prints + // that ink, else as its process equivalent. + let spots: BTreeSet = if self.set.output.spots_to_process { + BTreeSet::new() + } else { + plates(self.doc).into_iter().filter(|p| p.spot).map(|p| p.name).collect() + }; + let own = |name: &str| spots.contains(name); + // A spot plate printing as process prints as the document's swatch of its ink does, when + // there is one; else as the process equivalent its file gives. + let equivalent = |p: &vectorcraft_doc::separated::InkPlate| match self.doc.swatch(&p.name).and_then(|w| Some((w.paint.color()?, w.spot))) { + Some((c, spot)) => { + let c = self.doc.linked_color(c, spot); + cms::PROCESS_PLATES.map(|q| self.ink(q, &c, None)) + } + None => p.cmyk, + }; for blob in d.images.values_mut() { + if let Some(s) = blob.separated() { + if let Some(gray) = s.plate_png(plate, &own, &equivalent) { + *blob = gray; + } + continue; + } let gray = blob.map_rgb(|[r, g, b]| { let rgb = |v: u8| v as f32 / 255.0; let v = (255.0 * (1.0 - self.ink(plate, &Color::rgb(rgb(r), rgb(g), rgb(b)), None))).round() as u8; @@ -153,25 +177,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..5b86f2b895 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -322,6 +322,76 @@ fn image_doc(blob: ImageBlob, w: u32, h: u32) -> Document { d } +/// An image placed from a DCS file prints each of its plates on its own ink: a spot plate on its +/// spot ink's plate, or as its process equivalent when spots print as process. Its composite, the +/// CMYK samples every other reader sees, never prints on a separation. +#[test] +fn a_dcs_image_prints_each_plate_on_its_own_ink() { + use vectorcraft_doc::separated::{InkPlate, Separated}; + let plate = |name: &str, cmyk: [f32; 4], data: [u8; 2]| InkPlate { name: name.into(), cmyk, data: data.to_vec() }; + let s = Separated::new(2, 1, vec![plate("Cyan", [0.0; 4], [255, 0]), plate("Spot Orange", [0.0, 0.6, 1.0, 0.0], [128, 0])]).unwrap(); + let mut d = image_doc(ImageBlob::separated_tiff(&s, None, &[]).unwrap(), 2, 1); + d.swatches.push(Swatch { name: "Spot Orange".into(), paint: Paint::solid(Color::cmyk(0.0, 0.6, 1.0, 0.0)), global: true, spot: true }); + let plates = |spots_to_process: bool| { + let settings: PrintSettings = serde_json::from_value(json!({"output": {"mode": "separations", "spotsToProcess": spots_to_process}})).unwrap(); + let names: Vec = print_inks(&d, &settings).0.into_iter().map(|i| i.name).collect(); + let job = plan(&d, &PrintOptions { settings, ..Default::default() }).unwrap(); + let coverage: Vec> = job + .plates + .iter() + .map(|p| { + let NodeKind::Image(im) = &p.layers[0].children().unwrap()[0].kind else { panic!("an image") }; + p.image_blob(im).and_then(|b| b.coverage()).unwrap().2 + }) + .collect(); + names.into_iter().zip(coverage).collect::>() + }; + let own = plates(false); + let get = |all: &[(String, Vec)], name: &str| all.iter().find(|(n, _)| n == name).map(|(_, c)| c.clone()); + assert_eq!(get(&own, "Cyan"), Some(vec![255, 0])); + assert_eq!(get(&own, "Magenta"), Some(vec![0, 0]), "the spot ink stays off the process plates"); + assert_eq!(get(&own, "Yellow"), Some(vec![0, 0])); + assert_eq!(get(&own, "Spot Orange"), Some(vec![128, 0])); + let process = plates(true); + assert_eq!(get(&process, "Spot Orange"), None); + assert_eq!(get(&process, "Magenta"), Some(vec![77, 0]), "60% of the spot plate's 50%"); + assert_eq!(get(&process, "Yellow"), Some(vec![128, 0])); +} + +/// A DCS spot plate that prints as process prints as the document's swatch of its ink does (the +/// swatch kept in place of the plate's), not as the equivalent its file gives. +#[test] +fn a_dcs_spot_plate_printing_as_process_takes_the_documents_swatch() { + use vectorcraft_doc::separated::{InkPlate, Separated}; + let plate = |name: &str, cmyk: [f32; 4], data: [u8; 2]| InkPlate { name: name.into(), cmyk, data: data.to_vec() }; + let s = Separated::new(2, 1, vec![plate("Cyan", [0.0; 4], [255, 0]), plate("Spot Orange", [0.0, 0.6, 1.0, 0.0], [0, 128])]).unwrap(); + let mut d = image_doc(ImageBlob::separated_tiff(&s, None, &[]).unwrap(), 2, 1); + let plates = |d: &Document, spots_to_process: bool| { + let settings: PrintSettings = serde_json::from_value(json!({"output": {"mode": "separations", "spotsToProcess": spots_to_process}})).unwrap(); + let names: Vec = print_inks(d, &settings).0.into_iter().map(|i| i.name).collect(); + let job = plan(d, &PrintOptions { settings, ..Default::default() }).unwrap(); + let coverage = job.plates.iter().map(|p| { + let NodeKind::Image(im) = &p.layers[0].children().unwrap()[0].kind else { panic!("an image") }; + p.image_blob(im).and_then(|b| b.coverage()).unwrap().2 + }); + names.into_iter().zip(coverage).collect::>() + }; + let get = |all: &[(String, Vec)], name: &str| all.iter().find(|(n, _)| n == name).map(|(_, c)| c.clone()); + // A spot swatch of the ink in another color. + d.swatches.push(Swatch { name: "Spot Orange".into(), paint: Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)), global: true, spot: true }); + let process = plates(&d, true); + assert_eq!(get(&process, "Cyan"), Some(vec![255, 128]), "the swatch's cyan"); + assert_eq!(get(&process, "Magenta"), Some(vec![0, 0]), "not the file's magenta"); + assert_eq!(get(&process, "Yellow"), Some(vec![0, 0])); + // A process swatch of the ink's name: the job prints no plate for it. + d.swatches.retain(|w| w.name != "Spot Orange"); + d.swatches.push(Swatch { name: "Spot Orange".into(), paint: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), global: true, spot: false }); + let own = plates(&d, false); + assert_eq!(get(&own, "Spot Orange"), None); + assert_eq!(get(&own, "Black"), Some(vec![0, 128]), "the swatch's black"); + assert_eq!(get(&own, "Yellow"), Some(vec![0, 0])); +} + #[test] fn the_output_settings_convert_cmyk_images_and_compression_recompresses_them_in_cmyk() { let ink = [0u8, 102, 255, 0]; @@ -380,6 +450,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 +475,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 +521,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/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 897e7241b4..5c5e1eb2c0 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -275,11 +275,8 @@ fn an_artboard_that_does_not_fit_prints_one_copy_per_sheet() { let d = doc(700.0, 900.0, &[(Rect::new(0.0, 0.0, 700.0, 900.0), rgb(0.0, 0.0, 1.0))]); let r = job(&d, json!({"copiesPerSheet": true})); assert_eq!(r.pages, 1); - assert!( - r.warnings.iter().any(|w| w == "Artboard 1 with its bleed and marks doesn't fit the imageable area: it prints one copy per sheet"), - "{:?}", - r.warnings - ); + // A note on the options; the art that doesn't print is what the job loses. + assert_eq!(r.setting_notes, ["Artboard 1 with its bleed and marks doesn't fit the imageable area: it prints one copy per sheet"]); assert!(r.warnings.iter().any(|w| w.contains("larger than the imageable area")), "{:?}", r.warnings); assert_eq!(r.bytes, job(&d, json!({})).bytes, "printed as without copies per sheet"); assert!(preview(&d, &settings(json!({"copiesPerSheet": true}))).unwrap().sheets[0].copies.is_empty()); diff --git a/crates/pdf/src/tests/printadvanced.rs b/crates/pdf/src/tests/printadvanced.rs index f9dacb7597..8ff14f2fd1 100644 --- a/crates/pdf/src/tests/printadvanced.rs +++ b/crates/pdf/src/tests/printadvanced.rs @@ -136,5 +136,5 @@ fn separations_separate_with_a_cmyk_printer_profile() { assert_ne!(device, press, "the profile separates"); // An RGB printer profile doesn't separate. let r = job(&d, json!({"output": {"mode": "separations"}, "color": {"profile": cms::SRGB}})); - assert!(r.warnings.iter().any(|w| w.contains("RGB printer profile")), "{:?}", r.warnings); + assert!(r.setting_notes.iter().any(|w| w.contains("RGB printer profile")), "{:?}", r.setting_notes); } diff --git a/crates/pdf/src/tests/realtext.rs b/crates/pdf/src/tests/realtext.rs index 3db63a4b2a..a36cea3ee7 100644 --- a/crates/pdf/src/tests/realtext.rs +++ b/crates/pdf/src/tests/realtext.rs @@ -976,7 +976,10 @@ fn dithered_type_keeps_its_resolution_when_scaled_and_stays_searchable() { /// Exact craft-fonts face: a substituted Arabic font would miss Noto's dot decomposition. fn mark_text(text: &str) -> Option { - let face = FontDb::global().face("Noto Sans Arabic", "Regular").filter(|f| f.family == "Noto Sans Arabic"); + // The craft-fonts build of the face: a system font of the same family (Linux distributions + // install one) can lack the Latin and digit glyphs these fixtures shape with it. + let bundled = vectorcraft_text::CRAFT_FONTS.iter().any(|f| f.family == "Noto Sans Arabic" && f.style == "Regular"); + let face = FontDb::global().face("Noto Sans Arabic", "Regular").filter(|f| bundled && f.family == "Noto Sans Arabic"); let Some(face) = face else { assert!(std::env::var("CRAFT_FONTS_REQUIRED").as_deref() != Ok("1"), "Noto Sans Arabic is required"); eprintln!("SKIPPED: PDF mark-text regression needs craft-fonts Noto Sans Arabic"); 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/predicates.rs b/crates/render/src/fx/predicates.rs index 2592d2b64e..4f14cadfd1 100644 --- a/crates/render/src/fx/predicates.rs +++ b/crates/render/src/fx/predicates.rs @@ -54,13 +54,15 @@ pub(super) fn evaluates_live(n: &Node) -> bool { /// through live objects it evaluates? It can when `n` holds type (laid out in the fonts installed), /// a symbol instance (made from its symbol's art), an object with a 3D effect or a color /// adjustment (shaded or recolored through the color settings), one with Vector Halftone (its -/// dots sampled from everything it draws), or one with a live-effect plug-in that paints its pieces -/// (drawn only while the swatches and patterns they name are in the document), in it or in the -/// opacity masks of the objects in it. +/// dots sampled from everything it draws), one with a live-effect plug-in that paints its pieces +/// (drawn only while the swatches and patterns they name are in the document), or an image with a +/// fill or stroke that follows the outline of its pixels ([`effects::follows_image_pixels`]: the +/// document's pixels for it can change), in it or in the opacity masks of the objects in it. pub(super) fn reads_outside(n: &Node) -> bool { let mut reads = false; n.walk(&mut |c| { reads |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. }) + || effects::follows_image_pixels(c) || effects::has_revolve(c) || effects::has_solid(c) || effects::has_adjustment(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/live.rs b/crates/render/src/live.rs index 2b6610beb1..4d41e16af8 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -9,7 +9,8 @@ //! envelope around an instance of it). What the walk behind that key found is kept with the node //! and with the document's symbols and patterns as the walk read them ([`Walk`]). A later frame //! makes the key from what was kept while the node and the document's symbols and patterns stay -//! the same. A walk that found a placed file is not kept. +//! the same. A walk that found a placed file, or an image whose own fills or strokes follow its +//! pixels, is not kept. //! Gradient meshes are tessellated into many small solid-colour quads (vello //! has no mesh shading), with the density chosen from the on-screen patch size; each quad is //! grown by half a device pixel along its edges so neighbours overlap and no antialiasing seams @@ -44,7 +45,8 @@ type Walk = (Weak, Walked, Arc); /// Per-renderer cache of evaluated live objects: (live node, its evaluation, [`Found`]), a /// [`MeshEntry`] per mesh node and subdivision level, and a [`Walk`] per node whose key -/// [`Renderer::live_found`] found without finding a placed file. +/// [`Renderer::live_found`] found without finding a placed file or an image whose own fills or +/// strokes follow its pixels. pub(crate) struct LiveCache { expanded: FrameCache, Expanded, Found)>, meshes: FrameCache<(usize, usize), MeshEntry>, @@ -97,7 +99,8 @@ pub fn expand_live(n: &Node) -> Vec { /// What the evaluation of `n` (a live node, or an object whose effect art the renderer keeps with /// its inputs, see [`Renderer::live_found`]) reads from the document, placed files, /// the fonts, the plug-ins and the color settings, hashed: the art of the symbols, the tilings of -/// the patterns and the reads of the placed files it shows ([`hash_resources`]), the font +/// the patterns, the reads of the placed files it shows and the document's pixels for the images +/// whose own fills or strokes follow them ([`hash_resources`]), the font /// generation ([`vectorcraft_text::FontDb::generation`]) when it shows type or a placed file, the /// plug-in revision ([`crate::effects::plugin_revision`]) and `names` (the hash of the document's /// swatch and pattern names, [`DocInputs`]) when it shows an object with a plug-in effect, since a @@ -105,13 +108,13 @@ pub fn expand_live(n: &Node) -> Vec { /// while the swatches and patterns they name are in the document, and the color settings (`cms`, /// their address). Art is hashed by the addresses of its `Arc`s, which copies of the document /// share: a copy of the document has the same key. It also returns weak references to the reads -/// found, and what the walk found ([`Walked`]) when it found no placed file. +/// found, and what the walk found ([`Walked`]) when it found no placed file and no such image. fn resources_key(doc: &Document, cms: usize, names: u64, n: &Node) -> (u64, Vec>, Option) { let mut h = DefaultHasher::new(); let mut shown = Shown::default(); hash_resources(doc, n, &mut shown, &mut h); let walked = Walked { hash: h.finish(), text: shown.text, plugins: shown.plugins }; - (walked.key(cms, names), shown.reads, (!shown.placed).then_some(walked)) + (walked.key(cms, names), shown.reads, (!shown.placed && !shown.pixels).then_some(walked)) } /// What [`hash_resources`] found in a node: the hash of what it walked, whether it found type or @@ -153,6 +156,10 @@ struct Shown { text: bool, /// Whether a placed file was found. placed: bool, + /// Whether an image whose own fills or strokes follow its pixels was found + /// ([`crate::effects::follows_image_pixels`]): the document's pixels for it can change while + /// the walk's symbols and patterns stay the same. + pixels: bool, /// Whether an object with a visible plug-in effect was found. plugins: bool, /// Weak references to the reads of the placed files found. @@ -163,9 +170,11 @@ struct Shown { /// tilings ([`crate::pattern::hash_tiling`]) of the patterns in the fills and strokes of its /// objects and of type's characters, the address of each symbol instance's art, and the address of /// the read of each placed file that [`vectorcraft_doc::PlacedDocument::art`] shows (none before -/// the file is read). It walks `n` and then, one at a time from a list, the opacity-mask, pattern -/// and symbol art it finds, each pattern and each symbol's art once ([`first_seen`]). `shown` -/// records the type, placed files, reads and plug-in effects found. +/// the file is read), and the address of the document's pixels for each image whose +/// own fills or strokes follow them ([`crate::effects::follows_image_pixels`]). It walks `n` and +/// then, one at a time from a list, the opacity-mask, pattern and symbol art it finds, each pattern +/// and each symbol's art once ([`first_seen`]). `shown` records the type, placed files, reads, +/// such images and plug-in effects found. fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) { let mut todo = vec![]; let mut next = Some(n); @@ -203,6 +212,12 @@ fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut shown.placed = true; } NodeKind::Text(_) => shown.text = true, + // The address of the pixels the document holds for the image, which Update Link + // replaces under the same key ([`DocInputs`] holds them weakly). + NodeKind::Image(im) if crate::effects::follows_image_pixels(c) => { + doc.images.get(&im.key).map(|b| Arc::as_ptr(&b.bytes) as usize).hash(h); + shown.pixels = true; + } _ => {} } if let Some(m) = c.extras().mask.as_deref() { @@ -442,7 +457,7 @@ impl Renderer { /// evaluated live objects, type, symbol art or colors shaded through the color settings. The /// key is made from the [`Walk`] kept for `n` while `doc`'s symbols and patterns are those it /// read; `n` is walked again when they changed, and in every frame when the walk found a - /// placed file. + /// placed file or an image whose own fills or strokes follow its pixels. pub(crate) fn live_found(&mut self, doc: &Document, n: &Arc) -> Found { let inputs = self.doc_inputs(doc); let at = Arc::as_ptr(n) as usize; 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/proof.rs b/crates/render/src/proof.rs index 15d5b4644a..a6736b022d 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -10,7 +10,8 @@ //! Registration swatch print their tint on every plate, spot plates included. //! Placed raster images show their pixels' process inks the same way ([`plate_image`]): a CMYK //! image its own inks, an RGB one its pixels separated through the color settings. They carry -//! no spot ink; a colorized image takes its color's plates, as a fill of it does. +//! no spot ink; a colorized image takes its color's plates, as a fill of it does. An image +//! placed from a DCS file shows its own plates, spot plates included ([`plates_shown`]). //! * **Overprint Preview** (and Separations Preview, which implies it): fills and strokes that //! overprint ([`vectorcraft_doc::FillLayer::overprint`], characters' too) are drawn with //! Darken, which approximates their inks printing over the inks below: a zero ink lets the @@ -82,6 +83,10 @@ fn plate_color(doc: &Document, c: &Cms, proof: &ProofSetup, visible: &[String], /// profiles. Each table is made when an image first needs it. pub(crate) struct PlateLut { proof: ProofSetup, + /// The document's solid swatches: name, whether it is a spot color, and its color. An image + /// placed from a DCS file shows a spot plate on its own ink only when it is one of the spot + /// ones, in that swatch's color, and else as the swatch of its name ([`plates_shown`]). + swatches: Vec<(String, bool, Color)>, cms: Arc, /// [`cms::profiles_generation`]. profiles: u64, @@ -107,20 +112,29 @@ static PLATE_LUTS: Mutex>> = Mutex::new(Vec::new()); /// The last [`PlateLut::generation`] handed out. static PLATE_GENERATION: AtomicU64 = AtomicU64::new(0); -/// The tables placed images show Separations Preview's visible plates through with `opts`, or -/// `None` when it is off. -pub(crate) fn plate_lut(opts: &RenderOptions) -> Option> { +/// The tables the placed images of `doc` show Separations Preview's visible plates through with +/// `opts`, or `None` when it is off. +pub(crate) fn plate_lut(opts: &RenderOptions, doc: &Document) -> Option> { let proof = opts.proof.as_ref().filter(|p| p.separations.is_some())?; let (c, profiles) = (cms::active(), cms::profiles_generation()); + // The spot ones are the spot plates of `vectorcraft_doc::inks::plates`; their colors are part + // of the tables' identity, so a swatch edit shows. + let swatches: Vec<(String, bool, Color)> = doc + .swatches_iter() + .filter_map(|s| match &s.paint { + vectorcraft_color::Paint::Solid { color, .. } => Some((s.name.clone(), s.spot, doc.linked_color(*color, s.spot))), + _ => None, + }) + .collect(); let mut luts = PLATE_LUTS.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(l) = luts.iter().find(|l| Arc::ptr_eq(&l.cms, &c) && l.profiles == profiles && l.proof == *proof) { + if let Some(l) = luts.iter().find(|l| Arc::ptr_eq(&l.cms, &c) && l.profiles == profiles && l.proof == *proof && l.swatches == swatches) { return Some(l.clone()); } if luts.len() >= 4 { luts.remove(0); } let generation = PLATE_GENERATION.fetch_add(1, Ordering::Relaxed) + 1; - let l = Arc::new(PlateLut { proof: proof.clone(), cms: c, profiles, generation, rgb: OnceLock::new(), cmyk: OnceLock::new() }); + let l = Arc::new(PlateLut { proof: proof.clone(), swatches, cms: c, profiles, generation, rgb: OnceLock::new(), cmyk: OnceLock::new() }); luts.push(l.clone()); Some(l) } @@ -134,6 +148,11 @@ pub(crate) fn plate_image(lut: &PlateLut, key: &ImageKey, pm: &Pixmap, blob: Opt if let Some(p) = lookup(&want, touch) { return (want, p); } + // An image placed from a DCS file shows its own plates, spot plates included. + if let Some(s) = blob.filter(|b| crate::ink::shows_own_inks(key) && b.is_separated()).and_then(ImageBlob::separated) { + let out = images::store().insert(want.clone(), Arc::new(plates_shown(lut, &s, pm))); + return (want, out); + } let size = (u32::from(pm.width()), u32::from(pm.height())); let raw = crate::ink::key_inks(key, blob).filter(|i| (i.width, i.height) == size); let mut out = pm.clone(); @@ -165,6 +184,117 @@ pub(crate) fn plate_image(lut: &PlateLut, key: &ImageKey, pm: &Pixmap, blob: Opt (want, out) } +/// The visible plates of separated image `s` drawn at the size of `pm` (each pixel the mean of the +/// plate pixels it covers, [`Fit`]): with one spot plate visible its ink as a grey, else the +/// visible process inks through `lut` with the visible spot inks multiplied on top, each in the +/// color of the document's spot swatch of its ink. A spot plate whose ink the document has no spot +/// swatch for shows on the process plates as it prints +/// ([`vectorcraft_doc::separated::Separated::coverage_as`]): as the document's swatch of its name +/// when there is one, else as the process equivalent its file gives. +fn plates_shown(lut: &PlateLut, s: &vectorcraft_doc::separated::Separated, pm: &Pixmap) -> Pixmap { + let visible = lut.proof.separations.as_deref().unwrap_or_default(); + let shown = |name: &str| visible.iter().any(|v| v == name); + let swatch = |name: &str| lut.swatches.iter().find(|(n, ..)| n == name); + let own = |name: &str| swatch(name).is_some_and(|(_, spot, _)| *spot); + let (w, h) = (usize::from(pm.width()).max(1), usize::from(pm.height()).max(1)); + let fit = Fit::new(((s.width as usize).max(1), (s.height as usize).max(1)), (w, h)); + let alone = match visible { + [one] if !PROCESS_PLATES.contains(&one.as_str()) => Some(s.plates.iter().find(|p| p.name == *one && own(&p.name))), + _ => None, + }; + let spots: Vec<(&[u8], [f32; 3])> = s + .spots() + .filter(|p| own(&p.name) && shown(&p.name)) + .map(|p| (p.data.as_slice(), swatch(&p.name).map_or_else(|| lut.cms.cmyk_to_srgb(p.cmyk, false), |(.., c)| lut.cms.display_rgb(c)))) + .collect(); + // The plates that print on the process plates, each with the process inks it stands for. + let process: Vec<(&[u8], [f32; 4])> = s + .plates + .iter() + .filter(|p| !p.spot() || !own(&p.name)) + .map(|p| { + let inks = match swatch(&p.name) { + Some((.., c)) if p.spot() => lut.cms.to_cmyk(c, lut.proof.intent), + _ => p.cmyk, + }; + (p.data.as_slice(), inks) + }) + .collect(); + let t = lut.cmyk.get_or_init(|| { + CmykLut::build(|inks| { + let [x, y, z] = lab::srgb_to_xyz(lut.shown(inks)); + [x, y, z, 0.0] + }) + }); + let mut out = pm.clone(); + for (at, o) in out.data_mut().iter_mut().enumerate() { + let ink = |data: &[u8]| fit.ink(data, at); + let rgb = match alone { + Some(p) => [1.0 - p.map_or(0.0, |p| ink(&p.data)); 3], + None => { + let mut clear = [1.0f32; 4]; + for (data, inks) in &process { + let a = ink(data); + for (c, e) in clear.iter_mut().zip(inks) { + *c *= 1.0 - a * e; + } + } + let [x, y, z, _] = t.apply(clear.map(|c| 1.0 - c)); + let mut rgb = lab::xyz_to_srgb([x, y, z]); + for (data, c) in &spots { + let a = ink(data); + for (v, c) in rgb.iter_mut().zip(c) { + *v *= 1.0 - a * (1.0 - c); + } + } + rgb + } + }; + let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + *o = PremulRgba8 { r, g, b, a: 255 }; + } + out +} + +/// Plates of `from` (width, height) pixels drawn at `to` pixels: each pixel the mean of the plate +/// pixels it covers, so a reduced image (a smaller mip level) keeps the coverage the plate has; the +/// nearest plate pixel when it covers less than one. It keeps only the spans of each column and +/// row, not a copy of any plate. +struct Fit { + /// The plate's width. + sw: usize, + /// The shown width. + w: usize, + /// The plate columns each shown column covers, `start..end`. + columns: Vec<(usize, usize)>, + /// The plate rows each shown row covers, `start..end`. + rows: Vec<(usize, usize)>, +} + +impl Fit { + fn new((sw, sh): (usize, usize), (w, h): (usize, usize)) -> Self { + // The plate pixels each shown column or row covers: at least one. + // In 64 bits: a plate's width times the shown width may not fit 32 (the web build). + let span = |i: usize, n: usize, of: usize| { + let at = |i: usize| usize::try_from(i as u64 * of as u64 / n as u64).unwrap_or(of); + let start = at(i).min(of - 1); + (start, at(i + 1).clamp(start + 1, of)) + }; + Self { sw, w, columns: (0..w).map(|x| span(x, w, sw)).collect(), rows: (0..h).map(|y| span(y, h, sh)).collect() } + } + + /// The ink of plate `data` at shown pixel `at` (row by row), from 0 to 1. + fn ink(&self, data: &[u8], at: usize) -> f32 { + let (Some(&(x0, x1)), Some(&(y0, y1))) = (self.columns.get(at % self.w), self.rows.get(at / self.w)) else { return 0.0 }; + let mut sum = 0u64; + for row in y0..y1 { + sum += data.get(row * self.sw + x0..row * self.sw + x1).map_or(0, |r| r.iter().map(|&v| u64::from(v)).sum()); + } + let n = ((y1 - y0) * (x1 - x0)) as u64; + sum as f32 / n as f32 / 255.0 + } +} + /// The art a renderer drew with Overprint Preview or Separations Preview, kept for its next frame /// ([`prepare`]): the document's layers and symbol art as they were, each beside the art drawn for /// it, and what that art was made with. The kept nodes keep their addresses: no other node gets diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index fc729c1cc3..500d62d5b4 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -150,7 +150,7 @@ impl Renderer { let screen = if opts.rich_black { Ink::RichBlack } else { Ink::Display }; let symbols = doc.symbol_boxes().quick(); let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; - let plates = proof::plate_lut(opts); + let plates = proof::plate_lut(opts, doc); let frame = Frame { mt: threads > 0, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() }; self.begin_frame(); // View Opacity Mask: the mask's coverage in greyscale instead of the artwork. 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/render/src/tests/colorize.rs b/crates/render/src/tests/colorize.rs index 49e14e5e68..721707502d 100644 --- a/crates/render/src/tests/colorize.rs +++ b/crates/render/src/tests/colorize.rs @@ -182,6 +182,113 @@ fn separations_preview_shows_the_image_on_its_spot_plate() { assert!(off[..3].iter().all(|v| *v >= 250), "the process plates show paper, got {off:?}"); } +/// Separations Preview shows an image placed from a DCS file through its own plates: its spot +/// plate on that ink's plate only, its cyan plate on the cyan plate only. Without the preview it +/// shows its composite, the spot ink mixed in. +#[test] +fn separations_preview_shows_a_dcs_image_through_its_own_plates() { + use vectorcraft_doc::separated::{InkPlate, Separated}; + // Two pixels: the spot ink solid on the left, cyan solid on the right. + let plates = vec![ + InkPlate { name: "Cyan".into(), cmyk: [0.0; 4], data: vec![0, 255] }, + InkPlate { name: "Ink".into(), cmyk: [0.0, 1.0, 1.0, 0.0], data: vec![255, 0] }, + ]; + let s = Separated::new(2, 1, plates).unwrap(); + let mut d = Document::new_with_mode(40.0, 20.0, vectorcraft_doc::ColorMode::Cmyk); + d.swatches.push(vectorcraft_color::Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), global: true, spot: true }); + d.images.insert("pic".into(), ImageBlob::separated_tiff(&s, None, &[]).unwrap()); + let im = ImageObject { key: "pic".into(), width: 2, height: 1, xf: Affine::scale(20.0), link: None, placement: Default::default(), pixels: None }; + let (layer, id) = (d.layers[0].id, d.alloc_id()); + d.insert(Some(layer), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + let shown = |plates: &[&str]| { + let out = Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &separations(plates)); + (out.pixel(10, 10), out.pixel(30, 10)) + }; + let (left, right) = shown(&["Ink"]); + assert!(left[..3].iter().all(|v| *v < 20), "the Ink plate shows the spot plate as solid ink, got {left:?}"); + assert!(right[..3].iter().all(|v| *v >= 250), "and nothing of cyan, got {right:?}"); + let (left, right) = shown(&["Cyan"]); + assert!(left[..3].iter().all(|v| *v >= 250), "the Cyan plate shows nothing of the spot ink, got {left:?}"); + assert!(right[..3].iter().all(|v| *v < 20), "and the cyan plate as solid ink, got {right:?}"); + let (left, _) = shown(&["Cyan", "Magenta", "Yellow", "Black"]); + assert!(left[..3].iter().all(|v| *v >= 250), "the process plates show paper where only the spot ink prints, got {left:?}"); + let (left, _) = shown(&["Cyan", "Magenta", "Yellow", "Black", "Ink"]); + assert!(left[0] > 150 && left[1] < 100 && left[2] < 100, "with every plate the spot ink shows red, got {left:?}"); + let composite = Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &RenderOptions { smooth_images: false, ..Default::default() }).pixel(10, 10); + assert!(composite[0] > 150 && composite[1] < 100, "the composite mixes the spot ink in, got {composite:?}"); + // Without a spot swatch of the ink, the job prints no plate for it: it shows on the process + // plates as its process equivalent, as it prints. + d.swatches.retain(|s| s.name != "Ink"); + let process = Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &separations(&["Cyan", "Magenta", "Yellow", "Black"])).pixel(10, 10); + assert!(process[0] > 150 && process[1] < 100 && process[2] < 100, "the ink's magenta and yellow show, got {process:?}"); + let magenta = Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &separations(&["Magenta"])).pixel(10, 10); + assert!(magenta[..3].iter().all(|v| *v < 20), "the Magenta plate alone shows it as solid ink, got {magenta:?}"); +} + +/// A document of 40 × 20 pt holding separated image `s` (2 × 1 pixels) at 20 pt a pixel. +fn separated_doc(s: &vectorcraft_doc::separated::Separated) -> Document { + let mut d = Document::new_with_mode(40.0, 20.0, vectorcraft_doc::ColorMode::Cmyk); + d.images.insert("pic".into(), ImageBlob::separated_tiff(s, None, &[]).unwrap()); + let im = ImageObject { + key: "pic".into(), + width: s.width, + height: s.height, + xf: Affine::scale(40.0 / f64::from(s.width)), + link: None, + placement: Default::default(), + pixels: None, + }; + let (layer, id) = (d.layers[0].id, d.alloc_id()); + d.insert(Some(layer), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + d +} + +/// A DCS spot plate shows in the color of the document's swatch of its ink, as the art on that ink +/// does, and follows an edit of the swatch. +#[test] +fn separations_preview_colors_a_dcs_spot_plate_by_the_documents_swatch() { + use vectorcraft_doc::separated::{InkPlate, Separated}; + // The file says the ink is red; the document's swatch of it is cyan. + let s = Separated::new(2, 1, vec![InkPlate { name: "Ink".into(), cmyk: [0.0, 1.0, 1.0, 0.0], data: vec![255, 0] }]).unwrap(); + let mut d = separated_doc(&s); + d.swatches.push(vectorcraft_color::Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)), global: true, spot: true }); + let all = ["Cyan", "Magenta", "Yellow", "Black", "Ink"]; + let left = |d: &Document, plates: &[&str]| Renderer::new().render(d, 40, 20, Affine::IDENTITY, &separations(plates)).pixel(10, 10); + let p = left(&d, &all); + assert!(p[0] < 100 && p[2] > 150, "the swatch's cyan, not the file's red, got {p:?}"); + // The swatch edited to yellow: the image follows. + if let Some(w) = d.swatches.iter_mut().find(|w| w.name == "Ink") { + w.paint = Paint::solid(Color::cmyk(0.0, 0.0, 1.0, 0.0)); + } + let p = left(&d, &all); + assert!(p[0] > 150 && p[2] < 100, "the edited swatch's yellow, got {p:?}"); + // A process swatch of the ink's name: the plate shows on the process plates as that swatch. + if let Some(w) = d.swatches.iter_mut().find(|w| w.name == "Ink") { + (w.paint, w.spot) = (Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)), false); + } + let p = left(&d, &all[..4]); + assert!(p[0] < 100 && p[2] > 150, "the process swatch's cyan, got {p:?}"); +} + +/// A DCS image drawn reduced (from a smaller mip level) shows the coverage its plate has there, +/// the mean of the plate pixels each reduced pixel covers. +#[test] +fn separations_preview_keeps_a_reduced_dcs_plates_coverage() { + use vectorcraft_doc::separated::{InkPlate, Separated}; + // 64 × 64 pixels, the spot ink solid on every other column: 50% coverage. + let data: Vec = (0..64 * 64).map(|i| if i % 2 == 0 { 255 } else { 0 }).collect(); + let s = Separated::new(64, 64, vec![InkPlate { name: "Ink".into(), cmyk: [0.0, 1.0, 1.0, 0.0], data }]).unwrap(); + let mut d = Document::new_with_mode(64.0, 64.0, vectorcraft_doc::ColorMode::Cmyk); + d.swatches.push(vectorcraft_color::Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), global: true, spot: true }); + d.images.insert("pic".into(), ImageBlob::separated_tiff(&s, None, &[]).unwrap()); + let im = ImageObject { key: "pic".into(), width: 64, height: 64, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let (layer, id) = (d.layers[0].id, d.alloc_id()); + d.insert(Some(layer), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + let opts = RenderOptions { image_mips: true, ..separations(&["Ink"]) }; + let p = Renderer::new().render(&d, 16, 16, Affine::scale(0.25), &opts).pixel(8, 8); + assert!(p[..3].iter().all(|v| (100..=160).contains(v)), "half the ink, got {p:?}"); +} + /// Separations Preview showing `plates`, as the canvas draws it. fn separations(plates: &[&str]) -> RenderOptions { let proof = proof::ProofSetup { separations: Some(plates.iter().map(|p| p.to_string()).collect()), ..Default::default() }; diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index 7e4007c6ac..e8cf7a1745 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -771,6 +771,27 @@ fn rasterize_on_an_image_takes_in_its_strokes_shape() { assert_eq!((lum(img.pixel(8, 35)), lum(img.pixel(12, 35)), img.pixel(35, 35)), (WHITE, 0, [255, 0, 0, 255])); } +#[test] +fn an_images_outline_object_stroke_follows_new_pixels_under_the_same_key() { + // The opaque image's stroke runs along its frame, from 18 to 22. + let mut d = stroked_image_doc(vec![fx("path.outlineObject", json!({}))], false); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + let img = r.render(&d, 100, 100, Affine::IDENTITY, &opts); + assert_eq!((lum(img.pixel(19, 35)), img.pixel(26, 35)), (0, [255, 0, 0, 255])); + // New pixels under the same key, as Update Link stores them, with the node unchanged: an + // opaque disc of radius 8 pixels in the middle. The stroke follows its edge at 26.5. + let disc = image::RgbaImage::from_fn(30, 30, |x, y| { + let r = (f64::from(x) + 0.5 - 15.0).hypot(f64::from(y) + 0.5 - 15.0); + image::Rgba([255, 0, 0, if r <= 8.0 { 255 } else { 0 }]) + }); + let mut png = vec![]; + disc.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + d.images.insert("red".into(), ImageBlob::new("image/png", png)); + let img = r.render(&d, 100, 100, Affine::IDENTITY, &opts); + assert_eq!((lum(img.pixel(19, 35)), lum(img.pixel(26, 35))), (WHITE, 0)); +} + /// A 40 pt square filled with `fill` carrying effect `id`, in a 100×100 document. fn glowing_square(fill: Color, id: &str, params: Value) -> Document { let mut n = Node::path(NodeId(0), shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)), Appearance::basic(Paint::solid(fill), Paint::None, 0.0)); 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/svg/src/export/text/tests.rs b/crates/svg/src/export/text/tests.rs index fa8ca0455c..951817c2c5 100644 --- a/crates/svg/src/export/text/tests.rs +++ b/crates/svg/src/export/text/tests.rs @@ -90,6 +90,17 @@ fn japanese_type_with_mojikumi_is_laid_out_again() { assert_eq!(layouts_again(&none, true), 0); } +/// A middle dot is a character the Mojikumi sets space: type holding only middle dots is laid out +/// again with each set that spaces them. +#[test] +fn middle_dots_with_mojikumi_are_laid_out_again() { + for set in [Mojikumi::YakumonoHankaku, Mojikumi::GyomatsuYakumonoHankaku] { + let mut t = point("・・"); + t.para.mojikumi = set; + assert_eq!(layouts_again(&t, true), 1, "{set:?}"); + } +} + #[test] fn a_japanese_run_or_paragraph_lays_the_whole_object_out_again() { let mut runs = point("Latin "); diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index fa91e97875..23e00afa0c 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -15,6 +15,9 @@ use super::{ Ordering, Size, }; +/// The most faces [`FontDb::postscript_faces`] gives, and the most families it loads. +const MAX_POSTSCRIPT_FACES: usize = 16; + impl FontDb { /// The family's own name and the style for a name given in a document: any of a family's /// names (`ヒラギノ角ゴシック` is Hiragino Sans), a legacy family name (`Hiragino Sans W6` with its @@ -141,6 +144,33 @@ impl FontDb { loaded(self) } + /// Every installed face that [`find_postscript`](Self::find_postscript) could give for `name` + /// (its PostScript name ignoring case and anything but letters and digits), its answer first, + /// then the others in load order, at most 16 in all: copies of one font in + /// other families (`SampleSerif` beside `Sample Serif`) or versions, and names that differ + /// only in case. Each family that has one is loaded from the system fonts whole, as + /// [`versions`](Self::versions) loads one. Empty when no installed font has the name. + pub fn postscript_faces(&self, name: &str) -> Vec> { + let Some(first) = self.find_postscript(name) else { return vec![] }; + let key = norm(name); + let mut families: Vec = vec![first.family.clone()]; + if let Some(v) = self.aliases.read().unwrap_or_else(|e| e.into_inner()).get(&key) { + for a in v.iter().filter(|a| a.paired.is_none() && a.style.is_some()) { + if families.len() < MAX_POSTSCRIPT_FACES && !families.iter().any(|f| f.eq_ignore_ascii_case(&a.family)) { + families.push(a.family.clone()); + } + } + } + for family in &families { + self.load_family_files(family); + } + let mut out = vec![first.clone()]; + let faces = self.read_faces(); + let others = faces.iter().filter(|f| f.id != first.id && f.keys.postscript.contains(&key)); + out.extend(others.take(MAX_POSTSCRIPT_FACES - 1).cloned()); + out + } + /// The (family, style) of the installed face whose PostScript name is `name` (ignoring ASCII /// case). Documents name fonts this way, and a family can hold hyphens /// ("Rounded-X-Mplus-1c-black" is Rounded-X M+ 1c, black), so the name can't be split. diff --git a/crates/text/src/justify.rs b/crates/text/src/justify.rs index 17edeb4d86..6be6a6ab4a 100644 --- a/crates/text/src/justify.rs +++ b/crates/text/src/justify.rs @@ -167,6 +167,8 @@ pub(crate) fn apply_desired(sg: &mut [SGlyph], j: &JustificationOptions, scale_g g.sx *= g_des; g.dx *= g_des; g.kern_shift = (g.kern_shift - g.aki_shift) * g_des + g.aki_shift; + // The space Mojikumi took off before the glyph scales with it. + g.lead *= g_des; } f.width = g.adv - aki; f.scale = g_des; diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 21ab10c6e6..aae91be1ee 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -4,11 +4,13 @@ use super::breaking::{ roman_share, set_width, squeeze_em, tab_advance, word_width, }; use super::region::Region; -use super::vertical::{EM_CENTER, align_shift, compress_punctuation, glyph_em, punct_half, space_japanese_and_latin}; +use super::vertical::{ + EM_CENTER, MojikumiRules, align_shift, compress_punctuation, dot_quarter, glyph_em, halve_punctuation, punct_half, space_japanese_and_latin, +}; use super::{ Affine, BidiInfo, Burasagari, CharStyle, Composer, Ctx, EPS, Flex, Justify, Kinsoku, KinsokuShoriType, LeadingModel, LineFit, LineInfo, - ListMarker, Mojikumi, ParaStyle, Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, - fit_line, hyphen_glyph, is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, + ListMarker, ParaStyle, Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, + hyphen_glyph, is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, }; use crate::justify::is_format_control; use crate::shape::{keep_inseparable_pairs, keep_korean_words}; @@ -76,7 +78,7 @@ fn compose_para( // The same rule as the line loop below: an opening bracket starting a wrapped line gives up // the space before it. let start_credit = |i: usize| { - let flush = !rtl && para.mojikumi == Mojikumi::LineEndHalf; + let flush = !rtl && MojikumiRules::of(para.mojikumi).flush_start; sg.get(i).filter(|g| flush && g.lead <= 0.0).and_then(|g| punct_half(g, Punct::Opening)).unwrap_or(0.0) }; let mut sim = pen.clone(); @@ -195,7 +197,8 @@ struct ParagraphData<'a, 'text> { wakan: Vec, /// How much narrower a line ending with each glyph is set ([`line_end_trim`]), for measuring /// where lines break; empty when the paragraph's lines are measured at full width (Mojikumi - /// None, or right-to-left text). + /// None or YakumonoZenkaku, or right-to-left text with a set that adds no space between + /// Japanese and Latin text). line_end: Vec, flex: Vec, marker: usize, @@ -234,14 +237,26 @@ fn prepare_paragraph<'a, 'text>( if para.bunri_kinshi && para.kinsoku != Kinsoku::None { keep_inseparable_pairs(text, &mut sg); } - // Japanese composition: consecutive punctuation shares one half-em space. - let mut compressed = if para.mojikumi == Mojikumi::LineEndHalf { compress_punctuation(&mut sg) } else { vec![] }; + // Japanese composition (the paragraph's Mojikumi set): every punctuation mark set half width, + // or consecutive punctuation sharing one half-em space… + let rules = MojikumiRules::of(para.mojikumi); + let mut compressed = if rules.half { + halve_punctuation(&mut sg) + } else if rules.share { + compress_punctuation(&mut sg) + } else { + vec![] + }; // …and a quarter em between Japanese and Latin text. - let mut wakan = if para.mojikumi == Mojikumi::LineEndHalf { space_japanese_and_latin(&mut sg) } else { vec![] }; + let mut wakan = if rules.wakan { space_japanese_and_latin(&mut sg) } else { vec![] }; // Justification…: the glyphs at Desired word and letter spacing and glyph scaling, and how // far a justified line may move each one from it (Dynamic Text's Block on area type sets the // Desired word spacing to its word gap). let mut flex = apply_desired(&mut sg, &t.layout_justification(para), !cx.vertical); + // The Japanese–Latin space is part of the advance Desired glyph scaling scaled. + for (w, f) in wakan.iter_mut().zip(&flex) { + *w *= f.scale; + } // Threaded text: a first paragraph that continues from the frame before has its first // line, first-line indent and list marker there. let continued = pi == 0 && t.first_para_continues; @@ -277,11 +292,9 @@ fn prepare_paragraph<'a, 'text>( pen.pending += para.space_before; } // A line fits when it fits as it is set: with its last character narrowed by Mojikumi. - let line_end = if para.mojikumi == Mojikumi::LineEndHalf && !rtl { - (0..sg.len()).map(|k| line_end_trim(&sg, &compressed, &wakan, k)).collect() - } else { - vec![] - }; + let end_rules = rules.at_line_end(rtl); + let line_end = + if end_rules.trims_line_end() { (0..sg.len()).map(|k| line_end_trim(&sg, &compressed, &wakan, end_rules, k)).collect() } else { vec![] }; let composed = compose_para(cx, &sg, &flex, &line_end, para, pen, rtl, continued); // Hyphenation options: the Hyphenation Zone applies with the Single-line Composer, and the // Hyphen Limit counts the lines in a row that end with a hyphen. @@ -369,7 +382,7 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC // space before it goes), and the line has that much more room. At a paragraph's start // that is the first-line indent: JIS X 4051's principle (JLREQ 3.1.5, Figure 71 ①). if !*rtl - && para.mojikumi == Mojikumi::LineEndHalf + && MojikumiRules::of(para.mojikumi).flush_start && let Some(glyph) = sg.get_mut(*i) && glyph.lead <= 0.0 && let Some(half) = punct_half(glyph, Punct::Opening) @@ -536,14 +549,17 @@ fn run_paragraph_lines(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, t: &TextObject, mut true } -/// Mojikumi (Line-end Punctuation Half Width): how much narrower a line ending with glyph `k` of -/// `sg` is set. A closing bracket, comma or full stop ending the line is set half width, unless it -/// already lost that half to the punctuation after it (`compressed`), and no Japanese–Latin space -/// (`wakan`) is left after the line's last character. Never more than the glyph's advance, and 0 -/// for an advance or a space that is not finite. -pub(super) fn line_end_trim(sg: &[SGlyph], compressed: &[bool], wakan: &[f64], k: usize) -> f64 { +/// Mojikumi: how much narrower a line ending with glyph `k` of `sg` is set by the paragraph's set +/// `rules`. With [`MojikumiRules::half_end`], a closing bracket, comma or full stop ending the line +/// is set half width, and with [`MojikumiRules::dot_end`] a middle dot loses the quarter em after +/// it, unless the glyph already lost that space (`compressed`); no Japanese–Latin space (`wakan`) +/// is left after the line's last character. Never more than the glyph's advance, and 0 for an +/// advance or a space that is not finite. +pub(super) fn line_end_trim(sg: &[SGlyph], compressed: &[bool], wakan: &[f64], rules: MojikumiRules, k: usize) -> f64 { let Some(g) = sg.get(k) else { return 0.0 }; - let half = if compressed.get(k).copied().unwrap_or(false) { None } else { punct_half(g, Punct::Closing) }; + let lost = compressed.get(k).copied().unwrap_or(false); + let half = (!lost && rules.half_end).then(|| punct_half(g, Punct::Closing)).flatten(); + let half = half.or_else(|| (!lost && rules.dot_end).then(|| dot_quarter(g)).flatten()); let trim = half.unwrap_or(0.0) + wakan.get(k).copied().unwrap_or(0.0); if trim.is_finite() && g.adv.is_finite() { trim.min(g.adv).max(0.0) } else { 0.0 } } @@ -563,10 +579,11 @@ fn prepare_line_geometry(cx: &Ctx<'_>, t: &TextObject, paragraph: &ParagraphData trimmed -= 1; } let hyphen = (position.hyph && position.end > index).then(|| hyphen_glyph(&sg[position.end - 1])); + let rules = MojikumiRules::of(para.mojikumi).at_line_end(paragraph.rtl); let end_trim = trimmed .checked_sub(1) - .filter(|&k| k >= index && para.mojikumi == Mojikumi::LineEndHalf) - .map_or(0.0, |k| line_end_trim(sg, ¶graph.compressed, ¶graph.wakan, k)); + .filter(|&k| k >= index && rules.trims_line_end()) + .map_or(0.0, |k| line_end_trim(sg, ¶graph.compressed, ¶graph.wakan, rules, k)); let measured_width = set_width(sg, index, trimmed, ¶.tabs, position.ind_l) + hyphen.as_ref().map_or(0.0, |g| g.adv) - end_trim; let line_start = sg.get(index).map_or(paragraph.pr.start, |g| g.byte); let line_end = sg.get(position.end).map_or(paragraph.pr.end, |g| g.byte); diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs index aea53c124b..fc6b8f1f7e 100644 --- a/crates/text/src/layout/vertical.rs +++ b/crates/text/src/layout/vertical.rs @@ -1,6 +1,6 @@ use super::flow::flow; use super::region::Region; -use super::{Affine, Ctx, Punct, Range, Rect, SGlyph, Tcy, TextLayout, TextObject, VerticalAlign, continues_cluster, is_cjk, punct}; +use super::{Affine, Ctx, Mojikumi, Punct, Range, Rect, SGlyph, Tcy, TextLayout, TextObject, VerticalAlign, continues_cluster, is_cjk, punct}; /// System Layout on or Fractional Widths off: each character that takes space advances by a whole /// number of points, at least one, so small type does not collapse onto itself. A zero advance (a @@ -126,6 +126,84 @@ pub(super) fn punct_half(g: &SGlyph, kind: Punct) -> Option { ((g.face.advance(g.gid) - em).abs() <= em * 0.1).then_some(em * 0.5 * g.sx) } +/// A quarter em of `g`'s size when it is a full-width Japanese middle dot (・, its advance an em, +/// give or take a tenth): the space on each side of the dot that a Mojikumi set can take off. +pub(super) fn dot_quarter(g: &SGlyph) -> Option { + if g.ch != '・' || g.tcy.is_some() || g.proportional { + return None; + } + let em = g.face.units_per_em(); + ((g.face.advance(g.gid) - em).abs() <= em * 0.1).then_some(em * 0.25 * g.sx) +} + +/// What a paragraph's Mojikumi set does to its characters. The five predefined sets other than +/// Line-end Punctuation Half Width follow VectorCraft's own spacing rules, built on the help +/// page's one-line description of each set +/// (). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct MojikumiRules { + /// Consecutive punctuation shares one half-em space ([`compress_punctuation`]). + pub share: bool, + /// Every opening and closing bracket, comma and full stop is set half width, and a middle dot + /// loses the quarter em on each side of it ([`halve_punctuation`]). + pub half: bool, + /// An opening bracket starting a line is set flush with the line's start. + pub flush_start: bool, + /// A closing bracket, comma or full stop ending a line is set half width. + pub half_end: bool, + /// A middle dot ending a line loses the quarter em after it. + pub dot_end: bool, + /// A quarter em between Japanese and Latin letters or digits ([`space_japanese_and_latin`]), + /// taken off again at a line's end. + pub wakan: bool, +} + +impl MojikumiRules { + pub(super) fn of(set: Mojikumi) -> Self { + let none = Self::default(); + match set { + Mojikumi::None | Mojikumi::YakumonoZenkaku => none, + Mojikumi::LineEndHalf => Self { share: true, flush_start: true, half_end: true, wakan: true, ..none }, + Mojikumi::YakumonoHankaku => Self { half: true, wakan: true, ..none }, + Mojikumi::GyomatsuYakumonoHankaku => Self { flush_start: true, half_end: true, dot_end: true, wakan: true, ..none }, + Mojikumi::GyomatsuYakumonoZenkaku => Self { wakan: true, ..none }, + } + } + + /// The rules a line's end follows: a right-to-left line keeps its punctuation's width there + /// and only loses the space between Japanese and Latin text. + pub(super) fn at_line_end(self, rtl: bool) -> Self { + if rtl { Self { half_end: false, dot_end: false, ..self } } else { self } + } + + /// Whether a line ending at some character can be set narrower than its characters' advances. + pub(super) fn trims_line_end(&self) -> bool { + self.half_end || self.dot_end || self.wakan + } +} + +/// YakumonoHankaku: every full-width opening bracket loses the half-em space before it, every +/// closing bracket, comma and full stop the half-em space after it, and every middle dot a quarter +/// em on each side. Returns which glyphs lost the space after them (a line ending in one takes +/// nothing more off). +pub(super) fn halve_punctuation(sg: &mut [SGlyph]) -> Vec { + let mut lost_after = vec![false; sg.len()]; + for (g, lost) in sg.iter_mut().zip(lost_after.iter_mut()) { + if let Some(h) = punct_half(g, Punct::Closing) { + g.adv -= h; + *lost = true; + } else if let Some(h) = punct_half(g, Punct::Opening) { + g.adv -= h; + g.lead += h; + } else if let Some(q) = dot_quarter(g) { + g.adv -= 2.0 * q; + g.lead += q; + *lost = true; + } + } + lost_after +} + /// Mojikumi (JLREQ 3.1.4): consecutive punctuation shares one half-em space. A closing bracket, /// comma or full stop followed by punctuation loses the space after it; an opening bracket after /// another loses the space before it. Returns which glyphs lost the space after them (a line @@ -154,7 +232,7 @@ pub(super) fn compress_punctuation(sg: &mut [SGlyph]) -> Vec { } /// The space between Japanese and Latin letters or digits (JLREQ 3.2.2: a quarter em of the -/// Japanese characters' size), with Line-end Punctuation Half Width. +/// Japanese characters' size), with the Mojikumi sets that add it ([`MojikumiRules::wakan`]). const WAKAN_AKI: f64 = 0.25; /// A Japanese character for the space next to Latin text: kana and kanji (and full-width @@ -174,12 +252,12 @@ fn is_japanese_letter(c: char) -> bool { } impl TextLayout { - /// Whether Line-end Punctuation Half Width (Mojikumi) can set type laid out as this layout - /// differently from Mojikumi None: `text`, the type's plain text, or one of the layout's list - /// markers holds Japanese punctuation or a Japanese letter, the only characters it spaces. - /// When it holds neither, the type lays out the same with either setting. + /// Whether a Mojikumi set can set type laid out as this layout differently from Mojikumi + /// None: `text`, the type's plain text, or one of the layout's list markers holds Japanese + /// punctuation, a middle dot or a Japanese letter, the only characters the sets space. When it + /// holds none of them, the type lays out the same with any set. pub fn mojikumi_applies(&self, text: &str) -> bool { - let spaced = |c: char| punct(c).is_some() || is_japanese_letter(c); + let spaced = |c: char| punct(c).is_some() || c == '・' || is_japanese_letter(c); text.chars().any(spaced) || self.markers.iter().any(|m| m.text.chars().any(spaced)) } } diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 2d766ae571..8c53e29a04 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -453,7 +453,7 @@ pub fn vertical_punctuation_font(alternates: bool) -> Option> { pub const FULL_WIDTH_FAMILY: &str = "Fullwidthtest Sans"; /// The ideographs and Japanese punctuation [`full_width_font`] sets one em wide. -pub const FULL_WIDTH_CHARS: &str = "一二三四五六「」、。"; +pub const FULL_WIDTH_CHARS: &str = "一二三四五六「」、。・"; /// A test-only cmap over bundled Source Sans 3: [`FULL_WIDTH_CHARS`] use the one-em-wide glyph of /// U+2318, so Japanese composition is tested without OS fonts; Latin letters and the space keep @@ -1594,6 +1594,30 @@ pub fn twin_font(newer: bool) -> Option> { Some(builder.build()) } +/// The names of a [`named_copy`]: family, style, version string and PostScript name. +pub type CopyNames<'a> = (&'a str, &'a str, &'a str, &'a str); + +/// The bundled Source Sans 3 Regular or, `inter`, the bundled Inter Regular (glyphs of other +/// widths) under `names`, as an installed copy of a font: a font library can keep copies whose +/// names differ only in case or punctuation, or whose family and style are one but whose PostScript +/// names or versions differ. `None` when it can't be built. +pub fn named_copy(inter: bool, (family, style, version, postscript): CopyNames<'_>) -> Option> { + const SOURCE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + const INTER: &[u8] = include_bytes!("../../../assets/fonts/Inter-Regular.ttf"); + let font = skrifa::FontRef::new(if inter { INTER } else { SOURCE }).ok()?; + let full = format!("{family} {style}"); + let name = name_table(&[(1, family), (2, style), (4, &full), (5, version), (6, postscript)])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`numbered_font`]: styles numbered W3 and W6, and no Regular. pub const NUMBERED_FAMILY: &str = "Numtest Mincho"; diff --git a/crates/text/src/tests/versions.rs b/crates/text/src/tests/versions.rs index a721e435b1..ca28d7e4ef 100644 --- a/crates/text/src/tests/versions.rs +++ b/crates/text/src/tests/versions.rs @@ -41,3 +41,26 @@ fn type_naming_a_version_is_set_in_it() { assert!((newer - older).abs() > 50.0, "the two versions set the line differently: {newer} vs {older}"); assert_eq!(width(&db, Some(VERSIONS[1])), newer); } + +/// Every installed face a PostScript name answers to, ignoring case and punctuation: the face +/// `find_postscript` gives first, then the copies in other families and the versions, in load +/// order; none for a name no face has. +#[test] +fn every_face_of_a_postscript_name_is_found() { + use crate::test_fonts::named_copy; + let db = FontDb::with_font_dirs(vec![]); + for (inter, names) in [ + (true, ("Facetest Ink", "Bold", "Version 1.000", "FacetestInkBold")), + (false, ("Facetest-Ink", "Bold", "Version 1.000", "FacetestInk-Bold")), + (true, ("Facetest-Ink", "Bold", "Version 2.000", "FACETESTINK-BOLD")), + (false, ("Other Ink", "Bold", "Version 1.000", "OtherInk-Bold")), + ] { + assert_eq!(db.add_font(named_copy(inter, names).expect("the test font builds")), 1, "{names:?}"); + } + let names = |name: &str| db.postscript_faces(name).iter().map(|f| f.postscript_name()).collect::>(); + let first = db.find_postscript("FacetestInk-Bold").expect("a face").postscript_name(); + assert_eq!(first, "FacetestInkBold"); + assert_eq!(names("FacetestInk-Bold"), ["FacetestInkBold", "FacetestInk-Bold", "FACETESTINK-BOLD"]); + assert_eq!(names("OtherInk-Bold"), ["OtherInk-Bold"]); + assert!(names("NoSuchInk-Bold").is_empty()); +} diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index e76aee72f0..dd12804e91 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -1145,6 +1145,249 @@ fn mojikumi_line_end_half_width_counts_when_a_line_breaks() { } } +/// The predefined Mojikumi sets space punctuation by their own rules, horizontal and vertical: +/// YakumonoHankaku sets every bracket, comma and full stop half width and a middle dot a half em +/// (a quarter off each side, drawn a quarter em earlier); GyomatsuYakumonoHankaku keeps them full +/// width inside the line, sets an opening bracket starting the line flush and a closing mark ending +/// it half width, and takes the quarter em after a middle dot ending the line off; +/// GyomatsuYakumonoZenkaku and YakumonoZenkaku keep every mark full width. All but YakumonoZenkaku +/// put a quarter em between Japanese and Latin letters. Uses a test font whose ideographs and +/// punctuation are one em. +#[test] +fn mojikumi_predefined_sets_space_punctuation_by_their_rules() { + use crate::test_fonts::{FULL_WIDTH_FAMILY, full_width_font}; + use vectorcraft_doc::Mojikumi; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(full_width_font().expect("test font")); + let lay = |text: &str, m: Mojikumi, vertical_type: bool| { + let style = CharStyle { size: 20.0, font_family: FULL_WIDTH_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let mut t = TextObject::point(Point::ZERO, text, style); + t.xf = Affine::IDENTITY; + t.vertical = vertical_type; + t.para.mojikumi = m; + layout(&db, &t) + }; + let round = |v: Vec| v.into_iter().map(|x| (x * 100.0).round() / 100.0).collect::>(); + for vertical_type in [false, true] { + let adv = |text: &str, m| round(lay(text, m, vertical_type).glyphs.iter().map(|g| g.advance).collect()); + let at = |m: Mojikumi| format!("vertical {vertical_type} {m:?}"); + let middle = "一「二」三・四、五。"; + let cases = [ + (Mojikumi::None, [20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0]), + (Mojikumi::YakumonoHankaku, [20.0, 10.0, 20.0, 10.0, 20.0, 10.0, 20.0, 10.0, 20.0, 10.0]), + (Mojikumi::GyomatsuYakumonoHankaku, [20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 10.0]), + (Mojikumi::GyomatsuYakumonoZenkaku, [20.0; 10]), + (Mojikumi::YakumonoZenkaku, [20.0; 10]), + ]; + for (m, want) in cases { + assert_eq!(adv(middle, m), want, "{}", at(m)); + } + // Consecutive punctuation: YakumonoHankaku halves both marks, GyomatsuYakumonoHankaku + // neither (Line-end Punctuation Half Width only the first). + assert_eq!(adv("一」「二", Mojikumi::YakumonoHankaku), [20.0, 10.0, 10.0, 20.0], "vertical {vertical_type}"); + assert_eq!(adv("一」「二", Mojikumi::GyomatsuYakumonoHankaku), [20.0; 4], "vertical {vertical_type}"); + assert_eq!(adv("一」「二", Mojikumi::LineEndHalf), [20.0, 10.0, 20.0, 20.0], "vertical {vertical_type}"); + // A line's start and end: the opening bracket flush and the middle dot's outer quarter off. + assert_eq!(adv("「一・", Mojikumi::GyomatsuYakumonoHankaku), [10.0, 20.0, 15.0], "vertical {vertical_type}"); + assert_eq!(adv("「一・", Mojikumi::YakumonoHankaku), [10.0, 20.0, 10.0], "vertical {vertical_type}"); + assert_eq!(adv("「一・", Mojikumi::GyomatsuYakumonoZenkaku), [20.0; 3], "vertical {vertical_type}"); + // YakumonoHankaku draws an opening bracket half an em and a middle dot a quarter em + // earlier than its pen. + let along = |r: Rect| if vertical_type { r.y0 } else { r.x0 }; + let (on, off) = (lay("一「二", Mojikumi::YakumonoHankaku, vertical_type), lay("一「二", Mojikumi::None, vertical_type)); + let moved = along(off.glyphs[1].outline.bounding_box()) - along(on.glyphs[1].outline.bounding_box()); + assert!((moved - 10.0).abs() < 0.01, "vertical {vertical_type}: 「 drawn half an em earlier ({moved})"); + let (on, off) = (lay("一・二", Mojikumi::YakumonoHankaku, vertical_type), lay("一・二", Mojikumi::None, vertical_type)); + let moved = along(off.glyphs[1].outline.bounding_box()) - along(on.glyphs[1].outline.bounding_box()); + assert!((moved - 5.0).abs() < 0.01, "vertical {vertical_type}: ・ drawn a quarter em earlier ({moved})"); + // The space between Japanese and Latin letters. + let none = adv("一A二", Mojikumi::None); + for (m, extra) in [ + (Mojikumi::YakumonoHankaku, 5.0), + (Mojikumi::GyomatsuYakumonoHankaku, 5.0), + (Mojikumi::GyomatsuYakumonoZenkaku, 5.0), + (Mojikumi::YakumonoZenkaku, 0.0), + ] { + let got = adv("一A二", m); + assert!((got[0] - none[0] - extra).abs() < 0.01 && (got[1] - none[1] - extra).abs() < 0.01, "{}: {got:?} {none:?}", at(m)); + } + } +} + +/// The predefined Mojikumi sets measure a line as they set it, with both composers, horizontal +/// and vertical: in a measure of three and a half ems, a closing bracket that fits only half width +/// ends the line with YakumonoHankaku and GyomatsuYakumonoHankaku, and goes to the next line with +/// the character before it (kinsoku) with GyomatsuYakumonoZenkaku and YakumonoZenkaku. A middle dot +/// that fits only without the quarter em after it ends the line with GyomatsuYakumonoHankaku. +#[test] +fn mojikumi_predefined_sets_count_when_a_line_breaks() { + use crate::test_fonts::{FULL_WIDTH_FAMILY, full_width_font}; + use vectorcraft_doc::{Burasagari, Composer, Kinsoku, KinsokuShoriType, Mojikumi}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(full_width_font().expect("test font")); + let lay = |text: &str, m: Mojikumi, composer: Composer, vertical_type: bool, measure: f64| { + let style = CharStyle { size: 20.0, font_family: FULL_WIDTH_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let mut t = TextObject::point(Point::ZERO, text, style); + t.xf = Affine::IDENTITY; + t.vertical = vertical_type; + t.para.mojikumi = m; + t.para.composer = composer; + t.para.burasagari = Burasagari::None; + t.para.kinsoku = Kinsoku::Hard; + t.para.kinsoku_type = KinsokuShoriType::PushOutOnly; + let frame = if vertical_type { Rect::new(0.0, 0.0, 200.0, measure) } else { Rect::new(0.0, 0.0, measure, 200.0) }; + t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame.to_path(0.1)) }; + layout(&db, &t) + }; + let first = |l: &TextLayout, text: &str| l.lines.first().map(|line| text[line.start..line.end].to_string()).unwrap_or_default(); + let widest = |l: &TextLayout| { + l.lines.iter().map(|line| l.glyphs[line.glyph_start..line.glyph_end].iter().map(|g| g.advance).sum::()).fold(0.0, f64::max) + }; + for vertical_type in [false, true] { + for composer in [Composer::SingleLine, Composer::EveryLine] { + let text = "一二三」四五六"; + for (m, line) in [ + (Mojikumi::YakumonoHankaku, "一二三」"), + (Mojikumi::GyomatsuYakumonoHankaku, "一二三」"), + (Mojikumi::GyomatsuYakumonoZenkaku, "一二"), + (Mojikumi::YakumonoZenkaku, "一二"), + ] { + let l = lay(text, m, composer, vertical_type, 70.0); + assert_eq!(first(&l, text), line, "vertical {vertical_type} {composer:?} {m:?}"); + assert!(widest(&l) <= 70.0 + 1e-9, "vertical {vertical_type} {composer:?} {m:?}: {}", widest(&l)); + } + let text = "一二三・四五六"; + for (m, line) in [(Mojikumi::GyomatsuYakumonoHankaku, "一二三・"), (Mojikumi::GyomatsuYakumonoZenkaku, "一二"), (Mojikumi::None, "一二")] + { + let l = lay(text, m, composer, vertical_type, 76.0); + assert_eq!(first(&l, text), line, "vertical {vertical_type} {composer:?} {m:?}"); + assert!(widest(&l) <= 76.0 + 1e-9, "vertical {vertical_type} {composer:?} {m:?}: {}", widest(&l)); + } + } + } +} + +/// A right-to-left paragraph measures its lines at full width with every Mojikumi set, and draws +/// them as it measures them: a closing bracket ending a line keeps its full em, with both composers. +#[test] +fn mojikumi_right_to_left_lines_are_drawn_as_measured() { + use crate::test_fonts::{FULL_WIDTH_FAMILY, full_width_font}; + use vectorcraft_doc::{Burasagari, Composer, Kinsoku, KinsokuShoriType, Mojikumi, ParaDirection}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(full_width_font().expect("test font")); + let lay = |text: &str, m: Mojikumi, composer: Composer, measure: f64| { + let style = CharStyle { size: 20.0, font_family: FULL_WIDTH_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let mut t = TextObject::point(Point::ZERO, text, style); + t.xf = Affine::IDENTITY; + t.para.direction = Some(ParaDirection::RightToLeft); + t.para.mojikumi = m; + t.para.composer = composer; + t.para.burasagari = Burasagari::None; + t.para.kinsoku = Kinsoku::Hard; + t.para.kinsoku_type = KinsokuShoriType::PushOutOnly; + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, measure, 200.0).to_path(0.1)) }; + layout(&db, &t) + }; + let text = "一二三」四五六"; + for composer in [Composer::SingleLine, Composer::EveryLine] { + for m in [Mojikumi::LineEndHalf, Mojikumi::GyomatsuYakumonoHankaku] { + let at = format!("{composer:?} {m:?}"); + // Three and a half ems: the bracket does not fit at full width, so kinsoku takes 三 on. + let narrow = lay(text, m, composer, 70.0); + let first = narrow.lines.first().map(|line| &text[line.start..line.end]); + assert_eq!(first, Some("一二"), "{at}"); + // Four and a quarter ems: the line is measured four ems wide and drawn so. + let l = lay(text, m, composer, 85.0); + let first = l.lines.first().map(|line| &text[line.start..line.end]); + assert_eq!(first, Some("一二三」"), "{at}"); + let bracket = text.find('」').and_then(|byte| l.glyphs.iter().find(|g| g.byte == byte)).map(|g| g.advance); + assert_eq!(bracket.map(|a| (a * 100.0).round() / 100.0), Some(20.0), "{at}"); + } + } +} + +/// A right-to-left line ending between a Japanese and a Latin character does not keep the quarter +/// em the set adds there: in three ems, 一二三 fits before Latin text, measured and drawn three ems +/// wide, with both composers and every set that adds the space. +#[test] +fn mojikumi_right_to_left_lines_end_without_the_japanese_latin_space() { + use crate::test_fonts::{FULL_WIDTH_FAMILY, full_width_font}; + use vectorcraft_doc::{Composer, Mojikumi, ParaDirection}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(full_width_font().expect("test font")); + let text = "一二三AB"; + for composer in [Composer::SingleLine, Composer::EveryLine] { + for m in [Mojikumi::LineEndHalf, Mojikumi::YakumonoHankaku, Mojikumi::GyomatsuYakumonoHankaku, Mojikumi::GyomatsuYakumonoZenkaku] { + let style = CharStyle { size: 20.0, font_family: FULL_WIDTH_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let mut t = TextObject::point(Point::ZERO, text, style); + t.xf = Affine::IDENTITY; + t.para.direction = Some(ParaDirection::RightToLeft); + t.para.mojikumi = m; + t.para.composer = composer; + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, 60.0, 200.0).to_path(0.1)) }; + let l = layout(&db, &t); + let line = l.lines.first(); + assert_eq!(line.map(|line| &text[line.start..line.end]), Some("一二三"), "{composer:?} {m:?}"); + let drawn = line.map(|line| l.glyphs[line.glyph_start..line.glyph_end].iter().map(|g| g.advance).sum::()); + assert_eq!(drawn.map(|w| (w * 100.0).round() / 100.0), Some(60.0), "{composer:?} {m:?}"); + } + } +} + +/// With a Desired glyph scaling other than 100%, the space a Mojikumi set takes off before an +/// opening bracket or a middle dot scales with the glyph: the glyph is drawn that much earlier, +/// with YakumonoHankaku and with Line-end Punctuation Half Width's consecutive brackets. +#[test] +fn mojikumi_space_taken_off_scales_with_desired_glyph_scaling() { + use crate::test_fonts::{FULL_WIDTH_FAMILY, full_width_font}; + use vectorcraft_doc::Mojikumi; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(full_width_font().expect("test font")); + let lay = |text: &str, m: Mojikumi| { + let style = CharStyle { size: 20.0, font_family: FULL_WIDTH_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let mut t = TextObject::point(Point::ZERO, text, style); + t.xf = Affine::IDENTITY; + t.para.mojikumi = m; + t.para.justification.glyph_scaling = [50.0, 50.0, 100.0]; + layout(&db, &t) + }; + for (text, m, k, want) in + [("一「二", Mojikumi::YakumonoHankaku, 1, 5.0), ("一・二", Mojikumi::YakumonoHankaku, 1, 2.5), ("一「「二", Mojikumi::LineEndHalf, 2, 5.0)] + { + let (on, off) = (lay(text, m), lay(text, Mojikumi::None)); + let pen = |l: &TextLayout| l.glyphs[..k].iter().map(|g| g.advance).sum::(); + let drawn = |l: &TextLayout| l.glyphs[k].outline.bounding_box().x0 - pen(l); + let moved = drawn(&off) - drawn(&on); + assert!((moved - want).abs() < 0.01, "{text} {m:?}: drawn {moved} earlier, want {want}"); + } +} + +/// With a Desired glyph scaling other than 100%, a line ending before Latin text is measured +/// without the scaled quarter em the set added there, not an unscaled one: at 50%, 一二三 is 30 pt +/// wide and does not fit 29 pt, with both composers and every set that adds the space. +#[test] +fn mojikumi_line_end_japanese_latin_space_scales_with_desired_glyph_scaling() { + use crate::test_fonts::{FULL_WIDTH_FAMILY, full_width_font}; + use vectorcraft_doc::{Composer, Mojikumi}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(full_width_font().expect("test font")); + let text = "一二三AB"; + for composer in [Composer::SingleLine, Composer::EveryLine] { + for m in [Mojikumi::LineEndHalf, Mojikumi::YakumonoHankaku, Mojikumi::GyomatsuYakumonoHankaku, Mojikumi::GyomatsuYakumonoZenkaku] { + let style = CharStyle { size: 20.0, font_family: FULL_WIDTH_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let mut t = TextObject::point(Point::ZERO, text, style); + t.xf = Affine::IDENTITY; + t.para.mojikumi = m; + t.para.composer = composer; + t.para.justification.glyph_scaling = [50.0, 50.0, 100.0]; + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, 29.0, 200.0).to_path(0.1)) }; + let l = layout(&db, &t); + let first = l.lines.first().map(|line| &text[line.start..line.end]); + assert_eq!(first, Some("一二"), "{composer:?} {m:?}"); + } + } +} + /// Mojikumi: in a frame that is narrow at the top, and in a frame a wrap object narrows at the top, /// a line's first word is measured as the line sets it. A word ending with a closing bracket that /// fits the narrow lines only with the bracket half width, and an opening bracket that fits them diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index ee7440dde6..cd72f1dd40 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -368,7 +368,7 @@ impl SmartPenTool { } Target::Close { id, si, first, mut anchor } => { let out = Self::handle_to(cx, first, ev.pos, first, shift, false); - let act = close_drag(id, Some(si), first - (out - first), alt, anchor.as_mut()); + let act = close_drag(id, Some(si), None, first - (out - first), alt, anchor.as_mut()); pr.what = Target::Close { id, si, first, anchor }; ("", act) } @@ -573,12 +573,15 @@ impl Tool for SmartPenTool { fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = vec![]; - if cx.pen_rubber_band - && self.press.is_none() + // The rubber band preference hides only the preview segment; Measurement Labels decides the readout. + if self.press.is_none() && let (Some((id, _, sp)), Some(h)) = (self.active(cx), self.hover) - && let Some(path) = self.rubber_band(sp, h) { - o.push(Overlay::Path { path, color: cx.doc.layer_color(id), width: 1.0, dashed: false }); + if cx.pen_rubber_band + && let Some(path) = self.rubber_band(sp, h) + { + o.push(Overlay::Path { path, color: cx.doc.layer_color(id), width: 1.0, dashed: false }); + } if let Some(last) = sp.anchors.last().map(|a| a.p) && cx.measurement_labels && last.distance(h) > 1e-9 diff --git a/crates/tools/src/addons/smart_pen/tests.rs b/crates/tools/src/addons/smart_pen/tests.rs index a7f792c22f..8bcc907f9d 100644 --- a/crates/tools/src/addons/smart_pen/tests.rs +++ b/crates/tools/src/addons/smart_pen/tests.rs @@ -315,6 +315,35 @@ fn the_rubber_band_shows_the_next_segment_and_ending_the_path() { assert!(t.overlays(&cx).is_empty()); } +/// With Enable Rubber Band for the Pen off, the preview segment is hidden but Measurement Labels +/// still shows the readout from the last anchor to the pointer. +#[test] +fn the_measurement_label_shows_with_the_rubber_band_off() { + let (d, _, s) = doc(line()); + let p = paint(); + let on = plain(&d, &s, &p); + let off = ToolContext { pen_rubber_band: false, ..plain(&d, &s, &p) }; + let (from, to) = (Point::new(200.0, 100.0), Point::new(300.0, 160.0)); + let measure = + |o: &[Overlay]| o.iter().filter_map(|o| if let Overlay::Measure { text, .. } = o { Some(text.clone()) } else { None }).collect::>(); + let band = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Path { .. })); + let mut t = drawing(&off, from); + t.pointer(&off, &ev(PointerKind::Move, to.x, to.y, NO)); + let o = t.overlays(&off); + assert_eq!(measure(&o), vec![off.segment_measure_label(from, to)], "{o:?}"); + assert!(!band(&o), "{o:?}"); + let o = t.overlays(&on); + assert_eq!(measure(&o), vec![on.segment_measure_label(from, to)], "{o:?}"); + assert!(band(&o), "{o:?}"); + for rubber in [true, false] { + let quiet = ToolContext { pen_rubber_band: rubber, measurement_labels: false, ..plain(&d, &s, &p) }; + assert!(measure(&t.overlays(&quiet)).is_empty()); + } + // Hovering exactly on the last anchor measures no segment. + t.pointer(&off, &ev(PointerKind::Move, from.x, from.y, NO)); + assert!(measure(&t.overlays(&off)).is_empty()); +} + #[test] fn an_alt_drag_away_from_paths_selects_the_points_inside_a_marquee() { let (d, id, s) = doc(SubPath::polyline(&[Point::new(100.0, 100.0), Point::new(200.0, 100.0), Point::new(300.0, 100.0)], false)); 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..02087d997a 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())] } @@ -707,38 +718,44 @@ impl Tool for CurvatureTool { } fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = self.snap.guides().to_vec(); - let band = cx.curvature_rubber_band && self.drag.is_none(); + // The rubber band preference hides only the preview curve; Measurement Labels decides the readout. + let idle = self.drag.is_none(); + let band = cx.curvature_rubber_band; let mut bp = BezPath::new(); if self.active(cx).is_none() { // The curve on from the current end of a selected path: its last segment and the next. - if band + if idle && let (Some(e), Some(h)) = (current_end(cx), self.hover) && let Some(sp) = subpath(cx, e.id, e.si) { - let n = sp.anchors.len(); - let near = if e.start { - sp.anchors.iter().take(2).rev().map(Anchor::reversed).collect() - } else { - sp.anchors.iter().skip(n.saturating_sub(2)).copied().collect() - }; - let mut tail = SubPath::new(near, false); - curvature_extend(&mut tail, false, h, self.how(&e), false); - tail.to_bezpath_into(&mut bp); - o.push(Overlay::Path { path: bp, color: FEEDBACK, width: 1.0, dashed: false }); + if band { + let n = sp.anchors.len(); + let near = if e.start { + sp.anchors.iter().take(2).rev().map(Anchor::reversed).collect() + } else { + sp.anchors.iter().skip(n.saturating_sub(2)).copied().collect() + }; + let mut tail = SubPath::new(near, false); + curvature_extend(&mut tail, false, h, self.how(&e), false); + tail.to_bezpath_into(&mut bp); + o.push(Overlay::Path { path: bp, color: FEEDBACK, width: 1.0, dashed: false }); + } if cx.measurement_labels && e.p.distance(h) > 1e-9 { o.push(Overlay::Measure { p: h + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: cx.segment_measure_label(e.p, h) }); } } return o; } - if band + if idle && !self.closed && let Some(h) = self.hover { - let mut pts = self.pts.clone(); - pts.push((h, false)); - curvature_spline(&pts, false).to_bezpath_into(&mut bp); - o.push(Overlay::Path { path: bp, color: FEEDBACK, width: 1.0, dashed: false }); + if band { + let mut pts = self.pts.clone(); + pts.push((h, false)); + curvature_spline(&pts, false).to_bezpath_into(&mut bp); + o.push(Overlay::Path { path: bp, color: FEEDBACK, width: 1.0, dashed: false }); + } if let Some((from, _)) = self.pts.last() && cx.measurement_labels && from.distance(h) > 1e-9 @@ -762,15 +779,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..50ef2281d1 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); @@ -487,3 +539,51 @@ fn clicks_go_on_from_a_current_end_and_the_other_end_closes() { 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 Enable Rubber Band for the Curvature tool off, the preview curve is hidden but +/// Measurement Labels still shows the readout, both while drawing a path and going on from the +/// current end of a selected one. +#[test] +fn the_measurement_label_shows_with_the_rubber_band_off() { + let p = paint(); + let measure = + |o: &[Overlay]| o.iter().filter_map(|o| if let Overlay::Measure { text, .. } = o { Some(text.clone()) } else { None }).collect::>(); + let band = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Path { .. })); + let to = pt(650.0, 60.0); + // Going on from the current end of a selected path. + let (d, id) = doc_with(wave()); + let s = selected(id, Some(4)); + let on = quiet(&d, &s, &p); + let off = ToolContext { curvature_rubber_band: false, ..quiet(&d, &s, &p) }; + let mut t = CurvatureTool::default(); + t.pointer(&off, &PointerEvent::new(PointerKind::Move, to.x, to.y)); + let from = pt(450.0, 60.0); + let o = t.overlays(&off); + assert_eq!(measure(&o), vec![off.segment_measure_label(from, to)], "{o:?}"); + assert!(!band(&o), "{o:?}"); + let o = t.overlays(&on); + assert_eq!(measure(&o), vec![on.segment_measure_label(from, to)], "{o:?}"); + assert!(band(&o), "{o:?}"); + // A path being drawn. + let (d, id) = doc_with(SubPath::polyline(&[pt(100.0, 100.0), pt(200.0, 150.0)], false)); + let s = selected(id, None); + let on = quiet(&d, &s, &p); + let off = ToolContext { curvature_rubber_band: false, ..quiet(&d, &s, &p) }; + let mut t = CurvatureTool { id: Some(id), pts: vec![(pt(100.0, 100.0), false), (pt(200.0, 150.0), false)], ..CurvatureTool::default() }; + assert!(t.active(&off).is_some()); + t.pointer(&off, &PointerEvent::new(PointerKind::Move, to.x, to.y)); + let from = pt(200.0, 150.0); + let o = t.overlays(&off); + assert_eq!(measure(&o), vec![off.segment_measure_label(from, to)], "{o:?}"); + assert!(!band(&o), "{o:?}"); + let o = t.overlays(&on); + assert_eq!(measure(&o), vec![on.segment_measure_label(from, to)], "{o:?}"); + assert!(band(&o), "{o:?}"); + for rubber in [true, false] { + let unlabeled = ToolContext { curvature_rubber_band: rubber, measurement_labels: false, ..quiet(&d, &s, &p) }; + assert!(measure(&t.overlays(&unlabeled)).is_empty()); + } + // Hovering exactly on the last point measures no segment. + t.pointer(&off, &PointerEvent::new(PointerKind::Move, from.x, from.y)); + assert!(measure(&t.overlays(&off)).is_empty()); +} diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index 31aabfb38f..a0ab57ae87 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -7,7 +7,8 @@ //! incoming handle mirrors the pointer (a click leaves it retracted and the anchor a corner, so the //! closing segment comes in straight). Its outgoing handle stays where it is on a corner, so the first segment keeps its //! shape, and on a smooth anchor turns to stay in line at its own length; Alt makes the anchor a -//! corner, leaving the outgoing handle where it was when Alt went down. Clicking the +//! corner, leaving the outgoing handle where it was when Alt went down; Space held moves the +//! anchor, handles and all. Clicking the //! last one retracts its outgoing handle, so the next segment leaves it as a corner; dragging from //! it pulls a new one out on its own. //! Alt held over a handle end, an anchor or a segment of a selected path (the one being drawn too) @@ -76,13 +77,15 @@ const DRAG_THRESHOLD: f64 = 3.0; /// An anchor being placed, as the press decided: where it is, the path it goes on (none: the /// first anchor of a new path) and whether it closes that path (the press was on its first /// anchor). The drag only shapes its handles, whatever the path looks like meanwhile: a closing -/// preview leaves the path closed, so no longer one the pen draws on. +/// preview leaves the path closed, so no longer one the pen draws on. `moved`: Space held has +/// moved the anchor from where the press found it. #[derive(Clone, Copy)] struct Place { at: Point, path: Option, subpath: Option, closing: bool, + moved: bool, } /// The open path the pen is extending: the single selected open path, or the single open path of a @@ -329,7 +332,7 @@ impl Tool for PenTool { params["subpaths"] = json!([si, other_si]); return vec![Action::Exec("path.join".into(), params)]; } - self.drag = Some(Place { at: p, path: Some(id), subpath: Some(si), closing: false }); + self.drag = Some(Place { at: p, path: Some(id), subpath: Some(si), closing: false, moved: false }); self.in_h = p; let params = json!({"id": id.0, "x": p.x, "y": p.y, "subpath": si}); return vec![Action::Begin("Pen".into()), Action::Preview("path.appendAnchor".into(), params)]; @@ -366,7 +369,7 @@ impl Tool for PenTool { return vec![act]; } (self.drawing, self.path, self.subpath) = (true, None, None); - self.drag = Some(Place { at: p, path: None, subpath: None, closing: false }); + self.drag = Some(Place { at: p, path: None, subpath: None, closing: false, moved: false }); vec![Action::Begin("Pen".into()), Action::Preview("path.create".into(), json!({"anchors": [{"x": p.x, "y": p.y}]}))] } PointerKind::Drag => { @@ -390,13 +393,19 @@ impl Tool for PenTool { } return vec![set_out_handle(id, si, ai, h)]; } - let Some(Place { at: mut a, path, subpath, closing }) = self.drag else { return vec![] }; - // Space held moves the anchor being placed, handles and all. - if ev.mods.space && !closing { + let Some(Place { at: mut a, path, subpath, closing, mut moved }) = self.drag else { return vec![] }; + // Space held moves the anchor being placed, handles and all; while closing, the + // first anchor, with the outgoing handle a closing drag keeps. + if ev.mods.space { let d = ev.pos - self.last; a += d; self.in_h += d; - self.drag = Some(Place { at: a, path, subpath, closing }); + if closing && let Some((anchor, out)) = &mut self.first { + anchor.translate(d); + *out += d; + } + moved |= d != Vec2::ZERO; + self.drag = Some(Place { at: a, path, subpath, closing, moved }); } self.last = ev.pos; let mut out_h = ev.pos; @@ -413,7 +422,7 @@ impl Tool for PenTool { )]; }; if closing { - return vec![close_drag(id, subpath, a - (out_h - a), alt, self.first.as_mut())]; + return vec![close_drag(id, subpath, moved.then_some(a), a - (out_h - a), alt, self.first.as_mut())]; } // Alt pressed mid-drag keeps the curve already shaped into the anchor: only the // outgoing handle follows. Held from the start, the incoming handle stays retracted. @@ -486,19 +495,21 @@ impl Tool for PenTool { return t.overlays(cx); } let mut o = vec![]; - if cx.pen_rubber_band - && self.drag.is_none() + // The rubber band preference hides only the preview segment; Measurement Labels decides the readout. + if self.drag.is_none() && self.handle.is_none() && let (Some((id, _, _, last, out)), Some(h)) = (self.active(cx), self.hover) { - let mut bp = BezPath::new(); - bp.move_to(last); - if out.distance(last) > 1e-9 { - bp.quad_to(out, h); - } else { - bp.line_to(h); + if cx.pen_rubber_band { + let mut bp = BezPath::new(); + bp.move_to(last); + if out.distance(last) > 1e-9 { + bp.quad_to(out, h); + } else { + bp.line_to(h); + } + o.push(Overlay::Path { path: bp, color: cx.doc.layer_color(id), width: 1.0, dashed: false }); } - o.push(Overlay::Path { path: bp, color: cx.doc.layer_color(id), width: 1.0, dashed: false }); if cx.measurement_labels && last.distance(h) > 1e-9 { o.push(Overlay::Measure { p: h + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: cx.segment_measure_label(last, h) }); } @@ -583,7 +594,7 @@ impl PenTool { /// anchor a corner with its incoming handle retracted until a drag pulls it out, as a click on /// the last anchor retracts its outgoing one ([`set_out_handle`]). fn begin_close(&mut self, cx: &ToolContext, id: NodeId, si: usize, at: Point) -> Vec { - self.drag = Some(Place { at, path: Some(id), subpath: Some(si), closing: true }); + self.drag = Some(Place { at, path: Some(id), subpath: Some(si), closing: true, moved: false }); self.first = first_anchor(cx, id, si).map(|a| (a, a.h_out)); let params = json!({"id": id.0, "subpath": si, "in": [at.x, at.y], "independent": true}); vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), params)] @@ -609,12 +620,23 @@ pub(crate) fn first_anchor(cx: &ToolContext, id: NodeId, si: usize) -> Option, in_h: Point, alt: bool, first: Option<&mut (Anchor, Point)>) -> Action { +/// The preview of a closing drag that puts the first anchor's incoming handle at `in_h`, the anchor +/// first moved to `at` when given (Space held). `first` holds that anchor as it was when the press +/// began closing the path (moved with it), and its outgoing handle as the drag last left it: a +/// smooth anchor turns that handle to stay in line, and Alt (`alt`), which makes the anchor a +/// corner, keeps it there. +pub(crate) fn close_drag( + id: NodeId, + subpath: Option, + at: Option, + in_h: Point, + alt: bool, + first: Option<&mut (Anchor, Point)>, +) -> Action { let mut params = json!({"id": id.0, "in": [in_h.x, in_h.y], "independent": alt}); + if let Some(at) = at { + params["at"] = json!([at.x, at.y]); + } if let Some((anchor, out)) = first { if alt { params["out"] = json!([out.x, out.y]); diff --git a/crates/tools/src/pen/tests.rs b/crates/tools/src/pen/tests.rs index 984f34646a..32c91318e6 100644 --- a/crates/tools/src/pen/tests.rs +++ b/crates/tools/src/pen/tests.rs @@ -628,6 +628,43 @@ fn alt_mid_close_keeps_the_turned_outgoing_handle() { assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 130.0, 200.0)), vec![Action::Commit]); } +/// Space held during a closing drag moves the first anchor, handles and all, by as far as the +/// pointer moves; released, the drag shapes the handles round the anchor's new place. +#[test] +fn space_moves_the_closing_anchor() { + use vectorcraft_geom::{Anchor, SubPath}; + let anchors = vec![Anchor::smooth(Point::new(100.0, 300.0), Point::new(150.0, 300.0)), Anchor::corner(Point::new(200.0, 200.0))]; + let (mut d, id, s) = drawing(SubPath { anchors, closed: false }); + let p = paint(); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + assert_eq!(t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 100.0, 300.0)), close_press(id, Point::new(100.0, 300.0))); + d.node_mut(id).unwrap().path_data_mut().unwrap().subpaths[0].closed = true; + let c = cx(&d, &s, &p); + let close = |v: serde_json::Value| vec![Action::Preview("path.close".into(), v)]; + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 100.0, 200.0)), + close(json!({"id": id.0, "in": [100.0, 400.0], "independent": false, "subpath": 0})) + ); + let space = Mods { space: true, ..Mods::default() }; + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 180.0).with_mods(space)), + close(json!({"id": id.0, "at": [130.0, 280.0], "in": [130.0, 380.0], "independent": false, "subpath": 0})), + "moved, handles and all" + ); + // Space released: the drag shapes the handles round the anchor's new place. + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 230.0)), + close(json!({"id": id.0, "at": [130.0, 280.0], "in": [130.0, 330.0], "independent": false, "subpath": 0})) + ); + // Alt keeps the outgoing handle where the drag had turned it, moved with the anchor. + let alt = Mods { alt: true, ..Mods::default() }; + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 160.0, 230.0).with_mods(alt)), + close(json!({"id": id.0, "at": [130.0, 280.0], "in": [100.0, 330.0], "out": [130.0, 230.0], "independent": true, "subpath": 0})) + ); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 160.0, 230.0)), vec![Action::Commit]); +} + #[test] fn a_one_anchor_path_does_not_close_on_itself() { let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(10.0, 300.0)], false)); @@ -736,6 +773,48 @@ fn anchors_snap_to_smart_guides() { assert_eq!(a[1], Action::Preview("path.create".into(), json!({"anchors": [{"x": 100.0, "y": 100.0}]}))); } +/// With Enable Rubber Band off, the preview segment is hidden but Measurement Labels still shows +/// the D / Angle / dX / dY readout at the snapped point before the next click. +#[test] +fn measurement_label_shows_with_the_rubber_band_off() { + let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(10.0, 300.0), Point::new(60.0, 300.0)], false)); + let p = paint(); + let on = cx(&d, &s, &p); + let off = ToolContext { pen_rubber_band: false, ..cx(&d, &s, &p) }; + let from = Point::new(60.0, 300.0); + let to = Point::new(150.0, 318.0); + let measure = + |o: &[Overlay]| o.iter().filter_map(|o| if let Overlay::Measure { text, .. } = o { Some(text.clone()) } else { None }).collect::>(); + let preview = |o: &[Overlay]| { + o.iter().any(|o| matches!(o, Overlay::Path { path, .. } if path.elements().first().and_then(|e| e.end_point()) == Some(from))) + }; + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&off, &PointerEvent::new(PointerKind::Move, 152.0, 318.0)); + let o = t.overlays(&off); + assert_eq!(measure(&o), vec![off.segment_measure_label(from, to)], "{o:?}"); + assert!(!preview(&o), "{o:?}"); + // The rubber band on still shows both. + let o = t.overlays(&on); + assert_eq!(measure(&o), vec![on.segment_measure_label(from, to)], "{o:?}"); + assert!(preview(&o), "{o:?}"); + // Measurement Labels off shows no readout either way. + for band in [true, false] { + let quiet = ToolContext { pen_rubber_band: band, measurement_labels: false, ..cx(&d, &s, &p) }; + assert!(measure(&t.overlays(&quiet)).is_empty()); + } + // The click places the same anchor as with the rubber band on. + let a = click(&mut t, &off, 152.0, 318.0, Mods::default()); + assert_eq!(a[1], Action::Preview("path.appendAnchor".into(), json!({"id": id.0, "x": 150.0, "y": 318.0, "subpath": 0}))); + // Hovering exactly on the last anchor measures no segment. + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&off, &PointerEvent::new(PointerKind::Move, 60.0, 300.0)); + assert!(measure(&t.overlays(&off)).is_empty()); + // With no path being drawn there is nothing to measure from. + let mut t = PenTool::default(); + t.pointer(&off, &PointerEvent::new(PointerKind::Move, 152.0, 318.0)); + assert!(measure(&t.overlays(&off)).is_empty()); +} + #[test] fn alt_over_a_shown_handle_or_an_anchor_converts() { // The middle anchor is smooth: handles at (150, 100) and (250, 100) round (200, 100). diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 17bf7eeaef..05b81ae049 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -239,7 +239,8 @@ pub(crate) struct MoveSnap { copy_targets: Option, copy_points: Option, /// With Smart Guides on, the ruler guides View › Snap to Point still pulls the grabbed point - /// onto (#1534), and lines the bounds up with (#5746); `points` holds them with Smart Guides off. + /// onto (#1534), and lines the bounds up with (#5746), within the Snapping Tolerance as drawing + /// does; `points` holds them with Smart Guides off. rulers: Option, } @@ -303,7 +304,7 @@ impl MoveSnap { // axis without one that Smart Guides left free, the bounds line up with the ruler guides // (#5746), alongside the Smart Guides. if let Some(t) = &self.rulers { - let (adj, ov, held) = t.snap_moved_to_rulers(start + d, self.bounds.map(|b| b + d), cx.tol(cx.snap_tolerance), taken); + let (adj, ov, held) = t.snap_moved_to_rulers(start + d, self.bounds.map(|b| b + d), cx.snap_tol(), taken); if adj != Vec2::ZERO { d += adj; if held { @@ -373,7 +374,7 @@ impl MoveSnap { } } if let Some(t) = &self.rulers { - let (q, ov) = t.snap_point_along(start + d, u, cx.tol(cx.snap_tolerance)); + let (q, ov) = t.snap_point_along(start + d, u, cx.snap_tol()); if q != start + d { d = q - start; guides = ov; @@ -382,7 +383,7 @@ impl MoveSnap { { // Nothing else lined up: the bounds slide along the line onto a ruler guide, as // they do without Shift (#4312). - let (adj, ov) = t.snap_moved_along_to_rulers(start + d, b + d, u, cx.tol(cx.snap_tolerance)); + let (adj, ov) = t.snap_moved_along_to_rulers(start + d, b + d, u, cx.snap_tol()); d += adj; guides = ov; } @@ -1382,9 +1383,7 @@ pub(crate) fn release_guide_at(cx: &ToolContext, p: Point, m: Mods) -> Option Cursor { - let steps = if angle.is_finite() { (angle / 45.0).round() as i64 } else { 0 }; - let h = Handle::ALL.get((h as i64 - steps).rem_euclid(8) as usize).copied().unwrap_or(h); - match h { + match screen_handle(h, angle) { Handle::Top | Handle::Bottom => Cursor::ResizeV, Handle::Left | Handle::Right => Cursor::ResizeH, Handle::TopLeft | Handle::BottomRight => Cursor::ResizeNwSe, @@ -1392,6 +1391,13 @@ pub(crate) fn handle_cursor(h: Handle, angle: f64) -> Cursor { } } +/// The handle of an upright box that sits where handle `h` of a box turned by `angle` +/// (counter-clockwise degrees) appears, in 45° steps. +pub(crate) fn screen_handle(h: Handle, angle: f64) -> Handle { + let steps = if angle.is_finite() { (angle / 45.0).round() as i64 } else { 0 }; + Handle::ALL.get((h as i64 - steps).rem_euclid(8) as usize).copied().unwrap_or(h) +} + #[cfg(test)] mod tests; diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 659e50a6a5..c41056b7aa 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -751,7 +751,7 @@ fn escape_cancels_a_move_or_an_alt_drag_copy() { } /// #1534: with Smart Guides on (the default), the point a selection is dragged by still snaps -/// to a ruler guide within the Snap to Point distance; not with Snap to Point off. +/// to a ruler guide within the Snapping Tolerance; not with Snap to Point off. #[test] fn a_move_snaps_the_grabbed_point_to_a_ruler_guide_with_smart_guides_on() { let (mut d, id) = doc_with_rect(); @@ -797,6 +797,39 @@ fn a_shift_move_lands_the_edges_on_a_ruler_guide() { assert!(moved_by(m, (231.0, 0.0)), "{m:?}"); } +/// With Smart Guides on, a moved selection reaches a ruler guide within the Snapping Tolerance +/// (4 px), as drawing and handle drags do; with Smart Guides off, Snap to Point reaches it within +/// its own distance (2 px). +#[test] +fn a_move_reaches_ruler_guides_within_the_snapping_tolerance() { + let (mut d, id) = doc_with_rect(); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 340.0)); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let dx = |c: &ToolContext, to: f64| { + let mut t = SelectionTool::default(); + t.pointer(c, &ev(PointerKind::Down, 150.0, 150.0)); + let a = t.pointer(c, &ev(PointerKind::Drag, to, 150.0)); + let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") }; + v["matrix"][4].as_f64().unwrap() + }; + let c = cx(&d, &s, &p); + assert!(c.smart_guides && c.snap_to_point && c.guides); + // The right edge, 3 px short of the guide, lands on it, with or without Shift. + assert_eq!(dx(&c, 150.0 + 137.0), 140.0); + let (m, _) = shift_moved(&c, (150.0 + 137.0, 150.0)); + assert!(moved_by(m, (140.0, 0.0)), "{m:?}"); + // The grabbed point, 3 px from the guide, lands on it. + assert_eq!(dx(&c, 337.0), 190.0); + // 5 px away is out of reach. + assert_eq!(dx(&c, 150.0 + 135.0), 135.0); + // Smart Guides off: the grabbed point lands on the guide from 1.5 px, not from 3 px. + let off = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + assert_eq!(dx(&off, 338.5), 190.0); + assert_eq!(dx(&off, 337.0), 187.0); +} + /// Alt pressed during a move makes a copy, which snaps to the original it leaves behind (as /// gathered before the previews moved it); released, the move doesn't. #[test] diff --git a/crates/tools/src/xform/free.rs b/crates/tools/src/xform/free.rs index 0f111faea2..bd7c0c0ecd 100644 --- a/crates/tools/src/xform/free.rs +++ b/crates/tools/src/xform/free.rs @@ -4,15 +4,17 @@ //! Alt from centre), outside the corners rotates, inside moves, and Cmd-dragging a side handle //! shears along that side. A scale snaps as the Selection tool's does. The Perspective Distort and Free Distort modes (tool option `mode`, or //! Cmd / Cmd+Alt+Shift while dragging a corner like classic Illustrator) move the corners of the -//! box and preview `object.distort`. +//! box and preview `object.distort`. After a rotation the box stays turned with the selection, as +//! the Selection tool's does: its handles scale, shear and distort along the selection's own sides. use serde_json::{Value, json}; +use vectorcraft_doc::OrientedBox; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use super::{BLUE, polygon, rect_corners}; use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag}; use crate::guides::{PointSnap, Targets}; -use crate::select::{matrix_json, selection_bounds}; +use crate::select::{handle_cursor, matrix_json, screen_handle, selection_box}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -69,7 +71,8 @@ impl Op { #[derive(Clone, Copy, Debug)] struct Drag { op: Op, - rect: Rect, + /// The selection's bounding box at the press, turned with the selection. + bx: OrientedBox, start: Point, began: bool, } @@ -170,28 +173,37 @@ impl FreeTransformTool { } } - fn classify(&self, cx: &ToolContext, r: Rect, p: Point, m: Mods) -> Option { - let tol = cx.tol(5.0); - if let Some(h) = hit_handle(r, p, tol) { + /// What a press at `p` on box `bx` does, read in the box's own frame. + fn classify(&self, cx: &ToolContext, bx: &OrientedBox, p: Point, m: Mods) -> Option { + let (tol, r, lp) = (cx.tol(5.0), bx.rect, bx.to_local(p)); + if let Some(h) = hit_handle(r, lp, tol) { return Some(self.handle_op(h, m)); } - if self.mode == DistortMode::Free && in_rotate_zone(r, p, tol, cx.tol(18.0)).is_some() { + if self.mode == DistortMode::Free && in_rotate_zone(r, lp, tol, cx.tol(18.0)).is_some() { return Some(Op::Rotate); } - r.contains(p).then_some(Op::Move) + r.contains(lp).then_some(Op::Move) } fn preview(&mut self, cx: &ToolContext, d: Drag, p: Point, m: Mods) -> Action { let shift = m.shift || self.constrain; + let bx = d.bx; let delta = p - d.start; + // The drag along the box's own sides. + let local = bx.to_local(p) - bx.to_local(d.start); self.guides.clear(); let xf = match d.op { Op::Corners(h, mode) => { - let q = distort_quad(d.rect, h, delta, mode); + let q = distort_quad(bx.rect, h, local, mode).map(|c| bx.to_doc() * c); self.quad = Some(q); self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(delta.x, delta.y))); let corners: Vec = q.iter().map(|c| json!([c.x, c.y])).collect(); - return Action::Preview("object.distort".into(), json!({ "corners": corners, "from": [d.rect.x0, d.rect.y0, d.rect.x1, d.rect.y1] })); + let r = bx.rect; + let mut params = json!({ "corners": corners, "from": [r.x0, r.y0, r.x1, r.y1] }); + if bx.angle != 0.0 { + params["angle"] = json!(bx.angle); + } + return Action::Preview("object.distort".into(), params); } Op::Move => { let v = move_delta(d.start, p, shift, cx.constrain_angle); @@ -199,22 +211,23 @@ impl FreeTransformTool { Affine::translate(v) } Op::Scale(h) => { - let mut a = scale_for_drag(d.rect, h, p, shift, m.alt); + // Scaled in the box's own frame, then turned back onto the page. + let mut a = scale_for_drag(bx.rect, h, bx.to_local(p), shift, m.alt); if let Some(t) = &self.targets { - (a, self.guides) = t.snap_scale(cx, &vectorcraft_doc::OrientedBox::aligned(d.rect), h, a, shift, m.alt); + (a, self.guides) = t.snap_scale(cx, &bx, h, a, shift, m.alt); } - let nr = a.transform_rect_bbox(d.rect); + let nr = a.transform_rect_bbox(bx.rect); self.measure = cx.transform_tools_guides.then(|| (p, cx.size_label(nr.width(), nr.height()))); - a + bx.conjugate(a) } - Op::Shear(h) => shear_for_side(d.rect, h, delta, m.alt), + Op::Shear(h) => bx.conjugate(shear_for_side(bx.rect, h, local, m.alt)), Op::Rotate => { - let (a, deg) = rotate_for_drag(d.rect.center(), d.start, p, shift); + let (a, deg) = rotate_for_drag(bx.center(), d.start, p, shift); self.measure = cx.transform_tools_guides.then(|| (p, format!("{:.1}°", -deg))); a } }; - self.quad = Some(rect_corners(d.rect).map(|c| xf * c)); + self.quad = Some(bx.corners().map(|c| xf * c)); Action::Preview("object.transform".into(), json!({ "matrix": matrix_json(xf), "copy": false })) } } @@ -233,10 +246,10 @@ impl Tool for FreeTransformTool { match ev.kind { PointerKind::Down => { self.drag = None; - let Some(r) = selection_bounds(cx) else { return vec![] }; - if let Some(op) = self.classify(cx, r, p, ev.mods) { + let Some(bx) = selection_box(cx) else { return vec![] }; + if let Some(op) = self.classify(cx, &bx, p, ev.mods) { self.targets = op.handle().is_some().then(|| PointSnap::new(cx, || Targets::for_scale(cx))); - self.drag = Some(Drag { op, rect: r, start: p, began: false }); + self.drag = Some(Drag { op, bx, start: p, began: false }); } vec![] } @@ -292,10 +305,12 @@ impl Tool for FreeTransformTool { fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = vec![]; - let quad = match (self.quad, selection_bounds(cx)) { - (Some(q), _) => q, - (None, Some(r)) => rect_corners(r), - _ => return o, + let quad = match self.quad { + Some(q) => q, + None => match selection_box(cx) { + Some(bx) => bx.corners(), + None => return o, + }, }; o.push(Overlay::Path { path: polygon(&quad, true), color: BLUE, width: 1.0, dashed: false }); for i in 0..4 { @@ -313,19 +328,17 @@ impl Tool for FreeTransformTool { } fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor { - let Some(r) = selection_bounds(cx) else { return Cursor::Arrow }; - match self.drag.map(|d| d.op).or_else(|| self.classify(cx, r, p, m)) { - Some(Op::Rotate) => Cursor::rotate_about_in_view(r.center(), p, cx.view_angle()), + let Some(bx) = self.drag.map(|d| d.bx).or_else(|| selection_box(cx)) else { return Cursor::Arrow }; + // The box's angle as it shows on screen. + let shown = bx.angle - cx.view_angle(); + match self.drag.map(|d| d.op).or_else(|| self.classify(cx, &bx, p, m)) { + Some(Op::Rotate) => Cursor::rotate_about_in_view(bx.center(), p, cx.view_angle()), Some(Op::Move) => Cursor::Move, - Some(Op::Shear(Handle::Top | Handle::Bottom)) => Cursor::ShearH, - Some(Op::Shear(_)) => Cursor::ShearV, - Some(Op::Scale(h)) => match h { - Handle::Top | Handle::Bottom => Cursor::ResizeV, - Handle::Left | Handle::Right => Cursor::ResizeH, - Handle::TopLeft | Handle::BottomRight => Cursor::ResizeNwSe, - Handle::TopRight | Handle::BottomLeft => Cursor::ResizeNeSw, - } - .turned(cx.view_angle()), + Some(Op::Shear(h)) => match screen_handle(h, shown) { + Handle::Top | Handle::Bottom | Handle::TopLeft | Handle::BottomRight => Cursor::ShearH, + _ => Cursor::ShearV, + }, + Some(Op::Scale(h)) => handle_cursor(h, shown), Some(Op::Corners(..)) => Cursor::Crosshair, None => Cursor::Arrow, } @@ -422,6 +435,43 @@ mod tests { assert_eq!(t.cursor(&c, Point::new(207.0, 93.0), Mods::default()), Cursor::RotateToward(3), "out from the top right"); } + /// After a 30° turn the box, its handles and their cursors turn with the selection, and a side + /// handle scales along the selection's own width. + #[test] + fn the_box_and_its_handles_turn_with_the_selection() { + let (mut d, id) = doc_with_rect(); + let c = Vec2::new(150.0, 150.0); + let turn = Affine::translate(c) * Affine::rotate(-30f64.to_radians()) * Affine::translate(-c); + d.node_mut(id).unwrap().transform(turn, false); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + let bx = selection_box(&cx).unwrap(); + assert!((bx.angle - 30.0).abs() < 1e-9, "{bx:?}"); + let mut t = FreeTransformTool::default(); + let shown: Vec = t.overlays(&cx).iter().filter_map(|o| if let Overlay::Anchor { p, .. } = o { Some(*p) } else { None }).collect(); + for corner in bx.corners() { + assert!(shown.iter().any(|q| q.distance(corner) < 1e-9), "{corner:?} not in {shown:?}"); + } + let top = bx.to_doc() * Handle::Top.pos(bx.rect); + assert_eq!(t.cursor(&cx, top, Mods::default()), Cursor::ResizeNwSe, "the top handle, turned 30°"); + // The Right handle dragged 100 pt out along the selection's own x axis doubles its width. + let right = bx.to_doc() * Handle::Right.pos(bx.rect); + let to = bx.to_doc() * (Handle::Right.pos(bx.rect) + Vec2::new(100.0, 0.0)); + t.pointer(&cx, &ev(PointerKind::Down, right.x, right.y)); + let a = t.pointer(&cx, &ev(PointerKind::Drag, to.x, to.y)); + assert_eq!(a[0], Action::Begin("Scale".into())); + let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") }; + let m: Vec = v["matrix"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect(); + let m = Affine::new([m[0], m[1], m[2], m[3], m[4], m[5]]); + let local = bx.to_doc().inverse() * m * bx.to_doc(); + let want = Affine::translate((bx.rect.x0, 0.0)) * Affine::scale_non_uniform(2.0, 1.0) * Affine::translate((-bx.rect.x0, 0.0)); + for (got, want) in local.as_coeffs().iter().zip(want.as_coeffs()) { + assert!((got - want).abs() < 1e-9, "{local:?}"); + } + } + #[test] fn cmd_side_handle_shears() { let (d, id) = doc_with_rect(); diff --git a/crates/trace/src/lib.rs b/crates/trace/src/lib.rs index 46c29f4e05..48baeccf83 100644 --- a/crates/trace/src/lib.rs +++ b/crates/trace/src/lib.rs @@ -51,6 +51,7 @@ mod gradient; mod group; mod logo; mod mosaic; +mod opaque; mod quantize; mod shapes; mod smooth; @@ -64,6 +65,7 @@ use vectorcraft_geom::PathData; pub use contour::{Component, Loop, trace_mask}; pub use gradient::TracedGradient; pub use mosaic::mosaic; +pub use opaque::{ALPHA_MAX_DECODE_BYTES, OUTLINE_MAX_ANCHORS, OUTLINE_MAX_PIXELS, decode_alpha, opaque_outline}; pub use quantize::{FULL_TONE_MAX, Quantized, TRANSPARENT, denoise, quantize}; pub use shapes::TracedShape; use subpixel::Crack; diff --git a/crates/trace/src/opaque.rs b/crates/trace/src/opaque.rs new file mode 100644 index 0000000000..52e80a368d --- /dev/null +++ b/crates/trace/src/opaque.rs @@ -0,0 +1,292 @@ +//! The outline of an image's opaque area: what Outline Object on an image's own fill or stroke +//! follows. + +use vectorcraft_geom::{Affine, PathData}; + +use crate::raster::{MAX_PIXELS, fit_size, gif_first_frame_pixels}; +use crate::{Mode, Raster, TraceError, TraceParams, trace_within}; + +/// The most pixels [`opaque_outline`] traces: a larger image is reduced to this many first, +/// aspect kept ([`reduced`]), and its outline is scaled back up to the image's size. +pub const OUTLINE_MAX_PIXELS: u64 = 4 << 20; + +/// The most anchor points an outline may have; an image whose outline would have more gives +/// [`TraceError::TooComplex`]. +pub const OUTLINE_MAX_ANCHORS: usize = 100_000; + +/// The most bytes [`decode_alpha`] decodes an image's samples into (256 MB: 64 megapixels at 8 +/// bits a channel, 32 megapixels at 16). +pub const ALPHA_MAX_DECODE_BYTES: u64 = 256 << 20; + +/// The alpha of the encoded image `bytes` (PNG, WebP, GIF, TIFF and the other formats the image +/// reader takes), one byte a pixel, row by row, with the image's width and height. `None` when the +/// image's format or color type has no alpha; the image is then not decoded. An image of more +/// than [`MAX_PIXELS`] (64 megapixels), or whose samples take more than [`ALPHA_MAX_DECODE_BYTES`], +/// gives [`TraceError::TooLarge`] before it is decoded. +pub fn decode_alpha(bytes: &[u8]) -> Result)>, TraceError> { + use image::ImageDecoder; + let decode_err = |e: image::ImageError| TraceError::Decode(e.to_string()); + let reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| TraceError::Decode(e.to_string()))?; + let decoder = reader.into_decoder().map_err(decode_err)?; + let (w, h) = decoder.dimensions(); + if w == 0 || h == 0 { + return Err(TraceError::Empty); + } + if !decoder.color_type().has_alpha() { + return Ok(None); + } + let pixels = u64::from(w) * u64::from(h); + let frame = gif_first_frame_pixels(bytes).unwrap_or(0); + if pixels.max(frame) > MAX_PIXELS || decoder.total_bytes() > ALPHA_MAX_DECODE_BYTES { + return Err(TraceError::TooLarge { width: w, height: h, max: MAX_PIXELS >> 20 }); + } + let alpha: Vec = match image::DynamicImage::from_decoder(decoder).map_err(decode_err)? { + image::DynamicImage::ImageRgba8(img) => img.as_raw().as_chunks::<4>().0.iter().map(|p| p[3]).collect(), + image::DynamicImage::ImageLumaA8(img) => img.as_raw().as_chunks::<2>().0.iter().map(|p| p[1]).collect(), + img => img.to_rgba8().as_raw().as_chunks::<4>().0.iter().map(|p| p[3]).collect(), + }; + Ok(Some((w, h, alpha))) +} + +/// The outline of the pixels of a `width × height` image whose `alpha` (one byte a pixel, row by +/// row) is at least half opaque (128 or more), in its pixel space (x right, y down; the image +/// spans `0..width × 0..height`). `None` when every pixel is: the outline is then the image's +/// frame. An image with no such pixel gives an empty outline. +/// +/// The alpha is traced as Image Trace's Black and White mode traces a gray at threshold 128, with +/// its Paths and Corners at their defaults and no area left out as noise: the edge runs where the +/// alpha crosses one half, to a fraction of a pixel along anti-aliased edges, and the outline is +/// fitted with curves. Outer outlines and holes run in opposite directions, and an island in a +/// hole runs as outer outlines do, so the outline fills the same with either fill rule. An image +/// of more than [`OUTLINE_MAX_PIXELS`] is traced at that size ([`reduced`]). +pub fn opaque_outline(width: u32, height: u32, alpha: Vec) -> Result, TraceError> { + let (w, h) = (width, height); + if (w as usize).checked_mul(h as usize).is_none_or(|n| n == 0 || n != alpha.len()) { + return Err(TraceError::Empty); + } + if alpha.iter().all(|&a| a >= 128) { + return Ok(None); + } + if alpha.iter().all(|&a| a < 128) { + return Ok(Some(PathData::default())); + } + let (nw, nh) = fit_size(w, h, OUTLINE_MAX_PIXELS); + let alpha = if (nw, nh) == (w, h) { alpha } else { reduced(&alpha, w, h, nw, nh) }; + // Opaque pixels are black, transparent ones white. + let mut rgba = Vec::with_capacity(alpha.len() * 4); + for a in alpha { + let g = 255 - a; + rgba.extend_from_slice(&[g, g, g, 255]); + } + let gray = Raster::new(nw, nh, rgba)?; + let params = TraceParams { mode: Mode::BlackAndWhite, threshold: 128, ignore_white: true, noise: 0, ..TraceParams::default() }; + let traced = trace_within(&gray, ¶ms, OUTLINE_MAX_ANCHORS)?; + let mut out = PathData::default(); + for p in traced.paths { + out.subpaths.extend(p.path.subpaths); + } + if (nw, nh) != (w, h) { + out = out.transformed(Affine::scale_non_uniform(f64::from(w) / f64::from(nw), f64::from(h) / f64::from(nh))); + } + Ok(Some(out)) +} + +/// The `w × h` `alpha` reduced to `nw × nh` (at most `w × h`): each pixel holds the mean of the +/// block of pixels it covers, and at least 128 when that block holds a pixel of 128 or more, so an +/// opaque line thinner than a block stays inside the outline. Along an edge the outline can then +/// run up to half a block further out than the full-size image's would. +fn reduced(alpha: &[u8], w: u32, h: u32, nw: u32, nh: u32) -> Vec { + let span = |i: u32, n: u32, of: u32| { + let at = |i: u32| usize::try_from(u64::from(i) * u64::from(of) / u64::from(n.max(1))).unwrap_or(usize::MAX); + let start = at(i); + start..at(i + 1).max(start + 1) + }; + let cols: Vec<_> = (0..nw).map(|x| span(x, nw, w)).collect(); + let mut out = Vec::with_capacity(nw as usize * nh as usize); + let (mut sums, mut maxes) = (vec![0u64; cols.len()], vec![0u8; cols.len()]); + for ty in 0..nh { + let rows = span(ty, nh, h); + sums.fill(0); + maxes.fill(0); + for y in rows.clone() { + let Some(row) = alpha.get(y * w as usize..(y + 1) * w as usize) else { break }; + for (x, c) in cols.iter().enumerate() { + for &a in row.get(c.clone()).unwrap_or_default() { + sums[x] += u64::from(a); + maxes[x] = maxes[x].max(a); + } + } + } + for (x, c) in cols.iter().enumerate() { + let count = (rows.len() * c.len()).max(1) as u64; + let mean = u8::try_from((sums[x] + count / 2) / count).unwrap_or(u8::MAX); + out.push(if maxes[x] >= 128 { mean.max(128) } else { mean }); + } + } + out +} + +#[cfg(test)] +mod tests { + use kurbo::Shape; + + use super::*; + + /// The width, height and alpha of `img`, as [`opaque_outline`] takes them. + fn alpha(img: &Raster) -> (u32, u32, Vec) { + (img.width, img.height, img.rgba.as_chunks::<4>().0.iter().map(|p| p[3]).collect()) + } + + fn outline(img: &Raster) -> Result, TraceError> { + let (w, h, a) = alpha(img); + opaque_outline(w, h, a) + } + + /// A `w × h` raster, opaque red inside the disc of radius `r` around the middle and + /// transparent outside it. + fn disc(w: u32, h: u32, r: f64) -> Raster { + let (cx, cy) = (f64::from(w) / 2.0, f64::from(h) / 2.0); + Raster::from_fn(w, h, |x, y| { + let (dx, dy) = (f64::from(x) + 0.5 - cx, f64::from(y) + 0.5 - cy); + if dx.hypot(dy) <= r { [255, 0, 0, 255] } else { [0, 0, 0, 0] } + }) + } + + fn area(p: &PathData) -> f64 { + p.to_bezpath().area().abs() + } + + #[test] + fn the_outline_follows_the_opaque_disc_not_the_frame() { + let outline = outline(&disc(100, 100, 30.0)).unwrap().unwrap(); + let b = outline.bounds().unwrap(); + for (got, want) in [(b.x0, 20.0), (b.y0, 20.0), (b.x1, 80.0), (b.y1, 80.0)] { + assert!((got - want).abs() < 1.0, "{b:?}"); + } + let disc_area = std::f64::consts::PI * 30.0 * 30.0; + assert!((area(&outline) - disc_area).abs() < disc_area * 0.02, "{}", area(&outline)); + // Fitted with curves, not one line per pixel step. + assert!(outline.anchor_count() < 40, "{} anchors", outline.anchor_count()); + } + + #[test] + fn an_opaque_image_keeps_its_frame_and_a_transparent_one_has_no_outline() { + let opaque = Raster::from_fn(10, 10, |_, _| [0, 0, 255, 128]); + assert_eq!(outline(&opaque).unwrap(), None); + let clear = Raster::from_fn(10, 10, |_, _| [0, 0, 255, 127]); + assert!(outline(&clear).unwrap().unwrap().is_empty()); + // One pixel either way. + assert_eq!(outline(&Raster::from_fn(1, 1, |_, _| [9, 9, 9, 255])).unwrap(), None); + assert!(outline(&Raster::from_fn(1, 1, |_, _| [9, 9, 9, 0])).unwrap().unwrap().is_empty()); + // No pixels at all, or an alpha that doesn't match the size. + assert!(opaque_outline(0, 0, vec![]).is_err()); + assert!(opaque_outline(2, 2, vec![0]).is_err()); + } + + #[test] + fn pixels_less_than_half_opaque_are_outside() { + // A 20 px square, opaque, inside a 6 px band of alpha `band`, on a transparent 40 px image. + let framed = |band: u8| { + Raster::from_fn(40, 40, |x, y| { + let d = x.min(y).min(39 - x).min(39 - y); + let alpha = match d { + 10.. => 255, + 4.. => band, + _ => 0, + }; + [0, 0, 0, alpha] + }) + }; + let inner = outline(&framed(127)).unwrap().unwrap().bounds().unwrap(); + assert!((inner.x0 - 10.0).abs() < 0.5 && (inner.x1 - 30.0).abs() < 0.5, "{inner:?}"); + // A half-opaque band is inside; the edge runs through the middle of its outer pixels, + // which are half covered. + let outer = outline(&framed(128)).unwrap().unwrap().bounds().unwrap(); + assert!((outer.x0 - 4.5).abs() < 0.25 && (outer.x1 - 35.5).abs() < 0.25, "{outer:?}"); + let outer = outline(&framed(255)).unwrap().unwrap().bounds().unwrap(); + assert!((outer.x0 - 4.0).abs() < 0.25 && (outer.x1 - 36.0).abs() < 0.25, "{outer:?}"); + } + + #[test] + fn a_hole_in_the_opaque_area_is_a_hole_in_the_outline() { + let ring = Raster::from_fn(60, 60, |x, y| { + let d = (f64::from(x) + 0.5 - 30.0).hypot(f64::from(y) + 0.5 - 30.0); + [0, 0, 0, if (10.0..=25.0).contains(&d) { 255 } else { 0 }] + }); + let outline = outline(&ring).unwrap().unwrap(); + let want = std::f64::consts::PI * (25.0 * 25.0 - 10.0 * 10.0); + assert!((outline.to_bezpath().area().abs() - want).abs() < want * 0.03, "{}", outline.to_bezpath().area()); + assert!(!outline.to_bezpath().contains(kurbo::Point::new(30.0, 30.0))); + assert!(outline.to_bezpath().contains(kurbo::Point::new(30.0, 12.0))); + } + + #[test] + fn the_outline_fills_the_same_with_either_fill_rule() { + // A ring with an opaque island in its hole. + let target = Raster::from_fn(80, 80, |x, y| { + let d = (f64::from(x) + 0.5 - 40.0).hypot(f64::from(y) + 0.5 - 40.0); + [0, 0, 0, if (25.0..=35.0).contains(&d) || d <= 10.0 { 255 } else { 0 }] + }); + let path = outline(&target).unwrap().unwrap().to_bezpath(); + let winding = |x: f64, y: f64| path.winding(kurbo::Point::new(x, y)); + let (ring, hole, island, outside) = (winding(40.0, 10.0), winding(40.0, 20.0), winding(40.0, 40.0), winding(2.0, 2.0)); + // Non-zero and even-odd agree when every winding number is -1, 0 or 1. + assert!(ring.abs() == 1 && island == ring && hole == 0 && outside == 0, "{ring} {hole} {island} {outside}"); + } + + #[test] + fn a_large_image_is_traced_smaller_and_scaled_back() { + let big = disc(2400, 2000, 800.0); + assert!(u64::from(big.width) * u64::from(big.height) > OUTLINE_MAX_PIXELS); + let b = outline(&big).unwrap().unwrap().bounds().unwrap(); + for (got, want) in [(b.x0, 400.0), (b.y0, 200.0), (b.x1, 2000.0), (b.y1, 1800.0)] { + assert!((got - want).abs() < 3.0, "{b:?}"); + } + } + + #[test] + fn a_line_thinner_than_the_reduction_stays_in_a_large_images_outline() { + // 39 megapixels, reduced to 4: each traced pixel covers about 3 × 3. The only opaque + // pixels are a line 1 pixel wide, which averages to about a third opaque. + let (w, h) = (8192u32, 4800u32); + let mut a = vec![0u8; (w * h) as usize]; + for y in 1000..3000 { + a[(y * w + 2001) as usize] = 255; + } + let b = opaque_outline(w, h, a).unwrap().unwrap().bounds().unwrap(); + assert!(b.x0 > 1990.0 && b.x1 < 2012.0 && (b.y0 - 1000.0).abs() < 6.0 && (b.y1 - 3000.0).abs() < 6.0, "{b:?}"); + } + + #[test] + fn an_outline_of_too_many_anchors_is_refused() { + // A checkerboard of 2 px squares: more than 50,000 opaque squares. + let checker = Raster::from_fn(640, 640, |x, y| [0, 0, 0, if (x / 2 + y / 2) % 2 == 0 { 255 } else { 0 }]); + assert!(matches!(outline(&checker), Err(TraceError::TooComplex { max: OUTLINE_MAX_ANCHORS }))); + } + + /// `img` encoded as `format`. + fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec { + let mut out = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap(); + out + } + + #[test] + fn decode_alpha_reads_the_alpha_of_formats_that_have_one() { + let px = |x: u32, y: u32| image::Rgba([10, 20, 30, u8::try_from((x + 4 * y) * 16).unwrap()]); + let rgba = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(4, 4, px)); + let want: Vec = (0..16).map(|i| u8::try_from(i * 16).unwrap()).collect(); + for (name, img) in [ + ("rgba", rgba.clone()), + ("gray and alpha", image::DynamicImage::ImageLumaA8(rgba.to_luma_alpha8())), + ("16 bits", image::DynamicImage::ImageRgba16(rgba.to_rgba16())), + ] { + let got = decode_alpha(&encoded(img, image::ImageFormat::Png)).unwrap(); + assert_eq!(got, Some((4, 4, want.clone())), "{name}"); + } + let rgb = image::DynamicImage::ImageRgb8(rgba.to_rgb8()); + assert_eq!(decode_alpha(&encoded(rgb.clone(), image::ImageFormat::Png)).unwrap(), None); + assert_eq!(decode_alpha(&encoded(rgb, image::ImageFormat::Jpeg)).unwrap(), None); + assert!(decode_alpha(b"not an image").is_err()); + } +} diff --git a/crates/trace/src/raster.rs b/crates/trace/src/raster.rs index 3e61c58953..5e198e6fb7 100644 --- a/crates/trace/src/raster.rs +++ b/crates/trace/src/raster.rs @@ -59,7 +59,7 @@ pub struct Raster { /// The pixels the first frame of GIF `bytes` declares in its image descriptor, which the decoder /// allocates for before it crops the frame to the logical screen the dimension check reads. `None` /// when the bytes aren't a GIF or hold no frame header. -fn gif_first_frame_pixels(bytes: &[u8]) -> Option { +pub(crate) fn gif_first_frame_pixels(bytes: &[u8]) -> Option { if !bytes.starts_with(b"GIF8") { return None; } 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/background.rs b/crates/ui-egui/src/background.rs index 16b87a6576..806434fa1f 100644 --- a/crates/ui-egui/src/background.rs +++ b/crates/ui-egui/src/background.rs @@ -190,6 +190,19 @@ pub fn run_with_progress( then(app, r) } +/// Run `f` on the UI thread once job `id` has finished, right after the job's own result is +/// applied, with that applied result (an error when the work failed). Nothing runs when no job +/// `id` is in progress. +pub fn after(app: &mut VectorcraftApp, id: u64, f: impl FnOnce(&mut VectorcraftApp, &Result) + 'static) { + let Some(job) = app.background.jobs.iter_mut().find(|j| j.id == id) else { return }; + let then = std::mem::replace(&mut job.then, Box::new(|_, r| r)); + job.then = Box::new(move |app, r| { + let r = then(app, r); + f(app, &r); + r + }); +} + /// Run `f` with every save and export it starts written at once, as with the preferences off, so /// its result is the written file or the error (a control client's `wait: true`). The jobs already /// running finish first, so none of them writes over its files afterwards. 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/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index b20d7beef1..f34363e5b7 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -942,27 +942,23 @@ pub(crate) fn opentype_body(ui: &mut egui::Ui, d: &mut Dialog) { } } -/// The key under which the dialog keeps its footer's height for the next frame: the dialog's own -/// id, so the stored value is found on every frame. -fn footer_id(ui: &egui::Ui) -> egui::Id { - ui.layer_id().id.with("char-style-footer") +/// The key under which the dialog keeps the height its section content was drawn at, for the next +/// frame. +fn content_id(ui: &egui::Ui) -> egui::Id { + ui.layer_id().id.with("char-style-content") } -/// The dialog's body: the section list beside the selected section's content, which scrolls when it -/// is taller than the window (General lists every attribute of the style and OpenType every -/// feature), and the footer below it - Reset Panel, the Preview checkbox and an invalid value's -/// error. The content's height is the space the footer leaves, measured last frame, so the buttons -/// stay on screen at any interface scale; the section list is outside the scroll area and stays put -/// while the content scrolls. Returns whether the dialog asks to be cancelled (never: Cancel comes -/// from the button row in `dialogs::show`). +/// The dialog's body: the section list beside the selected section's content, and below them +/// Reset Panel, the Preview checkbox and an invalid value's error. The content is at most 420 points +/// tall, and scrolls when it is taller than that or than the screen less the rest of the window +/// (as drawn last frame). The section list stays put while the content scrolls. Returns whether +/// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - // The content scrolls inside a shorter window: General lists every attribute of the style and - // OpenType every feature, so the window stays within the screen and its buttons stay visible. - // The footer was measured last frame, so the room left for the content keeps it on screen at any - // interface scale; the section list stays put while the content scrolls. - let footer = ui.ctx().data(|m| m.get_temp::(footer_id(ui)).unwrap_or(120.0)); - let room = (ui.available_height() - footer - 8.0).clamp(0.0, 420.0); - ui.horizontal(|ui| { + let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); + let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); + let rest = (window - content).max(0.0); + let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).clamp(0.0, 420.0); + let drawn = ui.horizontal(|ui| { section_list(ui, d); ui.separator(); // The section list handles a click before this frame's content is laid out, so the section @@ -971,9 +967,13 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let content_w = ui.available_width(); // Long sections scroll both ways: at a large interface scale the window has fewer points, and // a wide row (a character-format grid) must stay inside it rather than widen the window. - egui::ScrollArea::both().id_salt(("char-style-sections", section)).max_height(room).max_width(content_w).auto_shrink([false, true]).show( - ui, - |ui| { + let shown = egui::ScrollArea::both() + .id_salt(("char-style-sections", section)) + .max_height(room) + .min_scrolled_height(room) + .max_width(content_w) + .auto_shrink([false, true]) + .show(ui, |ui| { ui.vertical(|ui| { if d.str("section") == "basic" { basic_body(ui, d); @@ -996,28 +996,24 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } } }); - }, - ); + }); + // `inner_rect` is the height offered before a short section shrinks the area to its content. + shown.inner_rect.height().min(shown.content_size.y) }); - let footer_h = ui - .scope(|ui| { - reset_button(ui, d); - match edited_attrs(d) { - Ok(attrs) => { - let params = json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs}); - form::preview(app, ui, d, tl!("Character Style Options"), "charStyle.edit", params); - } - Err(why) => attrs_error(ui, &why), - } - }) - .response - .rect - .height(); - let was = ui.ctx().data(|m| m.get_temp::(footer_id(ui))); - ui.ctx().data_mut(|m| m.insert_temp(footer_id(ui), footer_h)); - if was != Some(footer_h) { + let content_h = drawn.inner; + let was = ui.ctx().data(|m| m.get_temp::(content_id(ui))); + ui.ctx().data_mut(|m| m.insert_temp(content_id(ui), content_h)); + if was.is_none_or(|was| (was - content_h).abs() > 0.5) { ui.ctx().request_repaint(); } + reset_button(ui, d); + match edited_attrs(d) { + Ok(attrs) => { + let params = json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs}); + form::preview(app, ui, d, tl!("Character Style Options"), "charStyle.edit", params); + } + Err(why) => attrs_error(ui, &why), + } false } @@ -1127,6 +1123,98 @@ mod tests { let basic = ctx.memory(|m| m.area_rect(dialog)).expect("the dialog is drawn").width(); assert!((basic - width).abs() < 0.5, "the width does not change with the section: {width} -> {basic}"); } + + /// On a 1920 by 1080 screen the dialog opens with its content 420 points tall when the General + /// list is longer than that: the first frame that draws it, with no input, already has the full + /// height, and later frames keep it. + #[test] + fn the_sections_open_at_their_full_height_without_input() { + let mut app = app(); + app.run( + "charStyle.new", + json!({"name": "Body", "attrs": { + "font_family": "Source Sans 3", "font_style": "Regular", "size": 24.0, "leading": 30.0, + "kerning": 0.0, "tracking": 5.0, "all_caps": false, "small_caps": null, + "position": {"kind": "normal", "size": 100.0, "position": 0.0}, "underline": false, + "strikethrough": false, "standardVerticalRoman": false, "charAlign": "romanBaseline", + "h_scale": 100.0, "v_scale": 100.0, "baseline_shift": 0.0, "rotation": 0.0, + "language": "English: USA", "overprint_fill": false, "overprint_stroke": false, + "stroke_width": 0.0, "features": ["liga", "calt", "dlig", "swsh", "salt", "titl", "ordn", "frac"] + }}), + ) + .unwrap(); + open(&mut app, "Body").unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1920.0, 1080.0)); + let mut drawn = 0; + for _ in 0..6 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let texts = texts_of(&out); + let top = |label: &str| texts.iter().find(|(text, _)| text == label).map(|r| r.1.top()); + // The first frame only measures the window and draws no text. + let (Some(reset), Some(general)) = (top("Reset Panel"), top("General")) else { continue }; + drawn += 1; + let content = reset - general; + assert!(content >= 410.0, "the content is 420 points tall in drawn frame {drawn}: {content}"); + } + assert!(drawn >= 4, "the dialog is drawn: {drawn} frames"); + // On the smallest window the buttons are on the screen in the first frame that draws them. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 500.0)); + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let texts = texts_of(&out); + let Some(ok) = texts.iter().find(|(text, _)| text == "OK").map(|r| r.1) else { continue }; + let cancel = texts.iter().find(|(text, _)| text == "Cancel").expect("Cancel is drawn with OK").1; + assert!(ok.bottom() <= 501.0 && cancel.bottom() <= 501.0, "the buttons are on an 800 by 500 screen when first drawn: {ok:?} {cancel:?}"); + return; + } + panic!("the dialog is drawn on an 800 by 500 screen"); + } + + /// Going back to the long General list from a shorter section keeps OK and Cancel on a small + /// screen in the first frame after the switch, not only once the window has measured itself again. + #[test] + fn switching_to_a_long_section_keeps_the_buttons_on_a_small_screen() { + let mut app = app(); + app.run( + "charStyle.new", + json!({"name": "Body", "attrs": { + "font_family": "Source Sans 3", "font_style": "Regular", "size": 24.0, "leading": 30.0, + "kerning": 0.0, "tracking": 5.0, "all_caps": false, "small_caps": null, + "position": {"kind": "normal", "size": 100.0, "position": 0.0}, "underline": false, + "strikethrough": false, "standardVerticalRoman": false, "charAlign": "romanBaseline", + "h_scale": 100.0, "v_scale": 100.0, "baseline_shift": 0.0, "rotation": 0.0, + "language": "English: USA", "overprint_fill": false, "overprint_stroke": false, + "stroke_width": 0.0, "features": ["liga", "calt", "dlig", "swsh", "salt", "titl", "ordn", "frac"] + }}), + ) + .unwrap(); + open(&mut app, "Body").unwrap(); + for h in [560.0, 640.0, 720.0] { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, h)); + for section in ["basic", "advanced", "color", "opentype"] { + app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!(section)); + let _ = frame_texts_in(&ctx, &mut app, 900.0, h); + app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!("general")); + let mut out = + ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let texts = texts_of(&out); + for label in ["OK", "Cancel"] { + let r = texts.iter().find(|(text, _)| text == label).unwrap_or_else(|| panic!("{label} is drawn")).1; + assert!(r.bottom() <= h + 1.0, "{label} stays on a {h}-point screen going from {section} to General: {r:?}"); + } + } + } + } + /// The dialog stays usable in the smallest window the app allows (800 by 500 points): in every /// section the section list, OK and Cancel are on the screen. #[test] 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/package.rs b/crates/ui-egui/src/dialogs/package.rs index 40a8db9cff..2ff2097975 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -1,14 +1,14 @@ //! File → Package…: where the package folder goes, its name, and what it collects (the linked //! files, in a folder of their own or not, relinked or not; the fonts; the report). A document -//! never saved is saved first (Save As); unsaved changes are saved before packaging. The web -//! downloads the package as a zip. +//! never saved is saved first (Save As); unsaved changes are saved before packaging, and when that +//! save fails no package is written. The web downloads the package as a zip. //! //! Fields: `folder` (the location), `name` (the package folder), `copyLinks`, `linksFolder`, //! `relink`, `copyFonts`, `report`. OK runs `file.package` with them, then offers to show the //! package folder (`file.showPackage`). On the desktop with Background Export on, the package is //! collected and written on the background thread ([`crate::background`]) after the dialog closes. -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; use serde_json::{Value, json}; @@ -108,21 +108,35 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } else if d.str("folder").trim().is_empty() { return Err("choose a location for the package".into()); } - // The package holds the document as saved. + // The package holds the document as saved: when the save fails, or asks a question and writes + // nothing yet, no package is written. + let mut saving = None; if app.session.active().is_some_and(|st| st.is_dirty()) { let r = io::save(app, vectorcraft_engine::cmd::fileio::SaveMode::Save, &json!({}), false)?; // The save asks first (it would replace a file that loses what opening it left out). if r.get("pending").is_some() { return Ok(r); } + // Background Save: the save is written on the worker, and its result decides the package. + if r["background"] == true { + saving = app.background.jobs.last().map(background::Job::id); + } } // Background Export (Preferences › File Handling): the linked files and fonts are collected // and the package is written from the document as it is now, while editing goes on. The jobs - // started before it (a save started above, an earlier package to the same folder) are written - // first: the worker runs its jobs in order, and a package made at once waits for them. + // started before it (an earlier package to the same folder) are written first: the worker + // runs its jobs in order, and a package made at once waits for them. let enabled = app.session.prefs.background_export; if !enabled { + let outcome: Rc>>> = Rc::default(); + if let Some(id) = saving { + let applied = outcome.clone(); + background::after(app, id, move |_, r| *applied.borrow_mut() = Some(r.clone())); + } background::wait_all(app); + if let Some(r) = outcome.take().filter(|r| !saved(r)) { + return r; + } } let package = app.session.prepare_package(¶ms).map_err(|e| e.to_string()).inspect_err(|e| app.ui.status = e.clone())?; let label = format!("Packaging {}", d.str("name")); @@ -134,7 +148,23 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { |path: &str, bytes: &[u8]| write(path, bytes).map_err(|e| EngineError::Other(if e.contains(path) { e } else { format!("{path}: {e}") })); package.write(&mut write).map_err(|e| e.to_string()) }; - let r = background::run(app, enabled, label, None, work, move |app, r| packaged(app, r, web, in_background.get()))?; + let start = + move |app: &mut VectorcraftApp| background::run(app, enabled, label, None, work, move |app, r| packaged(app, r, web, in_background.get())); + // Both in the background: the package, collected from the document as it is now, starts once + // the save is written. + if let Some(id) = saving.filter(|_| enabled) { + later.set(true); + app.ui.dialog = None; + background::after(app, id, move |app, r| { + if saved(r) + && let Err(e) = start(app) + { + app.status(e); + } + }); + return Ok(json!({ "background": true })); + } + let r = start(app)?; if r["background"] == true { later.set(true); app.ui.dialog = None; @@ -142,6 +172,12 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { Ok(r) } +/// Did a save whose applied result is `r` write the document (no error, and no question asked +/// before writing)? +fn saved(r: &Result) -> bool { + r.as_ref().is_ok_and(|r| r.get("pending").is_none()) +} + /// Report the package `r` (`file.package`'s reply): the status bar, the web's download, and the /// offer to show the package folder. `later`: it was written in the background, after the dialog /// closed, and a dialog open now is another one, which stays (the status bar names the folder). 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/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index 41253029a2..5c9e899354 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -181,7 +181,7 @@ fn a_dirty_documents_save_is_written_before_its_package() { let (mut app, files) = saved_with_worker(&dir, &gate); let (doc, out) = (dir.path("card.vectorcraft"), dir.path("out")); // With Background Export on, the save and the package both run in the background, and the - // worker writes the save first. + // package starts once the save is written. app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); package_dialog(&mut app, &out); // A thread opens the gate after 10 s at the latest, so a confirm that waits for the save ends. @@ -191,7 +191,7 @@ fn a_dirty_documents_save_is_written_before_its_package() { opener.open(); }); assert_eq!(confirm(&mut app).unwrap()["background"], true); - assert_eq!(app.background.jobs.len(), 2, "the save and the package"); + assert_eq!(app.background.jobs.len(), 1, "the save; the package waits for it"); gate.open(); background::wait_all(&mut app); let paths = written(&files); @@ -216,6 +216,38 @@ fn a_dirty_documents_save_is_written_before_its_package() { assert!(app.ui.status.starts_with("Packaged 3 files in "), "the package's status came last: {}", app.ui.status); } +/// A save before packaging that fails writes no package, with Background Export on or off. +#[test] +fn a_failed_save_before_packaging_writes_no_package() { + let dir = Folder::new("failed-save"); + let (doc, out) = (dir.path("card.vectorcraft"), dir.path("out")); + let root = std::path::Path::new(&out).join("card Folder"); + for background_export in [true, false] { + let mut app = saved(&dir); + let (files, refused) = (Files::default(), doc.clone()); + let recorded = files.clone(); + app.services.write_shared = Some(Arc::new(move |p: &str, b: &[u8]| { + if p == refused { + return Err("Access is denied. (os error 5)".into()); + } + recorded.lock().unwrap().push((p.to_string(), b.to_vec())); + Ok(()) + })); + app.session.execute("prefs.set", &json!({"values": {"backgroundExport": background_export}})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + package_dialog(&mut app, &out); + let r = confirm(&mut app); + background::wait_all(&mut app); + assert!(written(&files).is_empty(), "Background Export {background_export}: {:?}", written(&files)); + assert!(!root.exists(), "Background Export {background_export}: no package folder"); + assert!(app.session.active().unwrap().is_dirty(), "the save failed"); + match r { + Ok(r) => assert!(background_export && r["background"] == true, "{r}"), + Err(e) => assert!(!background_export && e.contains("Access is denied"), "{e}"), + } + } +} + #[test] fn a_package_made_at_once_waits_for_one_in_the_background() { let dir = Folder::new("twice"); diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 486cfd682f..9a0ca9c1d5 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -90,6 +90,9 @@ impl WheelOwner { pub struct MenuLook<'a> { /// Show each family's sample (Preferences › Type › Enable in-menu font previews). pub samples: bool, + /// Preferences › Type › Show samples on white: each sample is drawn in dark type on a white + /// area, whatever the interface's brightness (off by default). + pub on_white: bool, /// Preferences › Type › Show Font Names in English (on by default). pub english_names: bool, /// Row height in points (Font Preview Size). @@ -106,9 +109,9 @@ pub struct MenuLook<'a> { } impl Default for MenuLook<'static> { - /// Samples on, English names, medium rows, no favourites, no wheel. + /// Samples on in the theme's colors, English names, medium rows, no favorites, no wheel. fn default() -> Self { - Self { samples: true, english_names: true, row: ROW, favorites: &[], recent: &[], wheel: false, wheel_owner: None } + Self { samples: true, on_white: false, english_names: true, row: ROW, favorites: &[], recent: &[], wheel: false, wheel_owner: None } } } @@ -121,6 +124,7 @@ impl<'a> MenuLook<'a> { }; Self { samples: app.session.prefs.font_preview, + on_white: app.session.prefs.font_samples_on_white, english_names: app.session.prefs.font_names_in_english, row, favorites: &app.ui.favorite_fonts, @@ -1235,6 +1239,7 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio let current = current.as_str(); let row_h = look.row; let t = Tokens::get(ui.ctx()); + let ink = sample_ink(look.on_white, t.text); let db = vectorcraft_text::FontDb::global(); let favorite = |f: &str| look.favorites.iter().any(|x| x.eq_ignore_ascii_case(f)); let widest = name_width(ui, look.english_names, &rows); @@ -1315,9 +1320,12 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio ui.painter_at(name_rect).text(name_rect.left_center(), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(NAME_SIZE), t.text); // The sample takes the row's whole height. let sample_rect = egui::Rect::from_min_max(rect.min + vec2(name_w, 0.0), rect.max - vec2(STAR + 2.0, 0.0)); - if !look.samples { - } else if let Some(tex) = sample_texture(ui.ctx(), family, row.style(), sample, sample_rect.height()) { - paint_sample(ui, sample_rect, &tex, t.text); + if look.samples { + // The paper is drawn while the sample is still rendering, and for a family whose sample fails. + let area = sample_area(ui, sample_rect, ink, PAPER_INSET); + if let Some(tex) = sample_texture(ui.ctx(), family, row.style(), sample, area.height()) { + paint_sample(ui, area, &tex, ink); + } } if resp.clicked() && !on_triangle && !on_star { chosen = row.pick(); @@ -1366,19 +1374,67 @@ pub(crate) const MENU_SAMPLE_SIZE: egui::Vec2 = vec2(90.0, 16.0); /// A generic sample of `family` drawn in `slot` (the room a Type → Font item of the in-window /// menu bar keeps for it; the native macOS menu shows names only). -pub(crate) fn menu_item_sample(ui: &Ui, slot: egui::Rect, family: &str) { - if let Some(tex) = sample_texture(ui.ctx(), family, None, None, slot.height()) { - paint_sample(ui, slot, &tex, Tokens::get(ui.ctx()).text_dim); +/// With `on_white` (Show samples on white), the sample is drawn in dark type on a white slot. +pub(crate) fn menu_item_sample(ui: &Ui, slot: egui::Rect, family: &str, on_white: bool) { + let ink = sample_ink(on_white, Tokens::get(ui.ctx()).text_dim); + let area = sample_area(ui, slot, ink, 0.0); + if let Some(tex) = sample_texture(ui.ctx(), family, None, None, area.height()) { + paint_sample(ui, area, &tex, ink); } } -/// Draw sample `tex` (tinted `tint`) at the left of `area`, centred vertically, cut at its right. -fn paint_sample(ui: &Ui, area: egui::Rect, tex: &egui::TextureHandle, tint: Color32) { +/// What a sample is drawn on with Show samples on white. +pub(crate) const SAMPLE_PAPER: Color32 = Color32::WHITE; + +/// How a sample is drawn: in `theme` (an interface text color) on the menu's own background, or, +/// with Show samples on white, in the Light brightness's text color on [`SAMPLE_PAPER`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct SampleInk { + pub ink: Color32, + pub paper: Option, +} + +pub(crate) fn sample_ink(on_white: bool, theme: Color32) -> SampleInk { + if on_white { + SampleInk { ink: Tokens::for_brightness(crate::theme::Brightness::Light).text, paper: Some(SAMPLE_PAPER) } + } else { + SampleInk { ink: theme, paper: None } + } +} + +/// Space between the left edge of a sample's paper and its type. +const PAPER_PAD: f32 = 3.0; + +/// Space above and below a menu row's paper, where the row's highlight color shows. +pub(crate) const PAPER_INSET: f32 = 2.0; + +/// The part of `slot` a sample is drawn in: `slot` itself, or, when `ink` has paper, the paper +/// painted in `slot` with `inset` points left above and below it. +fn sample_area(ui: &Ui, slot: egui::Rect, ink: SampleInk, inset: f32) -> egui::Rect { + let Some(paper) = ink.paper else { return slot }; + let area = slot.shrink2(vec2(0.0, inset)); + if area.is_positive() { + ui.painter_at(slot).rect_filled(area, 2.0, paper); + } + area +} + +/// Draw sample `tex` at the left of `area`, centered vertically, cut at its right; on paper, +/// [`PAPER_PAD`] in from its left edge. +fn paint_sample(ui: &Ui, area: egui::Rect, tex: &egui::TextureHandle, ink: SampleInk) { + let painter = ui.painter_at(area); + let mut start = area.left_center(); + if ink.paper.is_some() { + start.x += PAPER_PAD; + } let size = tex.size_vec2() / ui.ctx().pixels_per_point(); - let at = egui::Rect::from_min_size(area.left_center() - vec2(0.0, size.y * 0.5), size); + let at = egui::Rect::from_min_size(start - vec2(0.0, size.y * 0.5), size); let shown = at.intersect(area); + if !shown.is_positive() { + return; + } let uv = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2((shown.width() / size.x).clamp(0.0, 1.0), 1.0)); - ui.painter_at(area).image(tex.id(), shown, uv, tint); + painter.image(tex.id(), shown, uv, ink.ink); } type Key = (String, String, String, u32); diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 69063e8e87..14b203b044 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -882,3 +882,50 @@ fn the_variable_filter_lists_only_variable_families() { assert!(lasting.iter().all(|f| has(&again, f)), "{again:?}"); assert!(has(&again, TWO_AXIS_FAMILY) && has(&again, "Source Sans 3") && has(&again, "JetBrains Mono"), "{again:?}"); } + +/// A Type › Font menu item's sample follows Show samples on white: dark type on a white slot, +/// or the interface's dimmed text color with nothing behind it. The slot is white while the +/// sample is still rendering too. +#[test] +fn a_menu_items_sample_follows_show_samples_on_white() { + use crate::theme::{Brightness, Tokens}; + let dark = Tokens::for_brightness(Brightness::Light).text; + for b in Brightness::ALL { + let t = Tokens::for_brightness(b); + for on_white in [false, true] { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.data_mut(|d| d.insert_temp(egui::Id::NULL, t)); + let slot = egui::Rect::from_min_size(egui::pos2(40.0, 20.0), super::MENU_SAMPLE_SIZE); + let frame = || { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::menu_item_sample(ui, slot, "Inter", on_white)); + out.textures_delta.clear(); + out.shapes + }; + frame(); + super::wait_for_samples(&ctx); + let shapes = frame(); + let tints: Vec<_> = shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => m.vertices.first().map(|v| v.color), + _ => None, + }) + .collect(); + let papers = + shapes.iter().filter(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.fill == super::SAMPLE_PAPER && r.rect == slot)).count(); + assert_eq!(tints, [if on_white { dark } else { t.text_dim }], "{}, on white {on_white}", b.id()); + assert_eq!(papers, usize::from(on_white), "{}, on white {on_white}", b.id()); + } + } + // While a family's sample is still rendering, its slot is already white. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let slot = egui::Rect::from_min_size(egui::pos2(40.0, 20.0), super::MENU_SAMPLE_SIZE); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::menu_item_sample(ui, slot, "JetBrains Mono", true)); + out.textures_delta.clear(); + let shapes = out.shapes; + super::wait_for_samples(&ctx); + assert!(!shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default())), "no sample"); + assert!(shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.fill == super::SAMPLE_PAPER && r.rect == slot)), "the slot is white"); +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 7ee09ee14e..50d41f094e 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -659,7 +659,8 @@ const MESSAGE_DEPTH: usize = 5; /// Translate a status or error message for display (see the module docs). Unknown messages, and /// parts of them (file names, numbers, a reason with no entry, a JSON object or array such as -/// `{"objects": [...]}`), stay as they are. +/// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”` or backticks, such as a +/// symbol's name), stay as they are. pub fn message(lang: Lang, s: &str) -> String { message_at(lang, s, MESSAGE_DEPTH) } @@ -669,7 +670,8 @@ fn message_at(lang: Lang, s: &str, depth: usize) -> String { let count = caps.iter().find(|(k, _)| *k == "n").and_then(|(_, v)| v.parse::().ok()); let form = count.map_or(forms.len().saturating_sub(1), |n| (lang.0.plural)(n).min(forms.len().saturating_sub(1))); let Some(template) = forms.get(form) else { return s.to_string() }; - let nested = |v: &str| depth > 1 && !v.starts_with(['{', '[']); + let quoted = |v: &str| [('"', '"'), ('“', '”'), ('`', '`')].iter().any(|(a, b)| s.contains(&format!("{a}{v}{b}"))); + let nested = |v: &str| depth > 1 && !v.starts_with(['{', '[']) && !quoted(v); let values: Vec<(&str, String)> = caps.into_iter().map(|(k, v)| (k, if nested(v) { message_at(lang, v, depth - 1) } else { v.to_string() })).collect(); let args: Vec<(&str, &str)> = values.iter().map(|(k, v)| (*k, v.as_str())).collect(); @@ -677,13 +679,23 @@ fn message_at(lang: Lang, s: &str, depth: usize) -> String { } /// Fill `{name}` placeholders in one pass: a value that holds `{name}` text stays as it is. -/// Unknown placeholders are left as written. +/// Unknown placeholders are left as written. `{{` and `}}` are a literal `{` and `}`. fn fill_once(template: &str, args: &[(&str, &str)]) -> String { let mut rest = template; let mut out = String::with_capacity(rest.len()); - while let Some(open) = rest.find('{') { + while let Some(open) = rest.find(['{', '}']) { out.push_str(&rest[..open]); let after = &rest[open + 1..]; + if rest[open..].starts_with('}') { + out.push('}'); + rest = after.strip_prefix('}').unwrap_or(after); + continue; + } + if let Some(escaped) = after.strip_prefix('{') { + out.push('{'); + rest = escaped; + continue; + } let filled = after.find('}').and_then(|close| args.iter().find(|(k, _)| *k == &after[..close]).map(|(_, v)| (*v, close))); match filled { Some((value, close)) => { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index dcb73ca8af..839d14e8ad 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 Знаци за изрязване @@ -793,6 +797,8 @@ font-technology Variable Променливи Delete Width Point Изтриване на точка на ширината Delete Workspace Изтриване на работно пространство Delete {kind} Style Изтриване на стил ({kind}) + Delete the selected items and their artwork? Да се изтрият ли избраните елементи заедно с графиката им? + Delete this layer and its artwork? Да се изтрие ли този слой заедно с графиката му? Delete “{name}”? Изтриване на „{name}“? Depth: Дълбочина: Description Описание @@ -1005,6 +1011,7 @@ font-technology Variable Променливи Enable Contextual Task Bar Разрешаване на контекстуалната лента със задачи Enable copying of text, images and other content Разрешаване на копирането на текст, изображения и друго съдържание Enable in-menu font previews Разрешаване на прегледи на шрифтове в менюто + Show samples on white Показване на мострите на бял фон Enable Missing Glyph Protection Разрешаване на защита срещу липсващи глифи Enable Opacity Mask Разрешаване на маска за непрозрачност Enable plaintext metadata Разрешаване на метаданни в обикновен текст @@ -1967,6 +1974,10 @@ font-technology Variable Променливи Long Дълго Stylistic Стилистично Mojikumi Set Набор Mojikumi + YakumonoHankaku YakumonoHankaku + GyomatsuYakumonoHankaku GyomatsuYakumonoHankaku + GyomatsuYakumonoZenkaku GyomatsuYakumonoZenkaku + YakumonoZenkaku YakumonoZenkaku Kinsoku Set Набор Kinsoku Kinsoku Shori Type Тип Kinsoku Shori Push In First Първо прибиране @@ -2200,6 +2211,8 @@ font-technology Variable Променливи Normal Screen Mode Нормален режим на екран Note: Забележка: Nothing matches the Show filter. Нищо не отговаря на филтъра за показване. + Show DCS Transparency Interactions Показване на взаимодействията на DCS с прозрачност + Transparent, or overlaps transparent objects: check its separations Прозрачно е или се припокрива с прозрачни обекти: проверете цветоотделянето му Nothing to print Няма нищо за отпечатване Nudge Преместване Nudge in Perspective Преместване в перспектива @@ -5986,6 +5999,23 @@ axis Y Axis Y ос @msg Batch cannot play an action with a stop Пакет не може да изпълни действие със спиране Insert Menu Item… Вмъкване на елемент от меню… Insert Menu Item Вмъкване на елемент от меню + Insert Select Path Вмъкване на избор на път + Select Path Избор на път +@msg select one whole path or compound path изберете един цял път или съставен път +@msg select only one path изберете само един път +@msg the path is hidden or locked, or cannot be selected here пътят е скрит или заключен, или не може да бъде избран тук +@msg object {value} is not the stored path: it changed, or the document is another one обект {value} не е запазеният път: той е променен или документът е друг +@msg `fingerprint` must be "v1:" and 16 lowercase hex digits `fingerprint` трябва да е "v1:" и 16 шестнадесетични цифри с малки букви + 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 aeb045f9a4..5d7835022b 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… @@ -1925,6 +1929,8 @@ digits Malayalam Malajalam Modified since it was read: {path} Izmijenjeno nakon čitanja: {path} No Thumbnails Bez sličica Nothing matches the Show filter. Ništa ne odgovara filteru Prikaži. + Show DCS Transparency Interactions Prikaži interakcije DCS-a s prozirnošću + Transparent, or overlaps transparent objects: check its separations Prozirno je ili preklapa prozirne objekte: provjerite njegove separacije PPI PPI Relink… Ponovo poveži… Find Linked Files Pronađi povezane datoteke @@ -2000,6 +2006,10 @@ digits Malayalam Malajalam Long Dugo Stylistic Stilsko Mojikumi Set Mojikumi skup + YakumonoHankaku YakumonoHankaku + GyomatsuYakumonoHankaku GyomatsuYakumonoHankaku + GyomatsuYakumonoZenkaku GyomatsuYakumonoZenkaku + YakumonoZenkaku YakumonoZenkaku Kinsoku Set Kinsoku skup Kinsoku Shori Type Vrsta Kinsoku Shori Push In First Prvo uvlačenje @@ -2135,6 +2145,8 @@ digits Malayalam Malajalam Weight: Debljina: Art using a deleted global swatch keeps its colour. Crtež koji koristi izbrisani globalni uzorak boje zadržava svoju boju. Color Group: {name} Grupa boja: {name} + Delete the selected items and their artwork? Izbrisati odabrane stavke zajedno s njihovim crtežom? + Delete this layer and its artwork? Izbrisati ovaj sloj zajedno s njegovim crtežom? Delete “{name}”? Izbrisati „{name}”? Document Swatches Uzorci boja dokumenta Edit or Apply Color Group Uredi ili primijeni grupu boja @@ -3723,6 +3735,7 @@ theme Appearance Izgled Enable Background Export Omogući izvoz u pozadini Enable Background Save Omogući čuvanje u pozadini Enable in-menu font previews Omogući preglede fontova u meniju + Show samples on white Prikaži uzorke na bijeloj podlozi Enable Missing Glyph Protection Omogući zaštitu od nedostajućih glifova Enable Rubber Band for Omogući gumenu traku za Enable Touch Gestures Omogući pokrete dodirom @@ -6028,6 +6041,23 @@ 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 + Insert Select Path Umetni odabir putanje + Select Path Odabir putanje +@msg select one whole path or compound path odaberite jednu cijelu putanju ili složenu putanju +@msg select only one path odaberite samo jednu putanju +@msg the path is hidden or locked, or cannot be selected here putanja je skrivena ili zaključana, ili se ovdje ne može odabrati +@msg object {value} is not the stored path: it changed, or the document is another one objekt {value} nije sačuvana putanja: promijenjena je ili je dokument drugi +@msg `fingerprint` must be "v1:" and 16 lowercase hex digits `fingerprint` mora biti "v1:" i 16 malih heksadecimalnih cifara + 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 a27a1bcd5c..959a4c39ca 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 @@ -1159,6 +1163,8 @@ antiAlias Sharp Nítid Delete Width Point Suprimeix el punt d’amplada Delete Workspace Suprimeix l’espai de treball Delete {kind} Style Suprimeix l’estil de {kind} + Delete the selected items and their artwork? Voleu suprimir els elements seleccionats i el seu art? + Delete this layer and its artwork? Voleu suprimir aquesta capa i el seu art? Delete “{name}”? Voleu suprimir “{name}”? Depth Profunditat Depth: Profunditat: @@ -1468,6 +1474,7 @@ antiAlias Sharp Nítid Enable copying of text, images and other content Activa la còpia de text, imatges i altre contingut Enable Guides for 9-Slice Scaling Activa les guies per a l’escalat de 9 talls Enable in-menu font previews Activa les previsualitzacions de tipus de lletra als menús + Show samples on white Mostra les mostres sobre fons blanc Enable Missing Glyph Protection Activa la protecció de glifs absents Enable Opacity Mask Activa la màscara d’opacitat Enable plaintext metadata Activa les metadades en text pla @@ -2588,6 +2595,10 @@ digits Malayalam Malaiàlam Modify Modifica Mojikumi Ajust mojikumi Mojikumi Set Conjunt mojikumi + YakumonoHankaku YakumonoHankaku + GyomatsuYakumonoHankaku GyomatsuYakumonoHankaku + GyomatsuYakumonoZenkaku GyomatsuYakumonoZenkaku + YakumonoZenkaku YakumonoZenkaku Monitor RGB RGB del monitor Mono Monocrom Monochromatic Monocromàtic @@ -2808,6 +2819,8 @@ digits Malayalam Malaiàlam Note: Nota: Nothing is selected. Select the art to export, then open this tab again. No hi ha res seleccionat. Selecciona la il·lustració que vols exportar i torna a obrir aquesta pestanya. Nothing matches the Show filter. Res no coincideix amb el filtre Mostra. + Show DCS Transparency Interactions Mostra les interaccions de transparència DCS + Transparent, or overlaps transparent objects: check its separations És transparent o se superposa a objectes transparents: comproveu-ne les separacions Nothing to print No hi ha res per imprimir NTSC Colors Colors NTSC Nudge Desplaça @@ -4041,6 +4054,23 @@ 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ú + Insert Select Path Insereix una selecció de traçat + Select Path Selecciona el traçat +@msg select one whole path or compound path selecciona un traçat sencer o un traçat compost +@msg select only one path selecciona només un traçat +@msg the path is hidden or locked, or cannot be selected here el traçat està amagat o bloquejat, o no es pot seleccionar aquí +@msg object {value} is not the stored path: it changed, or the document is another one l’objecte {value} no és el traçat desat: ha canviat o el document és un altre +@msg `fingerprint` must be "v1:" and 16 lowercase hex digits `fingerprint` ha de ser "v1:" i 16 dígits hexadecimals en minúscula + 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. @@ -5802,6 +5832,7 @@ digits Malayalam Malaiàlam @msg not a VectorCraft shortcut set (missing `overrides`) no és un conjunt de dreceres de VectorCraft (falta `overrides`) @msg not an EMF or WMF file no és un fitxer EMF o WMF @msg not an HP-GL file no és un fitxer HP-GL +@msg not a PICT file no és un fitxer PICT @msg `pens` must be an array of 1 to 255 #rrggbb colors `pens` ha de ser una matriu d’1 a 255 colors #rrggbb @msg not an RTF file: it doesn't start with {\\rtf no és un fitxer RTF: no comença amb {\\rtf @msg not found no s’ha trobat @@ -5961,6 +5992,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 @@ -6011,7 +6046,67 @@ digits Malayalam Malaiàlam @msg t, dx and dy must be finite t, dx i dy han de ser finits @msg Targa files are RGB: colorModel rgb Els fitxers Targa són RGB: colorModel rgb @msg Text Wrap: select a wrap object Ajustament de text: selecciona un objecte d’ajustament +@msg the active document changed while the question was open; nothing was deleted el document actiu ha canviat mentre la pregunta era oberta; no s’ha suprimit res @msg that document is no longer open aquest document ja no està obert +@msg Extrude & Bevel Extrudeix i bisella +@msg Revolve Revoluciona +@msg Inflate Infla +@msg Rotate Gira +@msg Extrude & Bevel (Classic) Extrudeix i bisella (clàssic) +@msg Revolve (Classic) Revoluciona (clàssic) +@msg Rotate (Classic) Gira (clàssic) +@msg This effect Aquest efecte +@msg clipping paths traçats de retall +@msg other objects altres objectes +@msg {label} requires a group holding a shape with at least two anchors {label} requereix un grup que contingui una forma amb com a mínim dos punts d’ancoratge +@msg Revolve requires a group holding a shape with at least two anchors Revoluciona requereix un grup que contingui una forma amb com a mínim dos punts d’ancoratge +@msg Revolve requires a shape with at least two anchors Revoluciona requereix una forma amb com a mínim dos punts d’ancoratge +@msg {label} on a group needs paths, compound paths, type, groups, clipping groups, blends and symbol instances: release or expand its {what} first. {label} en un grup necessita traçats, traçats compostos, text, grups, grups de retall, fusions i instàncies de símbol: primer allibera o expandeix aquests elements: {what}. +@msg {label} on a group takes at most {MAX_MEMBERS} objects {label} en un grup admet com a màxim {MAX_MEMBERS} objectes +@msg A 3D effect on a group or layer goes on the group itself, not on its fill or stroke Un efecte 3D en un grup o una capa s’aplica al mateix grup, no al seu farciment ni al seu traç +@msg a 3D effect on a group's fill or stroke draws nothing un efecte 3D al farciment o al traç d’un grup no dibuixa res +@msg a 3D effect on a group's fill or stroke draws nothing to export un efecte 3D al farciment o al traç d’un grup no dibuixa res per exportar +@msg The 3D object is too complex to export L’objecte 3D és massa complex per exportar-lo +@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) l’objecte no té cap efecte 3D (Extrudeix i bisella, Revoluciona, Infla o Gira) +@msg its 3D effect builds no solid el seu efecte 3D no construeix cap sòlid +@msg bevel must be none or one of {_1} bevel ha de ser none o un de {_1} +@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} no pot construir sòlids a partir d’aquesta il·lustració: les seves instàncies de símbol, fusions i grups de retall contenen massa objectes +@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} no pot construir un sòlid a partir de la instància del símbol «{symbol}»: la il·lustració del símbol no està disponible +@msg {_1}: the clipping path is too complex to cut the art with {_1}: el traçat de retall és massa complex per retallar-hi la il·lustració +@msg {_1} takes at most {MAX_MEMBERS} objects {_1} admet com a màxim {MAX_MEMBERS} objectes +@msg {_1} can't build solids from art nested more than {MAX_DEPTH} levels deep {_1} no pot construir sòlids a partir d’una il·lustració imbricada en més de {MAX_DEPTH} nivells +@msg Revolve paint is too complex for this surface; reduce Segments or simplify the gradient La pintura de Revoluciona és massa complexa per a aquesta superfície; redueix Segments o simplifica el degradat +@msg Revolve edge must be left or right Revoluciona: edge ha de ser left o right +@msg Revolve cap must be a boolean Revoluciona: cap ha de ser un booleà +@msg the revolved object has no fill or stroke l’objecte de revolució no té farciment ni traç +@msg lightColor must be an opaque RGB color in #rrggbb form lightColor ha de ser un color RGB opac en format #rrggbb +@msg lights must contain one to ten lights lights ha de contenir d’un a deu llums +@msg each light must be an object cada llum ha de ser un objecte +@msg unknown light setting: use color, intensity, rotation, height, softness or behind paràmetre de llum desconegut: fes servir color, intensity, rotation, height, softness o behind +@msg light {key} must be a number from {min} to {max} llum: {key} ha de ser un nombre de {min} a {max} +@msg light color must use opaque #rrggbb color d’un llum ha de fer servir #rrggbb opac +@msg light behind must be true or false behind d’un llum ha de ser true o false +@msg shadow must be true or false shadow ha de ser true o false +@msg shadowPosition must be behind or below shadowPosition ha de ser behind o below +@msg {key} must be a number from {min} to {max} {key} ha de ser un nombre de {min} a {max} +@msg each of `{GRAPHICS}` must be an object cada element de `{GRAPHICS}` ha de ser un objecte +@msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` les entrades de `{GRAPHICS}` admeten symbol, face, x, y, scale i rotation, no `{k}` +@msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol cada element de `{GRAPHICS}` necessita `symbol`, el nom d’un símbol +@msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` ha de ser front o back +@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` ha de ser un nombre de {lo} a {hi} +@msg `{GRAPHICS}` must be an array `{GRAPHICS}` ha de ser una matriu +@msg Graphics map onto planar faces: use the Extrude or Plane object type Els gràfics s’apliquen a cares planes: fes servir el tipus d’objecte Extrusió o Pla +@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admet com a màxim {MAX_GRAPHICS} gràfics +@msg A plane has one face: map its graphics onto the front Un pla té una sola cara: aplica’n els gràfics a la cara davantera +@msg The graphics are too complex: simplify the symbols' art Els gràfics són massa complexos: simplifica la il·lustració dels símbols +@msg A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art La il·lustració d’un gràfic es pot imbricar com a màxim en {MAX_LEVELS} nivells: simplifica la il·lustració del símbol +@msg A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art La il·lustració d’un gràfic pot imbricar símbols com a màxim en {MAX_NESTING} nivells: simplifica la il·lustració del símbol +@msg A graphic's art holds too many objects: simplify the symbol's art La il·lustració d’un gràfic conté massa objectes: simplifica la il·lustració del símbol +@msg A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art Un gràfic dibuixa com a màxim {MAX_PIECES} farciments i traços: simplifica la il·lustració del símbol +@msg `surface` must be one of {_1} `surface` ha de ser un de {_1} +@msg {label} draws the source art for this object instead of its 3D surface {label} dibuixa la il·lustració d’origen d’aquest objecte en lloc de la seva superfície 3D +@msg {label} draws no faces for this object {label} no dibuixa cap cara per a aquest objecte +@msg the wireframe has more than {MAX_WIRE_EDGES} edges el filferro té més de {MAX_WIRE_EDGES} arestes @msg The 3D surface is too complex; simplify the shape La superfície 3D és massa complexa; simplifica la forma @msg the action has no steps l’acció no té cap pas @msg the action has no included steps l’acció no té cap pas inclòs @@ -6191,6 +6286,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} @@ -7118,7 +7214,9 @@ breakText Glyphs Glifs @msg “{shown}” opens {_1} files, not `{_2}` «{shown}» obre fitxers {_1}, no `{_2}` @msg `{_1}` is a plug-in of kind `{_2}`, not an importer `{_1}` és un complement del tipus `{_2}`, no un importador @msg `{_1}` is a plug-in of kind `{_2}`, not an exporter `{_1}` és un complement del tipus `{_2}`, no un exportador -@msg `{_1}` is an importer: open a file with document.open {{"importer"}"}} `{_1}` és un importador: obriu un fitxer amb document.open {{"importer"}"}} +@msg `{_1}` is an importer: open a file with document.open {{"importer": "{_2}"}} `{_1}` és un importador: obriu un fitxer amb document.open {{"importer": "{_2}"}} +@msg `{_1}` is an exporter: export with document.export {{"format": "{_2}"}} `{_1}` és un exportador: exporteu amb document.export {{"format": "{_2}"}} +@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` és un efecte dinàmic: apliqueu-lo amb effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects l’importador no ha retornat cap objecte @msg an importer returns `objects` and `warnings`, not `{key}` un importador retorna `objects` i `warnings`, no `{key}` @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads el fitxer supera els {MAX_INPUT_BYTES} bytes que llegeix un importador diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs index 138299643d..ac659ac4b2 100644 --- a/crates/ui-egui/src/i18n/catalog.rs +++ b/crates/ui-egui/src/i18n/catalog.rs @@ -47,23 +47,42 @@ const MAX_MESSAGE_LEN: usize = 2000; impl Template { /// `None` for a template that can't be matched reliably: no literal text, or two placeholders - /// in a row (where one ends and the next begins is unknowable). + /// in a row (where one ends and the next begins is unknowable). `{{` and `}}` are a literal `{` + /// and `}`, as in a Rust format string, and so is a `{` with no `}` after it. fn parse(source: &str, forms: Vec, counted: bool) -> Option