Merge main into feat/3d-custom-bevels

This commit is contained in:
dotCooCoo committed 2026-11-12 22:28:17 -08:00
commit fc41eb8033
257 files changed
+19051 -1325

No files matched your search

Generated
+1
View File
@@ -6476,6 +6476,7 @@ dependencies = [
"vectorcraft-plugins",
"vectorcraft-text",
"vectorcraft-three-d",
"vectorcraft-trace",
]
[[package]]
+7 -2
View File
@@ -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<String> {
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<String> {
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,
}
}
+30
View File
@@ -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));
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -150,7 +150,7 @@ fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> 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<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
let mut buf = tiff::decoder::DecodingResult::U8(Vec::new());
let layout = d.read_image_to_buffer(&mut buf).ok()?;
let data = match buf {
+197
View File
@@ -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")
}
}
+2
View File
@@ -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;
+31
View File
@@ -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() {
+4 -1
View File
@@ -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.
+25 -7
View File
@@ -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<f64>, Option<f64>)| {
// 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;
+4
View File
@@ -261,6 +261,10 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
b += ALLOC + size_of::<NodeExtras>();
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::<crate::color_mask::ColorMask>() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3);
b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t));
b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
if e.intertwine_tiers.capacity() > 0 {
+4
View File
@@ -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<Box<crate::color_mask::ColorMask>>,
}
/// 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
+24 -13
View File
@@ -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))))
}
}
+5
View File
@@ -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<Box<crate::color_mask::ColorMask>>,
}
impl From<NodeWire> for Node {
@@ -269,6 +273,7 @@ impl From<NodeWire> 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,
+14 -12
View File
@@ -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<Vec<Vec<[u8; 4]>>> {
/// 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<Vec<Vec<[u8; 4]>>> {
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<usize> = 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
+30 -1
View File
@@ -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"))));
+533
View File
@@ -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<String> {
if !hex.len().is_multiple_of(2) || hex.len() > max * 2 {
return None;
}
let bytes: Option<Vec<u8>> = (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<u8>,
}
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<InkPlate>,
}
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<InkPlate>) -> Option<Self> {
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<Item = &InkPlate> {
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<u8> {
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<u8> {
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<ImageBlob> {
let gray: Vec<u8> = 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<String> {
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<PlateFile> {
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> {
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<Self> {
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::<colortype::CMYK8>(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<String> =
[(!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::<colortype::Gray8>(s.width, s.height).ok()?;
img.encoder().write_tag(Tag::ImageDescription, description(p).as_str()).ok()?;
let inverted: Vec<u8> = 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<PlateFile> {
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<PathData> {
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<Arc<Separated>> {
thread_local! {
static LAST: std::cell::RefCell<Option<(String, Arc<Separated>)>> = 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<Separated> {
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::<colortype::CMYK8>(1, 1, &[0, 0, 0, 0]).unwrap();
for i in 0..plates {
let mut img = enc.new_image::<colortype::Gray8>(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::<colortype::CMYK8>(1, 1, &[0, 0, 0, 0]).unwrap();
let mut img = enc.new_image::<colortype::Gray8>(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::<colortype::Gray8>(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<InkPlate> = (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");
}
}
+159 -42
View File
@@ -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<NodeId> =
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<String>, &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<String, serde_json::Value>, key: &str, f: &mut LinkFn) -> bool {
let Some(value) = attrs.get_mut(key) else { return false };
let Ok(mut paint) = serde_json::from_value::<Paint>(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<Paint> + '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<Paint> + '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<String, serde_json::Value>, key: &str, f: &mut PaintFn) -> bool {
let Some(value) = attrs.get_mut(key) else { return false };
let Ok(paint) = serde_json::from_value::<Paint>(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<Item = &Paint> {
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<Item = &Paint> {
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<Item = &mut Paint> {
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<Item = &mut Paint> {
let runs = match &mut n.kind {
@@ -333,20 +409,11 @@ pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
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<Node> = 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<Node>, f: &mut LinkFn) -> usize {
fn map_tree(n: &mut Arc<Node>, 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<Node>, f: &mut LinkFn) -> usize {
}
}
fn map_trees(v: &mut [Arc<Node>], f: &mut LinkFn) -> usize {
fn map_trees(v: &mut [Arc<Node>], 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<String>, _: &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();
+15
View File
@@ -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 {
+1
View File
@@ -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
+64 -7
View File
@@ -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<Node> {
/// `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<Node> {
let mut m: Option<Node> = 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<Node>)
_ => 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<String> {
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<String> = g.freeform.as_ref().unwrap().points.iter().map(|p| p.color.to_hex()).collect();
+38 -2
View File
@@ -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<usize> = 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<u64> = const { std::cell::Cell::new(0) };
}
/// `n` with its geometry effects evaluated (`None` = unchanged).
fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
// 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<Node> {
}
_ => 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<Document> {
};
}
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)
+1 -1
View File
@@ -296,7 +296,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"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(
+2 -2
View File
@@ -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,
+272 -23
View File
@@ -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<Effect> {
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<String>) -> 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<AppearanceItem> {
items
.iter()
@@ -180,11 +304,109 @@ fn image_rows(items: &[AppearanceItem]) -> Vec<AppearanceItem> {
.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<PathData>, (u32, u32))>;
/// One of [`Outlines`]' entries: the pixels, held weakly, and their outline once it is traced.
type Entry = (Weak<Vec<u8>>, Arc<OnceLock<Traced>>);
/// 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<usize, Entry>,
/// The lookups since the last pruning.
lookups: usize,
}
static OUTLINES: Mutex<Outlines> = 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<usize> = const { std::cell::Cell::new(0) };
}
/// Does [`OUTLINES`] keep an entry for `pixels`?
#[cfg(test)]
pub(crate) fn keeps_outline(pixels: &Weak<Vec<u8>>) -> 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<PathData> {
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<Node> {
// 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<AppearanceItem>| {
(!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() };
+5 -3
View File
@@ -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]),
}
+76 -13
View File
@@ -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<Rect>,
/// 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<Shown>,
}
/// 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<Arc<(PathData, FillRule)>>,
}
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<T>(&mut self, c: &Node, f: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
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<bool, String> {
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<Vec<Arc<Node>>, 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;
}
@@ -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();
@@ -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>) -> 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<Node>| {
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<Node> = 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 {
+103
View File
@@ -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::<Vec<_>>()),
_ => 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<Vec<Point>>, 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.
+338
View File
@@ -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<u8> {
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<u8>, items: Vec<AppearanceItem>, 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<u8>)], rows: &[u8]) -> Vec<u8> {
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<Effect>) -> 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<Rect> {
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<Rect> {
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));
}
+2 -2
View File
@@ -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;
+1 -1
View File
@@ -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;
+112 -74
View File
@@ -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<CommandSpec> {
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<CommandSpec> {
"{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<Self> {
/// The settings `p` gives to command `cmd`, each checked.
fn read(p: &Value, cmd: &str) -> Result<Self> {
let percent = |key: &str| -> Result<f64> {
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<Vec<[u8; 3]>> {
/// 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<Vec<[u8; 3]>> {
// 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::<Option<_>>().ok_or_else(colors_error)?,
_ => return Err(colors_error()),
Value::Array(a) => a.iter().take(MAX_COLORS + 1).map(Value::as_str).collect::<Option<_>>().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<Value> {
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<Value> {
/// 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<Vec<(NodeId, Cleared, Affine)>> {
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<NodeId> = 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<NodeId> = 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<Cleared>> = 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<Vec<(NodeId, &'a ImageObject, &'a ImageBlob)>> {
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<Vec<NodeId>> {
let st = s.doc()?;
let ids: Vec<NodeId> = 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<NodeId> = 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<Option<Cleared>> {
/// 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<Option<Cleared>> {
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<Pixels>, bool, Option<Vec<u8>>)> {
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<Pixels>, bool, Option<Vec<u8>>)> {
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<Pix
let deep = kind.bytes_per_pixel() > 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);
+443
View File
@@ -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<CommandSpec> {
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<Self> {
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<Option<(String, ImageBlob, u64)>> {
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<Value> {
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<u64> = 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<ImageBlob>, u64);
fn mask_changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Vec<MaskChange>> {
let st = s.doc()?;
// Each image's pixels once, however many objects show them.
let mut made: HashMap<&str, (String, Option<ImageBlob>, 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<Value> {
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::<Vec<_>>().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<Vec<NodeId>> {
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<Value> {
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::<Vec<_>>() }))
}
fn apply_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
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::<Vec<_>>() }))
}
/// 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<Result<(ColorMask, Option<ImageBlob>)>> {
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<ImageBlob>)> {
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<Node>> = 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<Node>, old: Option<&Arc<Node>>) -> 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<HashMap<NodeId, &Arc<Node>>> = 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<ColorMask> {
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)
}
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -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));
}
@@ -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 {
+6 -2
View File
@@ -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<vectorcraft_tools::PaintDefaults> {
/// 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<vectorcraft_tools::PaintDefaults> {
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()))
}
+1 -1
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
+57 -8
View File
@@ -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 `<filter>` 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<CommandSpec> {
"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<CommandSpec> {
"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<String> {
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>, 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<Option<&'static str>> {
let key = "threeDType";
@@ -722,6 +735,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
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<NodeId>) -> 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
})
+44
View File
@@ -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();
+5 -3
View File
@@ -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<String>, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool, levels: u32) -> bool {
@@ -894,7 +894,9 @@ fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet<String>, 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))
}
+4 -2
View File
@@ -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;
+2 -2
View File
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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.<id>\" (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 o Line truncated
"{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.<id>\" (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 artwor Line truncated
always,
load::open
),
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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.<plug-in id>; 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.<plug-in id>; 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
),
+1 -7
View File
@@ -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",
+10 -2
View File
@@ -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",
+4 -2
View File
@@ -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)))
+18 -2
View File
@@ -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<vectorcraft_geom::PathData>,
}
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<Loaded>
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<Loaded>
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<u8>, 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<Document> {
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;
+7
View File
@@ -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<String>)> {
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<String>)> {
let p = vectorcraft_metafile::import_pict(bytes).map_err(super::err)?;
Ok((p.document, p.warnings))
}
+6 -5
View File
@@ -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()
+104
View File
@@ -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<u8> {
let words = |v: &[i16]| v.iter().flat_map(|x| x.to_be_bytes()).collect::<Vec<u8>>();
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());
}
+3 -2
View File
@@ -76,12 +76,13 @@ pub(crate) fn see_through_images(doc: &Document) -> BTreeSet<String> {
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<String>) -> 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))),
}
}
+2 -1
View File
@@ -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;
}
+446 -40
View File
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Item = &Paint> {
[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<Item = &'a Paint> {
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<Item = &str> {
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<Value> {
}
/// 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<Value> {
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<NodeId> = masked.into_iter().collect();
if !found.symbols.is_empty() || !found.patterns.is_empty() || !masked.is_empty() {
let texts: HashSet<NodeId> = 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<Value> {
}
}
/// 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<String> =
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<String, Option<Rect>> = 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<Value> {
let db = vectorcraft_text::FontDb::global();
#[cfg(not(target_arch = "wasm32"))]
@@ -1076,7 +1174,9 @@ pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> {
#[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<Value> {
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::<Vec<_>>()
};
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::<Vec<_>>()
};
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::<Vec<_>>();
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::<Vec<_>>()
};
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()
+314 -54
View File
@@ -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<CommandSpec> {
vec![
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<CommandSpec> {
"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<CommandSpec> {
"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<CommandSpec> {
"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<NodeId>,
/// Placed documents: what they show.
document: Option<Shown>,
/// An image placed from a DCS file: the plate files of their own its plates were read from.
plate_files: Vec<vectorcraft_doc::separated::PlateFile>,
}
/// 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<Shown>)> {
}
}
/// 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<u64>)> {
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<String> = 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<Group> {
let wanted: Option<std::collections::HashSet<NodeId>> = ids.map(|ids| ids.iter().copied().collect());
let mut add = |link: &LinkInfo, key: &str, document: Option<Shown>, id: Option<NodeId>| {
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<craft_docpath::Ref
}
/// Where the file of group `g` (of a document looking from `base`) is and whether it still has
/// the content shown. Its bytes are read only when its size or modification time changed.
/// the content shown. Its bytes are read only when its size or modification time changed. An image
/// placed from a DCS file is modified when one of its plate files of their own changed.
fn probe(g: &Group, base: LinkBase) -> (Status, Option<Found>) {
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<Found>) {
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<RasterImage> {
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<RasterImage> {
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<Clip>,
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<Clip>),
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<Node>)> = 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<Node>, 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<Node>, 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<Vec<NodeId>>, path: Option<&str>) -
}
}
let updated: Vec<u64> = 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<Item = &'a Read>) -> Vec<String> {
let mut out: Vec<String> = 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(&note) {
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<Value> {
}
}
// 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<Value> {
}
}
let relinked: Vec<u64> = 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<NodeId, (Status, Option
/// The format of the file image `im` of `d` shows: its link's extension, else its pixels' type.
fn format_label(d: &Document, im: &ImageObject) -> &'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<NodeId> {
/// 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<Rect>) {
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<Value> {
const C: &str = "links.list";
let st = s.doc()?;
@@ -1737,6 +1981,7 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Value> {
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<Value> {
}
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<Value> {
};
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))?;
+1 -1
View File
@@ -290,7 +290,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
+39 -6
View File
@@ -122,9 +122,14 @@ fn with_mesh<T>(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<T>(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
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<T>(k: &mut NodeKind, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
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<T>(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<Value> {
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::<Vec<_>>());
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 }))
}
+22 -7
View File
@@ -115,7 +115,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Vec<u8>>,
@@ -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<Node>, p: &Value, cmd: &str, inks: bool) -> Result<Rasterized> {
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<Node>, 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<Vec<u8>, 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<Value> {
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) =
+35 -11
View File
@@ -798,9 +798,9 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
};
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<Value> {
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<Value> {
/// 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<String>,
}
/// The New Document profiles' names: the built-in categories, in tab order.
pub fn profile_names() -> impl Iterator<Item = &'static str> {
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<Option<Document>, String> {
fn read_profile(&self, name: &str) -> std::result::Result<Option<ReadProfile>, 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 }))
}
}
+30 -7
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Vec<NodeId>, 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<GraySource> {
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`]?
+11 -2
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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 Line truncated
"{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 tent Line truncated
has_doc,
set_format
),
@@ -622,7 +622,16 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
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") {
+64 -19
View File
@@ -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 <filter> 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<Value> {
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
+6 -1
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Value> {
/// 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<Value> {
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<Value> {
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<Value> {
};
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);
}
+94 -61
View File
@@ -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<CommandSpec> {
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<CommandSpec> {
"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<Strin
Ok(pe.pattern)
}
/// Leave pattern editing mode, discarding the changes (`object.pattern.cancel`). An existing
/// pattern gets its definition back, its name included when Pattern Options renamed it while it was
/// edited and no other pattern, swatch or color group has taken that name since. A new pattern is
/// removed with its swatches, and every paint of it left in the document and in the fill, stroke
/// and appearance new art takes becomes no paint ([`forget_pattern`]).
fn pattern_cancel(s: &mut Session, _: &Value) -> Result<Value> {
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<Paint> + '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<Value> {
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<Value> {
}
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<NodeId> {
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<Value> {
@@ -604,29 +658,8 @@ fn pattern_delete(s: &mut Session, p: &Value) -> Result<Value> {
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 }))
}
+74 -15
View File
@@ -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<CommandSpec> {
"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<CommandSpec> {
"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<dcs::DcsArt>),
Vector {
/// The loaded document: the source of the art's resources.
src: Box<Document>,
@@ -205,6 +210,15 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
));
}
let crop = opts.crop != CropTo::Bounding;
// A DCS file stays linked to its file, which its plates print from; its parameters are checked
// as an EPS file's are.
if dcs::is_dcs(&src.bytes) {
let path = src.path.filter(|_| bool_or(p, "link", true)).map(fileio::absolute_path).ok_or_else(|| bad(cmd, dcs::LINK_ONLY))?;
let a = dcs::read(&src.bytes, Some(&path)).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
let link = super::links::link_info(&path, &src.bytes);
let (natural, warnings) = (a.page, a.warnings.clone());
return Ok(Loaded { name, format, art: Art::Dcs(Box::new(a)), natural, warnings, link: Some(link), board: None });
}
// A VectorCraft document: placed linked from its file, else as an editable copy.
if matches!(format.id, "vectorcraft" | "template") {
let page = page as u32;
@@ -408,6 +422,21 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> 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<PlaceRead> {
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<Value> {
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<Value> {
}
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<Value>) -> Result<QueueRead> {
// 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<Value> {
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<String> = 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)?);
}
+6
View File
@@ -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));
}
});
}
+132
View File
@@ -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<Node>,
/// The spot plates' inks and their process equivalents.
pub spots: Vec<(String, [f32; 4])>,
pub warnings: Vec<String>,
}
/// 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<DcsArt> {
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<RasterImage> {
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<String> {
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<PlateFile>) -> std::result::Result<Vec<u8>, 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<String> {
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
}
@@ -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",
+1
View File
@@ -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),
+14 -2
View File
@@ -112,6 +112,9 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Value> {
}
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<Value> {
}
let areas: Vec<Rect> = 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 }))
}
+343 -44
View File
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Vec<Color>>,
}
/// 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<Color>, Vec<ImageRead<'a>>, Option<usize>);
/// 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<Vec<Region>>,
/// The colours of the patterns read so far, and the patterns whose tiles are being read.
pattern_colors: HashMap<String, (Vec<Color>, Vec<ImageRead<'a>>)>,
/// 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<String, PatternRead<'a>>,
pattern_stack: Vec<String>,
/// Whether art was left out for passing [`MAX_THEME_DEPTH`].
cut: bool,
/// The region tests [`Self::shows`] has made.
work: std::cell::Cell<usize>,
/// 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<NodeId>,
/// 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<Box<dyn Fn(f64, f64) -> 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<dyn Fn(f64, f64) -> 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::<usize>())).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<Rect>, 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<Color> = 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<Color> = 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<Color> {
/// 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<Color> {
let mut out = vec![];
let mut patterns: Vec<String> = 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<Color> = 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<Value> {
.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<Node> {
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<Node>>) -> Arc<Node> {
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<Node> {
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");
}
}
+281
View File
@@ -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<CommandSpec> {
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<CommandSpec> {
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<Value> {
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<usize> {
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<String> {
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<NodeId, String> {
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<Value, String> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<char> = 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<Item = char> {
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 {
+66 -26
View File
@@ -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<CommandSpec> {
"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<Brush>, 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::<usize>();
*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::<usize>();
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<Brush>, 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<Value> {
let colors: HashSet<ColorKey> = colors.iter().filter_map(color_key).collect();
let patterns: HashSet<&String> = patterns.iter().collect();
let gradients: HashSet<GradientKey> = 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<String> =
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()),
@@ -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();
+26 -10
View File
@@ -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<CommandSpec> {
"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<CommandSpec> {
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<Value> {
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) {
+2 -1
View File
@@ -27,7 +27,8 @@ pub struct HistoryEntry {
pub(crate) named: Option<NamedStep>,
/// 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,
+5 -3
View File
@@ -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<Vec<(Vec<u64>, Option<usize>)>>,
/// 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<u64>,
/// The composite fonts (lowercase names) that the open documents defined when the font
/// database was last brought in step with them ([`cmd::compositefonts::sync`]).
+3 -1
View File
@@ -184,7 +184,9 @@ impl Session {
if changed.is_empty() {
return Ok(none());
}
let ids: Vec<u64> = 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<u64> = 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" => {
+4
View File
@@ -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,
+25 -1
View File
@@ -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.
+10 -2
View File
@@ -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(())
}
+2
View File
@@ -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;
+136 -1
View File
@@ -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<Vec<u64>, 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.
+86
View File
@@ -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<Point> {
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();
+43
View File
@@ -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();
+116
View File
@@ -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<u8> {
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("<image") && svg.contains("stroke-width=\"8\""), "{svg}");
let back = vectorcraft_pdf::import(&vectorcraft_pdf::export(&doc, &Default::default()).unwrap()).unwrap();
let mut outlines = 0;
for l in &back.layers {
l.walk(&mut |n| {
let stroked = (n.appearance.stroke_width() - 8.0).abs() < 0.01;
outlines += usize::from(matches!(n.kind, NodeKind::Path { .. }) && stroked && n.geometric_bounds().is_some_and(disc));
});
}
assert_eq!(outlines, 1);
// Expand Appearance leaves the disc's outline below the image.
run(&mut s, "effect.expandAppearance", json!({}));
let n = node(&s, im);
let kids = n.children().unwrap();
assert!(kids.len() == 2 && matches!(kids[1].kind, NodeKind::Image(_)), "{n:?}");
assert!(disc(kids[0].geometric_bounds().unwrap()), "{:?}", kids[0].geometric_bounds());
run(&mut s, "edit.undo", json!({}));
// An Offset Path of 3 pt after Outline Object moves the stroke 3 pt out: it shows from 63 to 70.
run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 3}, "item": 0}));
assert_eq!([shade(&s, 61, 100), shade(&s, 64, 100)], ["white", "black"]);
// Relinked to an opaque image, the stroke follows the frame 3 pt out: it shows from 43 to 50.
let dir = vectorcraft_testkit::temp_dir("outline-object-relink");
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("opaque.png");
let mut png = vec![];
image::RgbaImage::from_pixel(100, 100, image::Rgba([255, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
std::fs::write(&path, png).unwrap();
run(&mut s, "links.relink", json!({"ids": [im.0], "path": path}));
assert_eq!([shade(&s, 41, 100), shade(&s, 45, 100), shade(&s, 64, 100)], ["white", "black", "red"]);
}
#[test]
fn an_images_outline_object_stroke_exports_selects_and_measures_along_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": 20, "color": "#000000"}));
run(&mut s, "effect.apply", json!({"effect": "path.outlineObject", "item": 0}));
// EPS and the PDF-compatible .ai draw the disc's outline stroked 20 pt, 20 pt inside the
// image's frame on each side (EPS moves the art to its bounding box).
let disc_outlines = |d: &vectorcraft_doc::Document| {
let mut frame = None;
d.walk(|c| {
if matches!(c.kind, NodeKind::Image(_)) {
frame = c.geometric_bounds();
}
});
let f = frame.unwrap();
let mut n = 0;
d.walk(|c| {
let disc = |b: vectorcraft_geom::Rect| {
[b.x0 - f.x0 - 20.0, b.y0 - f.y0 - 20.0, f.x1 - b.x1 - 20.0, f.y1 - b.y1 - 20.0].iter().all(|d| d.abs() < 0.6)
};
let stroked = (c.appearance.stroke_width() - 20.0).abs() < 0.01;
n += usize::from(matches!(c.kind, NodeKind::Path { .. }) && stroked && c.geometric_bounds().is_some_and(disc));
});
n
};
let saved = |s: &mut Session, p: Value| vectorcraft_format::base64_decode(run(s, "file.saveCopy", p)["dataBase64"].as_str().unwrap()).unwrap();
let eps = saved(&mut s, json!({"format": "eps", "previewFormat": "none", "thumbnails": false}));
assert_eq!(disc_outlines(&vectorcraft_eps::import_with(&eps, false).unwrap().document), 1);
let ai = saved(&mut s, json!({"format": "ai"}));
assert_eq!(disc_outlines(&crate::cmd::fileio::page_document(&ai, 0, &Default::default()).unwrap().0), 1);
// An Offset Path of 30 pt after Outline Object: the stroke runs round a circle of radius 60,
// from 30 to 50 on the left, where along the frame it would run from 10 to 30.
run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 30}, "item": 0}));
assert_eq!((pixel(&s, 35, 100), pixel(&s, 15, 100)), ([0, 0, 0, 255], [255; 4]));
run(&mut s, "select.none", json!({}));
assert_eq!(click(&mut s, 35.0, 100.0), [im]);
run(&mut s, "select.none", json!({}));
assert!(click(&mut s, 15.0, 100.0).is_empty());
// Use Preview Bounds measures the stroke round the circle.
s.prefs.use_preview_bounds = true;
let b = s.transform_bounds(&[im]).unwrap();
assert!([b.x0 - 30.0, b.y0 - 30.0, b.x1 - 170.0, b.y1 - 170.0].iter().all(|d| d.abs() < 1.0), "{b:?}");
}
/// Click with the Selection tool at (x, y) on a 100% view: what is selected afterwards.
fn click(s: &mut Session, x: f64, y: f64) -> Vec<NodeId> {
let v = ViewInfo::default();
+697
View File
@@ -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<u8> {
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<u8> {
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::<Vec<_>>(), ["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<String> = 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<f64> {
fn find(n: &Node) -> Option<Option<f64>> {
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());
}
+8
View File
@@ -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]
+23
View File
@@ -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.
+296
View File
@@ -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();
+41
View File
@@ -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]
+56
View File
@@ -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");
+99
View File
@@ -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, &params).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
+362 -1
View File
@@ -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::<Paint>(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<Paint> {
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<Paint> = [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();
+8
View File
@@ -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"}));
+29
View File
@@ -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<String> { 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();
+47
View File
@@ -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");
}
}
+202
View File
@@ -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<u64> {
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());
}
+26
View File
@@ -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<serde_json::Value> = 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]
Loaded 100 of 257 files, more files were not shown because too many files have changed in this diff. Show more