Merge remote-tracking branch 'upstream/main' into fine-nudge-5258

# Conflicts:
#	docs/ui-parity.md
This commit is contained in:
ljkx
2026-11-13 04:30:36 +01:00
237 changed files with 17123 additions and 1117 deletions
+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 {
+115
View File
@@ -485,6 +485,88 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec<Vec<usize>> {
rows
}
/// The distinct colors [`theme_palette`] clusters, at most.
const THEME_CANDIDATES: usize = 4096;
/// The color palette of the weighted colors `samples` (color, weight), for Recolor Artwork's Color
/// Theme Picker: at most `n` colors. The same color given twice counts once with both weights,
/// and past [`THEME_CANDIDATES`] distinct colors, colors close in Lab merge into the heaviest of
/// them first.
/// The colors are grouped as [`cluster`] groups them, each group shows its heaviest color (a color
/// of `samples`, in its own model; on a tie the one given first), and the heaviest group comes
/// first (on a tie the group whose first color was given first). Samples without a positive,
/// finite weight are left out, so no samples give no colors.
pub fn theme_palette(samples: &[(Color, f32)], n: usize) -> Vec<Color> {
let mut index: std::collections::HashMap<ColorKey, usize> = std::collections::HashMap::new();
let mut colors: Vec<Color> = vec![];
let mut weights: Vec<f32> = vec![];
for (c, w) in samples {
if !(w.is_finite() && *w > 0.0) {
continue;
}
let i = *index.entry(ColorKey::of(c)).or_insert_with(|| {
colors.push(*c);
weights.push(0.0);
colors.len() - 1
});
weights[i] += w;
}
if colors.is_empty() || n == 0 {
return vec![];
}
// At most THEME_CANDIDATES colors are clustered: past that, colors in the same cube of Lab
// space merge into the heaviest of them, the cubes doubling in size until few enough remain.
if colors.len() > THEME_CANDIDATES {
let labs: Vec<[f32; 3]> = colors
.iter()
.map(|c| {
let l = c.to_lab();
[l.l, l.a, l.b]
})
.collect();
let mut side = 2.0f32;
loop {
let mut cube: std::collections::HashMap<[i32; 3], usize> = std::collections::HashMap::new();
let (mut top, mut sum): (Vec<usize>, Vec<f32>) = (vec![], vec![]);
for (i, lab) in labs.iter().enumerate() {
let k = lab.map(|v| (v / side).floor() as i32);
match cube.get(&k) {
Some(&j) => {
sum[j] += weights[i];
if weights[i] > weights[top[j]] {
top[j] = i;
}
}
None => {
cube.insert(k, top.len());
top.push(i);
sum.push(weights[i]);
}
}
}
if top.len() <= THEME_CANDIDATES {
colors = top.iter().map(|&i| colors[i]).collect();
weights = sum;
break;
}
side *= 2.0;
}
}
let mut groups: Vec<(f32, usize, Color)> = cluster(&colors, &weights, n)
.into_iter()
.filter_map(|g| {
let total: f32 = g.iter().map(|&i| weights[i]).sum();
let top = g.iter().copied().fold(None::<usize>, |best, i| match best {
Some(b) if weights[b] >= weights[i] => Some(b),
_ => Some(i),
})?;
Some((total, *g.first()?, colors[top]))
})
.collect();
groups.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
groups.into_iter().map(|g| g.2).collect()
}
/// A set of colours to snap to (Limit to Library), with their Lab values cached.
#[derive(Clone, Debug, Default)]
pub struct Palette(Vec<(Color, Lab)>);
@@ -691,6 +773,39 @@ mod tests {
assert!(cluster(&[], &[], 3).is_empty());
}
/// The Color Theme Picker's palette: similar colors merge, each group shows its heaviest
/// color in its own model, and the heaviest group comes first.
#[test]
fn theme_palette_takes_the_heaviest_color_of_each_group_heaviest_first() {
let red = Color::rgb(1.0, 0.0, 0.0);
let pink = Color::rgb(1.0, 0.2, 0.2);
let blue = Color::cmyk(1.0, 0.8, 0.0, 0.0);
let navy = Color::cmyk(1.0, 0.9, 0.0, 0.3);
let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 2.5), (red, 0.5)];
// Blue and navy weigh 4.5, and so do red (3 + 0.5, its two samples add up) and pink.
assert_eq!(theme_palette(&samples, 2), vec![red, navy], "a tie: the group given first");
let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 1.0)];
assert_eq!(theme_palette(&samples, 2), vec![red, blue], "heaviest group first, its heaviest color");
assert_eq!(theme_palette(&samples, 9).len(), 4, "never more colors than given");
assert_eq!(theme_palette(&samples, 1), vec![red]);
assert!(theme_palette(&samples, 0).is_empty());
assert!(theme_palette(&[(red, 0.0), (blue, f32::NAN), (pink, -1.0)], 3).is_empty(), "no weight, no colors");
assert!(theme_palette(&[], 3).is_empty());
}
/// Past 4,096 distinct colors, close colors merge before clustering: the palette still keeps
/// a heavy color apart from thousands of light ones.
#[test]
fn theme_palette_merges_close_colors_past_its_candidate_limit() {
let mut samples: Vec<(Color, f32)> = (0..20_000).map(|i| (Color::rgb(0.0, 0.0, 0.3 + 0.7 * i as f32 / 20_000.0), 0.001)).collect();
samples.extend((0..20_000).map(|i| (Color::rgb(1.0, 0.8 * i as f32 / 20_000.0, 0.0), 0.0001)));
samples.push((Color::rgb(0.0, 1.0, 0.0), 50.0));
let p = theme_palette(&samples, 3);
assert_eq!(p.len(), 3);
assert_eq!(p[0], Color::rgb(0.0, 1.0, 0.0), "the heavy green first, exactly as given");
assert!(p[1].to_hsb()[0] > 180.0 && p[2].to_hsb()[0] < 90.0, "then the blues, then the reds and oranges: {p:?}");
}
#[test]
fn hue_shift_with_own_model_puts_every_colour_of_the_row_in_the_new_model() {
let to = Color::cmyk(0.0, 1.0, 1.0, 0.0);
+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")
}
}
+3 -3
View File
@@ -569,7 +569,7 @@ fn clip_contains(clip: &Node, p: Point) -> bool {
/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in
/// [`clip_contains`].
fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
let frame = |n: &Node| {
let b = n.geometric_bounds()?;
Some(Node::path(n.id, vectorcraft_geom::shapes::rectangle(b), Default::default()))
@@ -640,7 +640,7 @@ fn source_of(n: &Node, scope: Option<NodeId>) -> bool {
/// Do clicks and marquees skip the child `i` of `parent` with `scope` isolated? For a Shaper
/// Group that is its original shapes (its first child), or, in Construction mode, when they are
/// isolated, the art the group shows.
fn shaper_hides(parent: &Node, i: usize, scope: Option<NodeId>) -> bool {
pub fn shaper_hides(parent: &Node, i: usize, scope: Option<NodeId>) -> bool {
parent.extras().shaper.is_some() && (i == 0) != source_of(parent, scope)
}
@@ -1356,7 +1356,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
/// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None
/// when the marquee misses it); otherwise it is all of `r`.
fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
pub fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
match parent.children().and_then(|c| c.first()) {
Some(clip) if parent.clips() => marquee_in_clip(clip, r),
_ => Some(r),
+2 -1
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;
@@ -51,7 +52,7 @@ pub mod overprint;
pub mod pattern;
pub mod perspective;
mod pixels;
pub use pixels::{GraySource, MAX_RASTER_ALLOC};
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick};
pub mod placed_document;
pub mod plugin_data;
pub mod profiles;
+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
+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,
+74
View File
@@ -11,6 +11,10 @@ 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), 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
/// the header first: the decoder's limit is on the file's samples, and a gray image is a quarter
@@ -61,6 +65,49 @@ impl ImageBlob {
Some(Self::png(png))
}
/// 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, 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));
let span = |a: f64, b: f64, n: f64| {
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]>, 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);
if x0 >= x1 || y0 >= y1 {
return vec![];
}
// Rows and columns in proportion to the box, at most `budget` cells in all.
let (bw, bh, budget) = (f64::from(x1 - x0), f64::from(y1 - y0), budget.max(1) as f64);
let (sx, sy) = if bw * bh <= budget {
(1, 1)
} else {
let rows = (budget * bh / bw).sqrt().floor().clamp(1.0, bh.min(budget));
let cols = (budget / rows).floor().clamp(1.0, bw);
((bw / cols).ceil() as usize, (bh / rows).ceil() as usize)
};
let mut out = vec![];
for y in (y0..y1).step_by(sy) {
for x in (x0..x1).step_by(sx) {
if keep((f64::from(x) + 0.5) / fw, (f64::from(y) + 0.5) / fh) {
out.push(img.get_pixel(x, y).0);
}
}
}
out
};
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
/// the PNG has an alpha channel only when some pixel isn't opaque. `f` runs once per distinct
/// color. `None` when the image can't be decoded, or when its file stores grayscale already
@@ -276,6 +323,33 @@ mod tests {
image::load_from_memory(&b.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
}
/// Sampling reads the pixels of a box of the image, spread to about the budget, and only those
/// whose centres `keep` takes.
#[test]
fn sampled_pixels_stay_in_their_box_and_budget() {
// 4 × 2: a red left half and a blue right half.
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, 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");
assert!(one(&img, Some([2.0, 0.0, 3.0, 1.0]), 100).is_empty(), "outside the image");
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, 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, 100, &any)]).is_none());
}
/// A GIF whose `w` × `h` screen holds one opaque red pixel at the top left. The file holds no
/// other pixels, and the decoder makes them transparent.
fn gif_with_one_red_pixel(w: u16, h: u16) -> Vec<u8> {
+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"))));
+1 -1
View File
@@ -17,7 +17,7 @@ mod wrap;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
use char_style::yes;
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, ScriptMetrics};
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, ScriptMetrics};
pub use composite::{
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
CompositeParts,
+20 -1
View File
@@ -34,6 +34,16 @@ pub struct CharStyle {
/// before it whose [`Self::kerning`] could space it. Elsewhere it has no effect.
#[serde(default, rename = "kerningBefore", skip_serializing_if = "crate::skip::is_default")]
pub kerning_before: f64,
/// Insert Aki Left (Character panel, East Asian options): space added before the character in
/// reading order, in 1/1000 em as [`Self::tracking`], 0 to 1000. Before is on the left in
/// left-to-right type, on the right in right-to-left type and above in vertical type. A
/// cluster takes the value of its first character, and full justification leaves it as it is.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, rename = "akiLeft", skip_serializing_if = "crate::skip::is_default")]
pub aki_left: f64,
/// Insert Aki Right: space added after the character in reading order, as [`Self::aki_left`].
#[serde(default, rename = "akiRight", skip_serializing_if = "crate::skip::is_default")]
pub aki_right: f64,
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
#[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")]
pub optical_kerning: bool,
@@ -404,6 +414,9 @@ fn hundred() -> f64 {
100.0
}
/// The largest Insert Aki Left or Right ([`CharStyle::aki_left`]), in 1/1000 em: one em.
pub const MAX_AKI: f64 = 1000.0;
pub(super) fn yes() -> bool {
true
}
@@ -420,6 +433,8 @@ impl Default for CharStyle {
tracking: 0.0,
kerning: None,
kerning_before: 0.0,
aki_left: 0.0,
aki_right: 0.0,
optical_kerning: false,
baseline_shift: 0.0,
h_scale: 100.0,
@@ -468,7 +483,8 @@ impl CharStyle {
/// becomes Auto, and a value past [`crate::MAX_COORD`] (a baseline shift past it either way)
/// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a
/// baseline shift that is not a number becomes 0. The Tate-chu-yoko Up/Down and Left/Right
/// offsets are kept as the baseline shift is.
/// offsets are kept as the baseline shift is. Insert Aki Left and Right are kept from 0 to
/// [`MAX_AKI`], and one that is not a number becomes 0.
pub fn keep_dimensions_in_range(&mut self) {
let default = Self::default();
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
@@ -480,6 +496,9 @@ impl CharStyle {
self.baseline_shift = shift(self.baseline_shift);
self.tcy_up_down = shift(self.tcy_up_down);
self.tcy_left_right = shift(self.tcy_left_right);
let aki = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) };
self.aki_left = aki(self.aki_left);
self.aki_right = aki(self.aki_right);
}
/// Do the characters draw a stroke (a paint and a positive weight)?
pub fn has_stroke(&self) -> bool {
+4
View File
@@ -490,6 +490,8 @@ impl crate::Document {
st.baseline_shift = num("baseline_shift").unwrap_or(st.baseline_shift);
st.tcy_up_down = num("tcyUpDown").unwrap_or(st.tcy_up_down);
st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right);
st.aki_left = num("akiLeft").unwrap_or(st.aki_left);
st.aki_right = num("akiRight").unwrap_or(st.aki_right);
st.keep_dimensions_in_range();
let kept = [
("size", Some(st.size)),
@@ -498,6 +500,8 @@ impl crate::Document {
("baseline_shift", Some(st.baseline_shift)),
("tcyUpDown", Some(st.tcy_up_down)),
("tcyLeftRight", Some(st.tcy_left_right)),
("akiLeft", Some(st.aki_left)),
("akiRight", Some(st.aki_right)),
("leading", st.leading),
];
for (k, v) in kept {
+3 -1
View File
@@ -357,7 +357,7 @@ impl ParaList {
/// The style the marker is set in: `first` (the style of the paragraph's first character)
/// without its baseline shift, rotation, superscript or subscript, tracking, manual kerning,
/// tate-chu-yoko, underline and strikethrough.
/// Insert Aki, tate-chu-yoko, underline and strikethrough.
pub fn marker_style(first: &CharStyle) -> CharStyle {
CharStyle {
baseline_shift: 0.0,
@@ -366,6 +366,8 @@ impl ParaList {
tracking: 0.0,
kerning: None,
kerning_before: 0.0,
aki_left: 0.0,
aki_right: 0.0,
optical_kerning: first.optical_kerning,
tate_chu_yoko: false,
underline: false,
+37
View File
@@ -92,6 +92,43 @@ fn font_height_reference_is_saved_only_when_not_the_em_box() {
assert_eq!(serde_json::from_value::<CharStyle>(old).unwrap().font_height_reference, FontHeightReference::EmBox);
}
/// Insert Aki Left and Right are 0 by default and saved only when not 0, each side on its own;
/// styles written before them read as 0, and a value out of range from a file is kept from 0 to one
/// em.
#[test]
fn insert_aki_is_saved_only_when_set() {
let st = CharStyle::default();
assert_eq!((st.aki_left, st.aki_right), (0.0, 0.0));
let saved = serde_json::to_value(&st).unwrap();
assert!(saved.get("akiLeft").is_none() && saved.get("akiRight").is_none());
for set in [
CharStyle { aki_left: 250.0, ..CharStyle::default() },
CharStyle { aki_right: 500.0, ..CharStyle::default() },
CharStyle { aki_left: 125.5, aki_right: 1000.0, ..CharStyle::default() },
] {
let saved = serde_json::to_value(&set).unwrap();
assert_eq!(saved.get("akiLeft").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_left);
assert_eq!(saved.get("akiRight").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_right);
assert_eq!(saved.get("akiLeft").is_some(), set.aki_left != 0.0);
assert_eq!(serde_json::from_value::<CharStyle>(saved).unwrap(), set);
}
let old = serde_json::to_value(&st).unwrap();
let read = serde_json::from_value::<CharStyle>(old).unwrap();
assert_eq!((read.aki_left, read.aki_right), (0.0, 0.0));
let mut damaged = CharStyle { aki_left: -20.0, aki_right: 4000.0, ..CharStyle::default() };
damaged.keep_dimensions_in_range();
assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI));
let mut damaged = CharStyle { aki_left: f64::NAN, aki_right: f64::INFINITY, ..CharStyle::default() };
damaged.keep_dimensions_in_range();
assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI));
// A character style from a file is kept in range the same way.
let mut d = crate::Document::new(100.0, 100.0);
let attrs = serde_json::json!({"akiLeft": 5000, "akiRight": -1});
d.char_styles.push(TextStyleDef { name: "Spaced".into(), attrs: attrs.as_object().cloned().unwrap_or_default() });
d.keep_type_values_in_range();
assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0)));
}
/// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its
/// script's block; every system saves under its id, which reads back, and other names are refused.
#[test]
+2
View File
@@ -26,3 +26,5 @@ serde_json = { workspace = true }
[dev-dependencies]
vectorcraft-color = { workspace = true }
# A face built in code from the bundled Source Sans 3 (no font file is committed).
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
+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)
+4 -4
View File
@@ -189,8 +189,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
EXTRUDE,
"Extrude & Bevel…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}),
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}),
),
g(
INFLATE,
@@ -203,8 +203,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
ROTATE,
"Rotate…",
&["Effect", "3D and Materials"],
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}),
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}),
),
g(
CLASSIC_EXTRUDE,
+1 -1
View File
@@ -689,7 +689,7 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
}
/// A path node of `id` on `path` (filled under `rule`) painted by `ap`.
fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node {
pub(crate) fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node {
let mut n = Node::path(id, path, ap);
if let NodeKind::Path { rule: r, .. } = &mut n.kind {
*r = rule;
+10 -4
View File
@@ -87,15 +87,21 @@ pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
};
pub use solids::{
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES,
classic_extrude_options, classic_shading, extrude_options, has_solid, inflate_options, is_classic_three_d, is_three_d, solid_art, solid_art_in,
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid,
validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, ROTATE, ROTATE_SURFACES,
ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds,
graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, solid_art, solid_art_in, takes_graphics, three_d_meshes,
three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in,
validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after, rename_appearance_graphic_symbol,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
pub use trap::TRAP;
pub use vectorcraft_three_d::Mesh;
pub use vectorcraft_three_d::PlanarFace;
pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version};
mod catalog;
+139 -8
View File
@@ -130,19 +130,142 @@ pub fn has_painted_effects(n: &Node) -> bool {
}
/// Is `n` type without inline graphics that has a fill or stroke of its own that paints and has a
/// visible geometry effect, or an image with a fill or stroke of its own that paints a shape
/// ([`image_rows`])? On type, such an effect reshapes the whole outline that its fill or stroke
/// paints ([`outline_text`], which leaves inline graphics out).
/// visible geometry effect, an image with a fill or stroke of its own that paints a shape
/// ([`image_rows`]), or a symbol instance whose active fill or stroke has a visible geometry effect
/// ([`active_fill`], [`active_stroke`])? On type, such an effect reshapes the whole outline that its
/// fill or stroke paints ([`outline_text`], which leaves inline graphics out). On a symbol
/// instance, it reshapes the fills or strokes of the art it places ([`add_instance_row_effects`]).
pub fn has_item_geometry(n: &Node) -> bool {
match &n.kind {
NodeKind::Text(t) => {
t.runs.iter().all(|r| r.inline.is_none()) && n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects()))
}
NodeKind::Image(_) => n.appearance.items.iter().any(shapes_image),
NodeKind::SymbolInstance { .. } => {
active_fill(n).is_some_and(|f| crate::has_geometry(&f.effects)) || active_stroke(n).is_some_and(|s| crate::has_geometry(&s.effects))
}
_ => false,
}
}
/// The fill of symbol instance `n` whose effects its art takes: its topmost fill, the one that
/// stains the art, when it is visible and its opacity is above 0. A lower fill's effects do not
/// reach the art.
fn active_fill(n: &Node) -> Option<&vectorcraft_doc::FillLayer> {
n.appearance.fill().filter(|f| f.visible && f.opacity > 0.0)
}
/// The stroke of symbol instance `n` whose effects its art takes: its topmost stroke, when it is
/// visible and its opacity is above 0.
fn active_stroke(n: &Node) -> Option<&vectorcraft_doc::StrokeLayer> {
n.appearance.stroke().filter(|s| s.visible && s.opacity > 0.0)
}
/// The visible geometry effects in `fx`, in order.
fn geometry_of(fx: &[Effect]) -> Vec<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 {
@@ -302,7 +425,9 @@ fn with_id(art: &Node, id: NodeId) -> Node {
/// `n` as plain art that geometry effects can reshape, without its transparency and object
/// effects: type outlined ([`outline_text`]), live objects evaluated (type inside them outlined),
/// a symbol instance as `symbol_art` (the symbol's art, stained as the caller draws it) placed by
/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them).
/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them), its
/// fills and strokes carrying the geometry effects of the instance's active fill and stroke
/// ([`add_instance_row_effects`]).
/// `None` for other kinds (images, paths, containers), and for an instance whose art placed
/// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of
/// `doc`'s symbols that its instances show toward its instance budget.
@@ -351,6 +476,9 @@ fn outline_art_with(
_ => return None,
};
outline_nested_text(paint_doc, &mut art, false);
if matches!(n.kind, NodeKind::SymbolInstance { .. }) {
add_instance_row_effects(symbols, n, &mut art);
}
art.opacity = 1.0;
art.blend = Default::default();
art.isolate = false;
@@ -497,8 +625,10 @@ pub fn reshape(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> O
/// `n` (see [`needs_outline`], or a path with [`has_transform_art`]) as plain art for Expand
/// Appearance: [`reshape`]d when it has
/// geometry effects, else type with fills or strokes of its own outlined, or an image with fills
/// or strokes of its own that paint a shape, in the same form. `None` when it has none of these.
/// geometry effects, else type with fills or strokes of its own outlined, an image with fills or
/// strokes of its own that paint a shape, or a symbol instance's art reshaped by the geometry
/// effects of its active fill or stroke ([`has_item_geometry`]), in the same form. `None` when it
/// has none of these.
pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<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 +682,13 @@ fn as_art_opts(
NodeKind::Image(im) => {
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
let mut image = Node::new(n.id, n.kind.clone());
// Its pixels draw as the image's do: colorized by a grayscale image's fill color, and
// smoothed or not.
// Its pixels draw as the image's do: colorized by a grayscale image's fill color,
// smoothed or not, and with its color mask's masked pixels.
{
let mut e = image.extras_mut();
e.colorize = n.extras().colorize.clone();
e.pixelated = n.extras().pixelated;
e.color_mask = n.extras().color_mask.clone();
}
let clipped = || {
let mut clip = Node::path(n.id, frame.clone(), Appearance::default());
+55 -6
View File
@@ -594,7 +594,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
if is_container(n) {
return group_art(n, expand);
}
let (path, _) = profile(n)?;
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
let mut children = vec![];
let mut copies = 0;
@@ -620,15 +620,17 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let path = geometry(&path, &n.appearance.effects, &ctx);
remaining = crate::without_geometry(&remaining);
// The object's Transform effects, applied to the path above, transform the items' raster
// effects too.
let mut items: Vec<AppearanceItem> = n.appearance.items.iter().filter(|i| crate::paints(i)).cloned().collect();
// effects too. Each copy keeps its item beside it, which plug-in effects are told they sit
// on.
let originals: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| crate::paints(i)).collect();
let mut items: Vec<AppearanceItem> = originals.iter().map(|i| (*i).clone()).collect();
crate::raster::follow_paints(&mut items, &n.appearance.effects);
// Every item's shadow goes behind every item's art.
let mut shadows = vec![];
for item in &items {
for (original, item) in originals.into_iter().zip(&items) {
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) {
let fx = item.effects().get(index)?;
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?;
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
@@ -640,7 +642,8 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
}
children.push(Arc::new(art));
} else {
children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() })));
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat)));
}
}
children.splice(0..0, shadows);
@@ -1022,6 +1025,52 @@ mod tests {
assert!(surface.children().unwrap().iter().all(|c| c.opacity == 1.0 && !has_revolve(c)));
}
#[test]
fn a_fill_without_the_revolve_keeps_the_even_odd_hole() {
use vectorcraft_geom::FillRule;
use vectorcraft_geom::hit::fill_contains;
// Two nested squares drawn in the same direction: only the even-odd rule leaves a hole.
let [outer, inner] = [(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| {
let mut b = BezPath::new();
b.move_to((lo, lo));
b.line_to((hi, lo));
b.line_to((hi, hi));
b.line_to((lo, hi));
b.close_path();
PathData::from_bezpath(&b)
});
let flat = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.1, 0.3, 0.9))));
for id in [REVOLVE, CLASSIC_REVOLVE] {
let mut top = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.8, 0.2, 0.1))));
top.effects_mut().push(crate::new_effect(id, &json!({})).unwrap());
let appearance = Appearance { items: vec![flat.clone(), top], ..Default::default() };
let members = vec![
Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())),
Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())),
];
let mut compound = Node::new(NodeId(1), NodeKind::Compound { children: members, rule: FillRule::EvenOdd });
compound.appearance = appearance.clone().into();
let both = PathData::new(outer.subpaths.iter().chain(&inner.subpaths).cloned().collect());
let path = crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance);
for (n, shape) in [(compound, "compound path"), (path, "path")] {
for (art, how) in [(revolve_art(&n), "live"), (expand_revolve_art(&n), "expanded")] {
let what = format!("{id} on the top fill of a {shape}, {how}");
let art = art.unwrap_or_else(|| panic!("{what}"));
let children = art.children().unwrap();
let plain: Vec<usize> = (0..children.len())
.filter(|&i| children[i].appearance.items == [flat.clone()] && children[i].path_data().is_some())
.collect();
let [index] = plain[..] else { panic!("{what}: one flat child, got {plain:?}") };
let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") };
assert_eq!(*rule, FillRule::EvenOdd, "{what}");
let bez = path.to_bezpath();
assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled");
assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open");
assert!(index + 1 < children.len(), "{what}: the revolved art is drawn above");
}
}
}
}
#[test]
fn export_bakes_faces_with_unique_ids_and_no_revolve_effects() {
let mut d = Document::new(300.0, 300.0);
let mut n = profile_node();
+291 -25
View File
@@ -6,7 +6,7 @@ use serde_json::Value;
use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask, StrokeLayer};
use vectorcraft_geom::{FillRule, PathData, Rect};
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View};
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, PlanarFace, View};
#[cfg(test)]
use vectorcraft_doc::color::Color;
@@ -20,6 +20,15 @@ pub use classic::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, ROTATE_SURFACES, SHADING_COLO
mod source;
pub(crate) use source::{resolve, resolve_for};
mod graphics;
pub use graphics::{
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol,
rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
};
pub use graphics::{
MAX_OFFSET as GRAPHIC_MAX_OFFSET, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, rename_appearance_graphic_symbol,
};
pub(crate) mod shadow;
pub(crate) mod wireframe;
@@ -70,6 +79,12 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
}
}
}
// A plane has only a front, so graphics on the back cap are dropped.
if to == ROTATE
&& let Some(Value::Array(list)) = out.get_mut(GRAPHICS)
{
list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id()));
}
Value::Object(out)
}
@@ -212,6 +227,7 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
}
crate::lighting::validate(p)?;
shadow::validate(p)?;
graphics::validate(id, p)?;
if let Some(v) = p.get("bevel")
&& !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some())
{
@@ -241,6 +257,9 @@ pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
/// `item`, whose shadow is cast by that item's solid alone.
fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, item: Option<usize>) -> Result<(), String> {
validate_solid_params(id, p)?;
if let Some(doc) = doc {
graphics::validate_symbols(doc, p)?;
}
let label = label_of(id);
let n = &*source::resolve_for(doc, n, label, is_plane(id))?;
if is_container(n) {
@@ -434,6 +453,7 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> {
/// [`validate_three_d`] with the symbols of `doc` ([`validate_solid_in`]).
pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> {
graphics::validate(id, p)?;
if crate::revolve::is_revolve(id) { crate::revolve::validate_in(doc, n, id, p) } else { validate_solid_in(doc, n, id, p) }
}
@@ -449,6 +469,7 @@ pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usi
/// [`validate_three_d_at`] with the symbols of `doc` ([`validate_solid_in`]). A symbol instance, a
/// blend and a clipping group take a 3D effect as groups do: on the object itself.
pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> {
graphics::validate(id, p)?;
match at {
Some(_) if is_container(n) || source::resolves(n) => {
Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into())
@@ -463,6 +484,7 @@ pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Va
/// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does
/// not need to fit.
pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
graphics::validate(id, p)?;
if crate::revolve::is_revolve(id) { crate::revolve::validate_params_of(id, p) } else { validate_solid_params(id, p) }
}
@@ -712,8 +734,8 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
/// blending mode, and those of a group it is in, apply to the surfaces of the members it holds
/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it
/// off), to be drawn behind every surface of the object, and the surfaces.
fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
let art = surfaces_for(n, fx, shapes)?;
fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
let art = surfaces_for(doc, n, fx, shapes)?;
// A shadow past the limits draws the source path, as a solid past them does; commands report
// the error ([`validate_solid_in`]).
let shadow = match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes).ok()? {
@@ -789,8 +811,139 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
/// its member's scopes and ink ([`cast_shadow`]).
type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec<shadow::Cast<'a>>);
/// [`art_for`] without the shadow: the solids' surfaces.
fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
/// The graphics of a 3D effect with parameters `p`, drawn on its faces ([`graphics::face_art`]):
/// for each planar face with a graphic, the art and the face. `caps` are the faces the viewer sees
/// of the ends of the object's solids, each with its end; `bounds` are the bounds the solids were
/// built with; `opacity` is the opacity of the fill or stroke those solids are painted with, which
/// the graphics take too. `elements` is the effect's count of drawn path elements, shared by every
/// call for one effect ([`graphics::face_art`]).
fn graphic_art(
doc: Option<&Document>,
id: NodeId,
(effect, p): (&str, &Value),
bounds: Rect,
caps: &[&Facet],
opacity: f32,
elements: &mut usize,
) -> Vec<(PlanarFace, Arc<Node>)> {
let list = graphics::mapped_graphics(p);
if list.is_empty() || !takes_graphics(effect) {
return vec![];
}
let view = view_options(p);
PlanarFace::ALL
.into_iter()
.filter_map(|face| {
let on: Vec<&Facet> = caps.iter().copied().filter(|f| f.end == Some(face)).collect();
let map = if effect == ROTATE {
vectorcraft_three_d::plane_face_map(bounds, view)
} else {
vectorcraft_three_d::extrude_face_map(bounds, extrude_options(p), view, face)
}?;
graphics::face_art(doc, id, &list, (face, &map), bounds.center(), &on, elements).map(|mut art| {
art.opacity *= opacity;
(face, Arc::new(art))
})
})
.collect()
}
/// A solid (a fill's or a stroke's) with ends the viewer sees: the index of its surface, its
/// member, the ends, the opacity and blending mode of its fill or stroke, and whether its surface
/// carries an opacity mask (a gradient's transparency under a colored light, [`surface`]).
struct Filled {
at: usize,
member: usize,
caps: Vec<Facet>,
opacity: f32,
blend: BlendMode,
masked: bool,
}
/// Does a surface in `paint` carry an opacity mask ([`surface`])?
fn masks_surface(paint: &Paint, colored: bool) -> bool {
colored && crate::lighting::opaque_paint(paint).1.is_some()
}
/// 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`
/// (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
/// draw no graphics.
fn placed_graphics(
doc: Option<&Document>,
id: NodeId,
effect: (&str, &Value),
bounds: Rect,
filled: &[Filled],
per_member: bool,
) -> Vec<(usize, PlanarFace, Arc<Node>)> {
let mut groups: Vec<Vec<&Filled>> = vec![];
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`]).
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))) {
Some(g) => g.push(f),
None => groups.push(vec![f]),
}
}
let mut out = vec![];
let mut elements = 0usize;
for group in groups {
let caps: Vec<&Facet> = group.iter().flat_map(|f| &f.caps).collect();
let opacity = group.first().map_or(1.0, |f| f.opacity);
let blend = group.first().map_or(BlendMode::Normal, |f| f.blend);
for (face, mut art) in graphic_art(doc, id, effect, bounds, &caps, opacity, &mut elements) {
if let Some(f) = group.iter().rev().find(|f| f.caps.iter().any(|c| c.end == Some(face))) {
Arc::make_mut(&mut art).blend = blend;
out.push((f.at, face, art));
}
}
}
out
}
/// One solid's surface as [`surfaces_for`] builds it: its faces' depths, its art, its member's
/// scopes, and for each face the end of a solid it is, when the viewer sees it.
type BuiltSurface<'s> = (Vec<Placed>, Node, &'s [Scope], Vec<Option<PlanarFace>>);
/// [`with_graphics`] of built surfaces, each drawn whole.
fn whole_surfaces<'s>(surfaces: Vec<BuiltSurface<'s>>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), arts)
}
/// `surfaces` drawn whole, each with its scopes, and the graphics `arts` ([`placed_graphics`]) each
/// right after its surface, with that surface's scopes and its opacity mask (a gradient's
/// transparency), so a graphic is hidden where its cap is.
fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc<Node>)>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
let mut out = Vec::with_capacity(surfaces.len() + arts.len());
for (k, (scopes, s)) in surfaces.into_iter().enumerate() {
let mask = s.extras().mask.clone();
out.push((scopes, s));
out.extend(arts.iter().filter(|(at, ..)| *at == k).map(|(.., art)| {
let mut art = art.clone();
if let Some(mask) = &mask {
Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone());
}
(scopes, art)
}));
}
out
}
/// The ends of `f` the viewer sees, for a fill's solid or a stroke's: where its graphics go.
fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> {
f.iter().filter(|f| f.end.is_some() && !f.away)
}
/// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar
/// faces drawn right after the last of the solids' surfaces that holds that face.
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
let b = union_bounds(shapes)?;
let p = crate::merged_params(&fx.id, &fx.params);
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
@@ -798,11 +951,14 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
let masks = has_masks(shapes);
// The paint copies of every solid together: past the allowance the source path is drawn.
let mut paint_bytes = 0usize;
// The caps are copied only when the effect has graphics to draw on them.
let graphics_on = !classic && takes_graphics(&fx.id) && !mapped_graphics(&p).is_empty();
if is_plane(&fx.id) {
// Every part turns about the centre of the object's own bounds (a group's members about
// the centre of theirs), so they stay together.
let mut out = vec![];
for s in shapes {
let mut filled = vec![];
for (member, s) in shapes.iter().enumerate() {
for item in &s.items {
let (paint, opacity, blend) = paint_of(item, s.opacity);
let (area, rule) = region(&s.path, s.rule, item);
@@ -810,10 +966,18 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) {
return None;
}
if graphics_on {
let caps: Vec<Facet> = seen_ends(&f).cloned().collect();
if !caps.is_empty() {
filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) });
}
}
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
out.push((s.scopes.as_slice(), Arc::new(art)));
}
}
let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks);
let out = with_graphics(out, &arts);
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
}
let (parts, bounds) = solid_parts(shapes, b);
@@ -845,36 +1009,56 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
let (_, opacity, blend) = paint_of(item, *member);
opacity >= 1.0 && blend == BlendMode::Normal
});
let surfaces: Vec<(Vec<Placed>, Node, &[Scope])> = solids
let arts = if !graphics_on {
vec![]
} else {
let filled: Vec<Filled> = solids
.iter()
.enumerate()
.filter_map(|(at, (item, member, _, f, shape))| {
let caps: Vec<Facet> = seen_ends(f).cloned().collect();
let (paint, opacity, blend) = paint_of(item, *member);
let masked = masks_surface(&paint, colored);
(!caps.is_empty()).then_some(Filled { at, member: *shape, caps, opacity, blend, masked })
})
.collect();
placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks)
};
let surfaces: Vec<BuiltSurface> = solids
.into_iter()
.map(|(item, member, scopes, f, shape)| {
let closed = shapes.get(shape).is_some_and(|s| s.path.subpaths.iter().all(|p| p.closed));
let paints = Paints::of(item, closed);
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
let (paint, opacity, blend) = paint_of(item, member);
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
(depths, art, scopes)
(depths, art, scopes, ends)
})
.collect();
if masks {
return Some(masked(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect()));
return Some(masked(n.id, whole_surfaces(surfaces, &arts)));
}
// One order takes a plain group of faces from each solid, one face for each facet. With
// colored lights a surface can instead be one clipped composite of all its facets. A composite
// has no faces to order, so when any surface is one, every surface of the solid, masked ones
// included, draws whole in member order.
let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
if !opaque || !plain {
return Some(surfaces.into_iter().map(|(_, s, _)| Arc::new(s)).collect());
}
let plain =
surfaces.iter().all(|(depths, s, _, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
// A surface in a gradient with transparent stops carries an opacity mask: its faces go in runs
// ([`in_runs`]), and each run carries the mask.
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _)| s.extras().mask.clone()).collect();
let (mut placed, mut faces) = (vec![], vec![]);
for (surface, (depths, s, _)) in surfaces.into_iter().enumerate() {
// ([`in_runs`]), and each run carries the mask. With graphics as well, the surfaces draw whole,
// each graphic right after its surface.
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect();
let masked_faces = masks.iter().any(Option::is_some);
if !opaque || !plain || (masked_faces && !arts.is_empty()) {
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
}
let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]);
for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() {
if let NodeKind::Group { children, .. } = s.kind {
placed.extend(depths);
faces.extend(children.into_iter().map(|face| Some((surface, face))));
ends.extend(e);
}
}
let sealed = match fx.id.as_str() {
@@ -883,8 +1067,18 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
_ => extrude_options(&p).cap,
};
let order = draw_order(&placed, sealed);
let faces: Vec<(usize, Arc<Node>)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect();
let children = if masks.iter().all(Option::is_none) { faces.into_iter().map(|(_, face)| face).collect() } else { in_runs(n.id, faces, &masks) };
if masked_faces {
let faces: Vec<(usize, Arc<Node>)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect();
return Some(vec![Arc::new(Node::group(n.id, in_runs(n.id, faces, &masks)))]);
}
// Each face's graphics go right after the last of the faces they are drawn on.
let last: Vec<Option<usize>> =
arts.iter().map(|(_, face, _)| order.iter().rposition(|k| ends.get(*k).copied().flatten() == Some(*face))).collect();
let mut children = Vec::with_capacity(order.len() + arts.len());
for (at, k) in order.into_iter().enumerate() {
children.extend(faces.get_mut(k).and_then(Option::take).map(|(_, face)| face));
children.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (.., art))| art.clone()));
}
Some(vec![Arc::new(Node::group(n.id, children))])
}
@@ -969,7 +1163,7 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
}
let n = &*resolve(doc, n, "").ok()?;
if is_container(n) {
return group_solid_art(n);
return group_solid_art(doc, n);
}
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
@@ -978,7 +1172,7 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
let remaining: Vec<Effect>;
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
let (shadow, surfaces) = art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?;
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?;
children.extend(shadow.into_iter().chain(surfaces));
// Later geometry effects act on the projected art as a whole.
remaining = past_effect(&n.appearance.effects, index);
@@ -994,7 +1188,7 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
for item in &paints {
if let Some((index, fx)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
let (shadow, surfaces) = art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
let later: Vec<Effect> = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect();
let with_later = |mut art: Arc<Node>| {
Arc::make_mut(&mut art).appearance.effects = later.clone();
@@ -1003,7 +1197,8 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
shadows.extend(shadow.into_iter().map(with_later));
children.extend(surfaces.into_iter().map(with_later));
} else {
children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() })));
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat)));
}
}
children.splice(0..0, shadows);
@@ -1018,11 +1213,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// geometry effects before it reshape the members, those after it bend the result as a whole; the
/// group's own fills and strokes are not drawn. `None` when the effect is only on one of the
/// group's own fills or strokes, or when its members can't become solids.
fn group_solid_art(n: &Node) -> Option<Node> {
fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option<Node> {
let (index, fx) = solid(&n.appearance.effects)?;
let mut shapes = members(n, "").ok()?;
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
let (shadow, surfaces) = art_for(n, fx, &shapes)?;
let (shadow, surfaces) = art_for(doc, n, fx, &shapes)?;
let children = shadow.into_iter().chain(surfaces).collect();
let remaining = past_effect(&n.appearance.effects, index);
let mut art = n.clone();
@@ -1031,6 +1226,77 @@ fn group_solid_art(n: &Node) -> Option<Node> {
Some(art)
}
/// Where the graphics of the 3D effect of `n` (on the object itself with `item` `None`, else on its
/// fill or stroke `item`) are drawn: the bounds its solids are built with and the maps of their
/// planar faces ([`graphics::GraphicFrame`]). `None` when `n` has no visible Extrude & Bevel or
/// Rotate there, or its art can't be built.
pub fn graphic_frame(doc: Option<&Document>, n: &Node, item: Option<usize>) -> Option<graphics::GraphicFrame> {
frame_of(doc, n, item, &solid)
}
/// [`graphic_frame`] of the 3D effect at `index` in that list, which must be a visible Extrude &
/// Bevel or Rotate.
pub fn graphic_frame_at(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<graphics::GraphicFrame> {
frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && SOLIDS.contains(&e.id.as_str())).map(|e| (index, e)))
}
/// Does a visible geometry effect come after the 3D effect at `index` in the effects of `n` (on the
/// object itself with `item` `None`, else on its fill or stroke `item`)? Such an effect moves or
/// bends the drawn art, graphics included, while [`graphic_frame_at`] places the graphics on the
/// art before it.
pub fn graphics_reshaped_after(n: &Node, item: Option<usize>, index: usize) -> bool {
n.appearance.effects_at(item).and_then(|fx| fx.get(index + 1..)).is_some_and(crate::has_geometry)
}
/// Finds a 3D effect in a list of effects, with its index there.
type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p;
/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`.
fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<graphics::GraphicFrame> {
let n = &*resolve(doc, n, "").ok()?;
let (fx, shapes) = if is_container(n) {
let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?;
let mut shapes = members(n, "").ok()?;
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
(fx, shapes)
} else {
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
match item {
None => {
let (index, fx) = pick(&n.appearance.effects)?;
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
(fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }])
}
Some(k) => {
let it = n.appearance.items.get(k)?;
let (index, fx) = pick(it.effects())?;
let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it));
(fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }])
}
}
};
if !takes_graphics(&fx.id) {
return None;
}
let p = crate::merged_params(&fx.id, &fx.params);
let b = union_bounds(&shapes)?;
let view = view_options(&p);
if fx.id == ROTATE {
let plane = vectorcraft_three_d::plane_face_map(b, view);
return Some(graphics::GraphicFrame::new(b, plane, None));
}
let (_, bounds) = solid_parts(&shapes, b);
let options = extrude_options(&p);
let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face);
Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back)))
}
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
pub fn graphic_bounds(doc: &Document, name: &str) -> Option<Rect> {
graphics::art_bounds(doc, name)
}
/// `effects` without the 3D effect at `index` and the geometry effects before it, which shape the
/// art it projects. Each raster effect before it follows the Transform effects among those
/// ([`crate::without_geometry`]), unless a Transform effect after it makes copies or moves at
+631
View File
@@ -0,0 +1,631 @@
//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials ›
//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a
//! plane, turned, foreshortened and shaded with that face and clipped to it.
//!
//! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale,
//! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of
//! the object's bounds in the face's own plane (points, x to the right and y down as the face is
//! seen from the front of that face), its size as a share of the symbol's own, and its turn
//! (degrees, counterclockwise). On the back cap, x runs to the right as the back is seen from
//! behind, so the graphic reads the right way round there.
use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol};
use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath};
use vectorcraft_three_d::{FaceMap, Facet, PlanarFace};
/// The effect parameter that holds the graphics.
pub const GRAPHICS: &str = "graphics";
/// The most graphics one 3D effect maps.
pub const MAX_GRAPHICS: usize = 64;
/// The most fills and stroke outlines the art of one symbol draws as a graphic.
const MAX_PIECES: usize = 4096;
/// The most path elements the graphics of one 3D effect draw together, after a perspective cuts
/// their curves.
const MAX_ELEMENTS: usize = 400_000;
/// The pieces each curve of a graphic is cut into under a perspective map, which bends it.
const PERSPECTIVE_PIECES: usize = 8;
/// How deep symbol instances in a graphic's art may nest.
const MAX_NESTING: usize = 8;
/// How deep the objects of a graphic's art may be, counting groups and the art of the symbols it
/// places: as deep as an object may be drawn.
const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH;
/// The size range of a graphic, as a percentage of its symbol's own size.
pub const SCALE_RANGE: (f64, f64) = (1.0, 10_000.0);
/// How far a graphic's center may be from the center of its object, in points.
pub const MAX_OFFSET: f64 = 1e6;
/// One graphic mapped onto a face of a 3D object.
#[derive(Clone, Debug, PartialEq)]
pub struct MappedGraphic {
pub symbol: String,
pub face: PlanarFace,
pub x: f64,
pub y: f64,
/// Percent of the symbol's own size.
pub scale: f64,
/// Degrees, counterclockwise.
pub rotation: f64,
}
impl MappedGraphic {
pub fn to_value(&self) -> Value {
json!({"symbol": self.symbol, "face": self.face.id(), "x": self.x, "y": self.y, "scale": self.scale, "rotation": self.rotation})
}
/// The graphic `v` describes. Only `symbol` is required: `face` defaults to front, the offsets
/// and the rotation to 0 and the scale to 100.
pub fn from_value(v: &Value) -> Result<Self, String> {
let Value::Object(m) = v else { return Err(format!("each of `{GRAPHICS}` must be an object")) };
if let Some(k) = m.keys().find(|k| !matches!(k.as_str(), "symbol" | "face" | "x" | "y" | "scale" | "rotation")) {
return Err(format!("`{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}`"));
}
let symbol = match m.get("symbol") {
Some(Value::String(s)) if !s.trim().is_empty() => s.clone(),
_ => return Err(format!("each of `{GRAPHICS}` needs `symbol`, the name of a symbol")),
};
let face = match m.get("face") {
None => PlanarFace::Front,
Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?,
};
let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result<f64, String> {
match m.get(key) {
None => Ok(default),
Some(v) => v
.as_f64()
.filter(|n| n.is_finite() && (lo..=hi).contains(n))
.ok_or_else(|| format!("`{GRAPHICS}` {key} must be a number from {lo} to {hi}")),
}
};
Ok(Self {
symbol,
face,
x: number("x", 0.0, (-MAX_OFFSET, MAX_OFFSET))?,
y: number("y", 0.0, (-MAX_OFFSET, MAX_OFFSET))?,
scale: number("scale", 100.0, SCALE_RANGE)?,
rotation: number("rotation", 0.0, (-360.0, 360.0))?,
})
}
/// Where the graphic's art goes in the face's plane, for symbol art whose bounds are `art` on an
/// object whose bounds have center `center`.
fn placement(&self, art: Rect, center: Point) -> Affine {
let place = Affine::translate((center.x + self.x, center.y + self.y))
* Affine::rotate(-self.rotation.to_radians())
* Affine::scale(self.scale / 100.0)
* Affine::translate(-art.center().to_vec2());
match self.face {
PlanarFace::Front => place,
// Seen from behind, the back's right is the front's left.
PlanarFace::Back => {
Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place
}
}
}
}
/// The 3D effects that take graphics: Extrude & Bevel (its caps) and Rotate (the plane), the two
/// object types of the 3D and Materials panel with planar faces.
pub fn takes_graphics(id: &str) -> bool {
id == super::EXTRUDE || id == super::ROTATE
}
/// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold
/// anything; commands check every entry with [`validate`]).
pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
match p.get(GRAPHICS) {
Some(Value::Array(list)) => list.iter().take(MAX_GRAPHICS).filter_map(|v| MappedGraphic::from_value(v).ok()).collect(),
_ => vec![],
}
}
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel and Rotate take
/// graphics, and a plane has only a front.
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
let list = match p.get(GRAPHICS) {
None => return Ok(()),
Some(Value::Array(list)) => list,
Some(_) => return Err(format!("`{GRAPHICS}` must be an array")),
};
if list.is_empty() {
return Ok(());
}
if !takes_graphics(id) {
return Err("Graphics map onto planar faces: use the Extrude or Plane object type".into());
}
if list.len() > MAX_GRAPHICS {
return Err(format!("`{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics"));
}
for v in list {
let g = MappedGraphic::from_value(v)?;
if id == super::ROTATE && g.face == PlanarFace::Back {
return Err("A plane has one face: map its graphics onto the front".into());
}
}
Ok(())
}
/// The first symbol the graphics in `p` name that `doc` does not have, leaving out the symbols the
/// graphics in `old` (the effect's parameters before an edit) already name: a graphic whose symbol
/// was deleted may stay.
pub fn missing_symbol(doc: &Document, p: &Value, old: Option<&Value>) -> Option<String> {
let kept = old.map(mapped_graphics).unwrap_or_default();
mapped_graphics(p)
.into_iter()
.map(|g| g.symbol)
.find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.iter().any(|g| g.symbol == *name))
}
/// Does the art of the symbols the graphics in `p` name fit the limits? A graphic whose symbol
/// `doc` does not have draws nothing and is not counted. With a perspective, each curve counts as
/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once.
pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> {
let curve = if super::view_options(p).perspective > 0.0 { PERSPECTIVE_PIECES } else { 1 };
let mut elements = 0usize;
for g in mapped_graphics(p) {
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
let pieces = pieces_of(doc, symbol)?;
elements = elements.saturating_add(pieces.iter().map(|p| drawn_elements(&p.path, curve)).sum());
if elements > MAX_ELEMENTS {
return Err("The graphics are too complex: simplify the symbols' art".into());
}
}
Ok(())
}
/// The path elements `path` draws when each curve draws `curve` elements, before curves near the
/// eye are split further: one for each straight line, move and close.
fn drawn_elements(path: &PathData, curve: usize) -> usize {
let segments = |s: &SubPath| (0..s.segment_count()).map(|i| if s.segment_is_line(i) { 1 } else { curve }).sum::<usize>();
path.subpaths.iter().map(|s| 1 + usize::from(s.closed) + segments(s)).sum()
}
/// One area of a graphic's art, drawn with one paint: a fill, or a stroke's outline.
struct Piece {
path: PathData,
rule: FillRule,
paint: Paint,
opacity: f32,
blend: BlendMode,
}
/// The areas the art of `symbol` paints, back to front, at the symbol's natural size: the fills of
/// its paths, compound paths and type (as outlines), and its strokes' outlines, through the symbol
/// instances it holds (with their changes to dynamic symbols, and through 9-slice guides). Hidden objects, guides, clipping paths and images are left out, and clipping
/// groups draw their art unclipped.
fn pieces_of(doc: &Document, symbol: &Symbol) -> Result<Vec<Piece>, String> {
fn walk(doc: &Document, n: &Node, outer: f32, xf: Affine, (depth, level): (usize, usize), out: &mut Vec<Piece>) -> Result<(), String> {
if !n.visible || n.is_guide() {
return Ok(());
}
if level > MAX_LEVELS {
return Err(format!("A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art"));
}
let opacity = outer * n.opacity;
let shape = match &n.kind {
NodeKind::Path { path, rule, clipping: false, .. } => Some((path.clone(), *rule)),
NodeKind::Compound { children, rule } => {
Some((PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()), *rule))
}
NodeKind::Text(_) => {
if let Some(mut outlined) = crate::outline_text(n) {
// The outlines take the type's place, with its opacity.
outlined.visible = true;
outlined.opacity = n.opacity;
walk(doc, &outlined, outer, xf, (depth, level + 1), out)?;
}
None
}
NodeKind::SymbolInstance { symbol, xf: at } => {
if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) {
if depth >= MAX_NESTING {
return Err(format!("A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art"));
}
// The instance shows its own changes to a dynamic symbol's art, and a symbol
// with 9-slice guides is placed through them, as the canvas draws it. The
// pieces are not clipped, so paths that cross a guide are cut at it.
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n);
if doc.symbol_slice_map(symbol, *at).is_some() {
let Some(placed) = doc.place_symbol_art_unclipped(symbol, &art, *at) else {
return Err("A graphic's art holds too many objects: simplify the symbol's art".into());
};
walk(doc, &placed, opacity, xf, (depth + 1, level + 1), out)?;
} else {
walk(doc, &art, opacity, xf * *at, (depth + 1, level + 1), out)?;
}
}
None
}
_ => {
for c in n.children().into_iter().flatten() {
walk(doc, c, opacity, xf, (depth, level + 1), out)?;
}
None
}
};
let Some((path, rule)) = shape else { return Ok(()) };
// Symbol art keeps its strokes' widths as drawn while its geometry is scaled to the
// symbol's square, so a stroke is outlined after the art takes its size.
let path = path.transformed(xf);
for item in n.appearance.items.iter().filter(|i| i.visible()) {
let (area, rule, paint, item_opacity, blend) = match item {
AppearanceItem::Fill(f) => (path.clone(), rule, f.paint.clone(), f.opacity, f.blend),
AppearanceItem::Stroke(s) if s.width > 0.0 && s.width.is_finite() => {
(crate::stroke::outline_region(&path, rule, s), FillRule::EvenOdd, s.paint.clone(), s.opacity, s.blend)
}
AppearanceItem::Stroke(_) => continue,
};
if matches!(paint, Paint::None) || area.bounds().is_none() {
continue;
}
if out.len() >= MAX_PIECES {
return Err(format!("A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art"));
}
// A placed gradient or pattern takes the same size and place as its path.
let mut paint = paint;
match &mut paint {
Paint::Gradient(g) => g.transform(xf),
Paint::Pattern { xf: placed, .. } => *placed = xf * *placed,
Paint::None | Paint::Solid { .. } => {}
}
out.push(Piece { path: area, rule, paint, opacity: opacity * item_opacity, blend });
}
Ok(())
}
let mut out = vec![];
walk(doc, &symbol.art, 1.0, doc.symbol_natural_xf(&symbol.name), (0, 1), &mut out)?;
Ok(out)
}
/// `path` through `map`: exactly for an affine map, otherwise with each curve cut into
/// [`PERSPECTIVE_PIECES`] pieces whose control points go through it (straight lines stay straight
/// under a perspective). Fails when part of it has no page point, or when it takes more than `room`
/// elements.
fn map_path(path: &PathData, map: &FaceMap, affine: Option<Affine>, room: usize) -> Result<BezPath, NotMapped> {
let bp = path.to_bezpath();
if let Some(a) = affine {
return if bp.elements().len() <= room { Ok(a * bp) } else { Err(NotMapped::Full) };
}
let to = |p: Point| map.to_page(p).ok_or(NotMapped::Behind);
let mut out = BezPath::new();
let mut at = Point::ZERO;
for el in bp.elements() {
if out.elements().len() > room {
return Err(NotMapped::Full);
}
match *el {
PathEl::MoveTo(p) => {
out.move_to(to(p)?);
at = p;
}
PathEl::LineTo(p) => {
out.line_to(to(p)?);
at = p;
}
PathEl::QuadTo(c, p) => {
cubic_to(&mut out, vectorcraft_geom::kurbo::QuadBez::new(at, c, p).raise(), map).ok_or(NotMapped::Behind)?;
at = p;
}
PathEl::CurveTo(c1, c2, p) => {
cubic_to(&mut out, CubicBez::new(at, c1, c2, p), map).ok_or(NotMapped::Behind)?;
at = p;
}
PathEl::ClosePath => out.close_path(),
}
}
if out.elements().len() <= room { Ok(out) } else { Err(NotMapped::Full) }
}
/// Why [`map_path`] drew nothing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NotMapped {
/// Part of the path has no page point: it is at or behind the eye.
Behind,
/// The path takes more elements than it has room for.
Full,
}
/// Curve `c` through `map`, cut into [`PERSPECTIVE_PIECES`] pieces. A piece that lies in front of
/// the eye while a control point does not is split further ([`piece_to`]). `None` when part of a
/// piece has no page point.
fn cubic_to(out: &mut BezPath, c: CubicBez, map: &FaceMap) -> Option<()> {
for k in 0..PERSPECTIVE_PIECES {
let (t0, t1) = (k as f64 / PERSPECTIVE_PIECES as f64, (k + 1) as f64 / PERSPECTIVE_PIECES as f64);
let s = c.subsegment(t0..t1);
if !map.maps_curve([s.p0, s.p1, s.p2, s.p3]) {
return None;
}
piece_to(out, s, map, MAX_SPLITS)?;
}
Some(())
}
/// How many times [`piece_to`] halves a piece whose control points are behind the eye.
const MAX_SPLITS: usize = 4;
/// Piece `s`, which lies in front of the eye, through `map`: halved until the control points of
/// each half have page points, at most `splits` times, and drawn straight past that.
fn piece_to(out: &mut BezPath, s: CubicBez, map: &FaceMap, splits: usize) -> Option<()> {
let end = map.to_page(s.p3)?;
match (map.to_page(s.p1), map.to_page(s.p2)) {
(Some(c1), Some(c2)) => out.curve_to(c1, c2, end),
_ if splits == 0 => out.line_to(end),
_ => {
let (a, b) = s.subdivide();
piece_to(out, a, map, splits - 1)?;
piece_to(out, b, map, splits - 1)?;
}
}
Some(())
}
/// The graphics `graphics` lists for `face`, drawn on caps `caps` (the faces of that end of the
/// object's solids that the viewer sees) through `map`, for an object whose bounds have
/// center `center`: one clipping group of every such graphic, shaded with the first cap's light.
/// Pattern tiles keep their colors: the document's pattern draws them. A graphic whose symbol
/// `doc` does not have draws nothing. `elements` counts the path elements
/// the effect's graphics have drawn so far, after a perspective cuts their curves, and is shared by
/// every call for one effect. `None` when there is nothing to draw or that count passes
/// [`MAX_ELEMENTS`].
pub(super) fn face_art(
doc: Option<&Document>,
id: NodeId,
graphics: &[MappedGraphic],
(face, map): (PlanarFace, &FaceMap),
center: Point,
caps: &[&Facet],
elements: &mut usize,
) -> Option<Node> {
let doc = doc?;
let light = caps.first()?.illumination;
let affine = map.local_affine(center).filter(|_| map.is_affine());
let mut children = vec![];
for g in graphics.iter().filter(|g| g.face == face) {
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
// A symbol past the limits is left out; the other graphics still draw.
let Ok(pieces) = pieces_of(doc, symbol) else { continue };
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
let place = g.placement(bounds, center);
// Gradients follow the face's map as it is near the graphic's center.
let middle = place * bounds.center();
// When the center is at or behind the eye, they follow it near the middle of the part that
// is in front; a graphic with no part in front is left out.
let local = map.local_affine(middle).or_else(|| {
let part = map.mapped_part(place.transform_rect_bbox(bounds))?;
let sum = part.iter().fold(Point::ZERO, |s, p| s + p.to_vec2());
map.local_affine(Point::new(sum.x / part.len() as f64, sum.y / part.len() as f64))
});
let Some(local) = local else { continue };
let gradient_map = local * place;
for piece in pieces {
let placed = piece.path.transformed(place);
// Each anchor draws at least one element. A perspective cuts curves into more, and
// straight lines stay one each: the path may take what is left of the limit, and is
// counted as it is drawn. Past the limit, the face draws nothing.
let least: usize = placed.subpaths.iter().map(|s| s.anchors.len()).sum();
let before = *elements;
if before.saturating_add(least) > MAX_ELEMENTS {
return None;
}
let room = MAX_ELEMENTS - before;
let mut rule = piece.rule;
let mapped = match map_path(&placed, map, affine, room) {
Err(NotMapped::Behind) => {
// Part of it is at or behind the eye: the part in front is drawn.
let Some(part) = placed.bounds().and_then(|b| map.mapped_part(b)) else { continue };
let Some(&first) = part.first() else { continue };
let mut front = BezPath::new();
front.move_to(first);
part.iter().skip(1).for_each(|p| front.line_to(*p));
front.close_path();
let cut = vectorcraft_pathops::boolean(
&placed,
piece.rule,
&PathData::from_bezpath(&front),
FillRule::NonZero,
vectorcraft_pathops::BoolOp::Intersect,
);
rule = FillRule::NonZero;
map_path(&cut, map, affine, room)
}
done => done,
};
let mapped = match mapped {
Ok(mapped) => mapped,
Err(NotMapped::Full) => return None,
Err(NotMapped::Behind) => continue,
};
*elements = before.saturating_add(mapped.elements().len());
let mut paint = piece.paint;
vectorcraft_doc::recolor::map_paint(&mut paint, &|c| crate::lighting::shade(c, light));
// A pattern's tiles follow the graphic onto the face, as its gradients do below.
if let Paint::Pattern { xf, .. } = &mut paint {
*xf = gradient_map * *xf;
}
let mut fill = FillLayer::new(paint);
fill.opacity = piece.opacity;
fill.blend = piece.blend;
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
appearance.transform_gradients(gradient_map);
let mut node = Node::path(id, PathData::from_bezpath(&mapped), appearance);
if let NodeKind::Path { rule: r, .. } = &mut node.kind {
*r = rule;
}
children.push(Arc::new(node));
}
}
if children.is_empty() {
return None;
}
let mut clip = BezPath::new();
for cap in caps {
// A cap's holes are contours of the same path wound against its outline, so turning the
// whole path keeps them holes under the nonzero rule.
let mut outline = cap.path().to_bezpath();
if outline.area() < 0.0 {
outline = outline.reverse_subpaths();
}
clip.extend(outline.iter());
}
let clip = Node::path(id, PathData::from_bezpath(&clip), Appearance::default());
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))
}
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
pub(super) fn art_bounds(doc: &Document, name: &str) -> Option<Rect> {
let symbol = doc.symbols.iter().find(|s| s.name == name)?;
pieces_of(doc, symbol).ok()?.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b))
}
/// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics'
/// offsets are from their center) and the maps of its front and back faces, when it has them.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GraphicFrame {
pub bounds: Rect,
front: Option<FaceMap>,
back: Option<FaceMap>,
}
impl GraphicFrame {
pub(super) fn new(bounds: Rect, front: Option<FaceMap>, back: Option<FaceMap>) -> Self {
Self { bounds, front, back }
}
pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> {
match face {
PlanarFace::Front => self.front.as_ref(),
PlanarFace::Back => self.back.as_ref(),
}
}
/// The point of `face`'s plane that offset `(x, y)` names, as [`MappedGraphic`] places a
/// graphic's center.
fn art_point(&self, face: PlanarFace, (x, y): (f64, f64)) -> Point {
let c = self.bounds.center();
match face {
PlanarFace::Front => Point::new(c.x + x, c.y + y),
PlanarFace::Back => Point::new(c.x - x, c.y + y),
}
}
/// Where graphic `g`'s center lands on the page, and whether its face is turned toward the
/// viewer. `None` when the object has no such face or the point has no page point.
pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> {
let map = self.map(g.face)?;
Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible))
}
/// The offset of a graphic on `face` whose center lands on page point `page`.
pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> {
let art = self.map(face)?.to_art(page)?;
let c = self.bounds.center();
let (x, y) = match face {
PlanarFace::Front => (art.x - c.x, art.y - c.y),
PlanarFace::Back => (c.x - art.x, art.y - c.y),
};
(x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y))
}
/// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most
/// 100: where a newly mapped graphic starts.
pub fn fitting_scale(&self, art: Rect) -> f64 {
let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9));
(fit * 100.0).clamp(SCALE_RANGE.0, 100.0)
}
}
/// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes').
pub fn graphic_symbols(n: &Node) -> Vec<String> {
appearance_graphic_symbols(&n.appearance)
}
/// The symbols the graphics of the 3D effects in `appearance` name, as [`graphic_symbols`]: for a
/// graphic style's appearance.
pub fn appearance_graphic_symbols(appearance: &Appearance) -> Vec<String> {
std::iter::once(&appearance.effects)
.chain(appearance.items.iter().map(AppearanceItem::effects))
.flatten()
.filter(|e| takes_graphics(&e.id))
.flat_map(|e| mapped_graphics(&e.params))
.map(|g| g.symbol)
.collect()
}
/// Makes the graphics of `n`'s 3D effects that name symbol `from` name `to` instead. Returns
/// whether any changed.
pub fn rename_graphic_symbol(n: &mut Node, from: &str, to: &str) -> bool {
// Checked first, so an appearance that names another symbol is not copied.
graphic_symbols(n).iter().any(|s| s == from) && rename_appearance_graphic_symbol(&mut n.appearance, from, to)
}
/// [`rename_graphic_symbol`] for the 3D effects in `appearance`: for a graphic style's appearance.
pub fn rename_appearance_graphic_symbol(appearance: &mut Appearance, from: &str, to: &str) -> bool {
if !appearance_graphic_symbols(appearance).iter().any(|s| s == from) {
return false;
}
let mut lists: Vec<&mut Vec<vectorcraft_doc::Effect>> = vec![];
let (effects, items) = (&mut appearance.effects, &mut appearance.items);
lists.push(effects);
lists.extend(items.iter_mut().map(AppearanceItem::effects_mut));
for e in lists.into_iter().flatten().filter(|e| takes_graphics(&e.id)) {
if let Some(Value::Array(list)) = e.params.get_mut(GRAPHICS) {
for g in list.iter_mut() {
if g.get("symbol").and_then(Value::as_str) == Some(from) {
g["symbol"] = json!(to);
}
}
}
}
true
}
/// Does `n` or any object in it, opacity masks included, have a graphic that names symbol `from`?
pub fn names_graphic_symbol(n: &Node, from: &str) -> bool {
let mut found = false;
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| found |= graphic_symbols(c).iter().any(|s| s == from));
found
}
/// [`rename_graphic_symbol`] for `n` and every object in it, at any depth, opacity masks included.
/// Only the parts that name `from` are copied. Returns whether any changed.
pub fn rename_graphic_symbol_in(n: &mut Node, from: &str, to: &str) -> bool {
let names = names_graphic_symbol;
let mut changed = rename_graphic_symbol(n, from, to);
if let Some(mask) = n.extras_if_any().and_then(|x| x.mask.as_deref_mut()).filter(|m| names(&m.art, from)) {
changed |= rename_graphic_symbol_in(Arc::make_mut(&mut mask.art), from, to);
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut().filter(|c| names(c, from)) {
changed |= rename_graphic_symbol_in(Arc::make_mut(c), from, to);
}
}
changed
}
/// `p` with graphic `g` added at the end of its list.
pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value {
let mut out = p.as_object().cloned().unwrap_or_else(Map::new);
let mut list = match out.get(GRAPHICS) {
Some(Value::Array(list)) => list.clone(),
_ => vec![],
};
list.push(g.to_value());
out.insert(GRAPHICS.into(), Value::Array(list));
Value::Object(out)
}
#[cfg(test)]
#[path = "tests_graphics.rs"]
mod tests;
+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;
}
+62
View File
@@ -457,6 +457,68 @@ fn transparency_stays_on_the_whole_surface_and_items_take_their_own_effect() {
assert!(matches!(surfaces[1].kind, NodeKind::Path { .. }));
}
/// Two nested squares drawn in the same direction, so only the even-odd rule leaves a hole.
fn nested_squares() -> [PathData; 2] {
[(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| {
let mut b = BezPath::new();
b.move_to((lo, lo));
b.line_to((hi, lo));
b.line_to((hi, hi));
b.line_to((lo, hi));
b.close_path();
PathData::from_bezpath(&b)
})
}
/// The nested squares as an even-odd compound path and as one even-odd path, painted by `items`.
fn even_odd_shapes(items: Vec<AppearanceItem>) -> [Node; 2] {
let [outer, inner] = nested_squares();
let appearance = Appearance { items, ..Default::default() };
let children = vec![
Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())),
Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())),
];
let mut compound = Node::new(NodeId(1), NodeKind::Compound { children, rule: FillRule::EvenOdd });
compound.appearance = appearance.clone().into();
let both = PathData::new(outer.subpaths.into_iter().chain(inner.subpaths).collect());
[compound, crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance)]
}
/// Check that `art` draws `item` as one flat child: an even-odd path with a hole in the middle,
/// below the 3D art after it.
fn assert_flat_item_keeps_the_hole(art: &Node, item: &AppearanceItem, what: &str) {
use vectorcraft_geom::hit::fill_contains;
let children = art.children().unwrap();
let flat: Vec<usize> =
(0..children.len()).filter(|&i| children[i].appearance.items == [item.clone()] && children[i].path_data().is_some()).collect();
let [index] = flat[..] else { panic!("{what}: one flat child, got {flat:?}") };
let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") };
assert_eq!(*rule, FillRule::EvenOdd, "{what}");
let bez = path.to_bezpath();
assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled");
assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open");
assert!(index + 1 < children.len(), "{what}: the 3D art is drawn above");
}
#[test]
fn a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole() {
let red = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(RED)));
let blue = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(BLUE)));
let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 4.0));
for id in SOLIDS {
// The top fill and then the top stroke take the effect; the fill below stays flat.
for (top, on) in [(&red, "fill"), (&stroke, "stroke")] {
let mut lifted = top.clone();
lifted.effects_mut().push(fx(id, json!({})));
for (n, shape) in even_odd_shapes(vec![blue.clone(), lifted]).into_iter().zip(["compound path", "path"]) {
let what = format!("{id} on the top {on} of a {shape}");
let art = solid_art(&n).unwrap_or_else(|| panic!("{what}"));
assert_flat_item_keeps_the_hole(&art, &blue, &what);
}
}
}
}
#[test]
fn export_and_expand_bake_faces_with_their_own_ids() {
for id in SOLIDS {
+659
View File
@@ -0,0 +1,659 @@
use serde_json::json;
use vectorcraft_doc::color::Color;
use vectorcraft_doc::{StrokeLayer, Symbol};
use vectorcraft_geom::shapes;
use super::super::{EXTRUDE, INFLATE, ROTATE, graphic_frame, solid_art_in, three_d_params_as, validate_three_d_in, validate_three_d_params};
use super::*;
fn red() -> Color {
Color::rgb(1.0, 0.0, 0.0)
}
fn square(id: u64, r: Rect, paint: Paint) -> Node {
Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0))
}
/// A document with symbol "Mark": a red 10 × 10 square.
fn document() -> Document {
let mut d = Document::new(1000.0, 1000.0);
d.symbols.push(Symbol {
dynamic: false,
name: "Mark".into(),
art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), Paint::solid(red()))),
});
d
}
/// A gray 100 × 100 square at (0, 0) with effect `id`, its parameters `params` over a view
/// straight on.
fn object(id: &str, params: Value) -> Node {
let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false});
if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) {
p.extend(extra.clone());
}
let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
n.appearance.effects.push(crate::new_effect(id, &p).unwrap());
n
}
/// The graphics clip groups in `art`, in drawing order: each one's mapped paths.
fn graphics_in(art: &Node) -> Vec<Vec<(PathData, Paint)>> {
let mut out = vec![];
art.walk(&mut |n| {
if let NodeKind::Group { children, clip: true } = &n.kind
&& let [_, inner] = children.as_slice()
&& let NodeKind::Group { children: paths, clip: false } = &inner.kind
{
let paths: Vec<(PathData, Paint)> = paths
.iter()
.filter_map(|p| {
let fill = p.appearance.items.iter().find_map(|i| match i {
AppearanceItem::Fill(f) => Some(f.paint.clone()),
AppearanceItem::Stroke(_) => None,
})?;
Some((p.path_data()?.clone(), fill))
})
.collect();
if paths.iter().any(|(_, p)| p.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3)) {
out.push(paths);
}
}
});
out
}
fn bounds_of(paths: &[(PathData, Paint)]) -> Rect {
paths.iter().filter_map(|(p, _)| p.bounds()).reduce(|a, b| a.union(b)).unwrap()
}
fn close(a: Rect, b: Rect) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6)
}
#[test]
fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() {
let d = document();
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}]}));
let art = solid_art_in(Some(&d), &n).unwrap();
let found = graphics_in(&art);
assert_eq!(found.len(), 1);
// Straight on, the front cap is the art: a 20 × 20 square centered 20 right of and 10 above (50, 50).
assert!(close(bounds_of(&found[0]), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds_of(&found[0]));
// Turned 45°, the square's corners reach out to its half diagonal.
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "rotation": 45.0}]}));
let b = bounds_of(&graphics_in(&solid_art_in(Some(&d), &n).unwrap())[0]);
assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6);
}
#[test]
fn without_the_document_or_its_symbol_nothing_is_drawn() {
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]}));
let art = solid_art_in(None, &n).unwrap();
assert!(graphics_in(&art).is_empty());
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Gone"}]}));
assert!(graphics_in(&solid_art_in(Some(&document()), &n).unwrap()).is_empty());
// Without graphics, the art is the same as before they existed.
let plain = object(EXTRUDE, json!({}));
assert_eq!(solid_art_in(Some(&document()), &plain), solid_art_in(None, &plain));
}
#[test]
fn the_graphic_is_shaded_with_its_face() {
let d = document();
let n = object(EXTRUDE, json!({"shade": true, "lightIntensity": 0.0, "ambient": 50.0, "graphics": [{"symbol": "Mark"}]}));
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
let c = found[0][0].1.color().unwrap().to_rgb();
assert!((c[0] - 0.5).abs() < 1e-3 && c[1].abs() < 1e-6 && c[2].abs() < 1e-6, "{c:?}");
}
#[test]
fn the_graphic_goes_right_after_its_cap_and_is_clipped_to_it() {
let d = document();
let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 25.0, "graphics": [{"symbol": "Mark", "scale": 2000.0}]}));
let art = solid_art_in(Some(&d), &n).unwrap();
let NodeKind::Group { children, .. } = &art.kind else { panic!("a group") };
let NodeKind::Group { children: faces, .. } = &children.last().unwrap().kind else { panic!("the ordered faces") };
let last = faces.last().unwrap();
assert!(matches!(&last.kind, NodeKind::Group { clip: true, .. }), "the graphic is drawn last, over the front cap");
let NodeKind::Group { children: parts, .. } = &last.kind else { panic!() };
let clip = parts[0].path_data().unwrap().bounds().unwrap();
let cap = faces[faces.len() - 2].path_data().unwrap().bounds().unwrap();
assert!(close(clip, cap), "clipped to the cap: {clip:?} against {cap:?}");
}
#[test]
fn the_back_cap_reads_the_right_way_round_from_behind() {
let d = document();
let behind = json!({"rotationY": 180.0, "graphics": [{"symbol": "Mark", "face": "back", "x": 20.0}]});
let n = object(EXTRUDE, behind);
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
assert_eq!(found.len(), 1);
let b = bounds_of(&found[0]);
// Seen from behind, x runs to the right on the page too.
assert!((b.center().x - 70.0).abs() < 1e-6, "{b:?}");
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": 20.0})).unwrap();
let (at, visible) = frame.handle(&g).unwrap();
assert!(visible && (at.x - 70.0).abs() < 1e-6);
let (x, y) = frame.offset_at(PlanarFace::Back, Point::new(40.0, 55.0)).unwrap();
assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6);
// From the front the back cap is hidden, and so is its graphic.
let front = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "face": "back"}]}));
assert!(graphics_in(&solid_art_in(Some(&d), &front).unwrap()).is_empty());
}
#[test]
fn a_perspective_foreshortens_the_graphic_with_its_face() {
let d = document();
let params = json!({"rotationX": -30.0, "rotationY": 35.0, "perspectiveAngle": 100.0, "graphics": [{"symbol": "Mark", "scale": 400.0}]});
let n = object(EXTRUDE, params);
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let map = frame.map(PlanarFace::Front).unwrap();
// The corners of the 40 × 40 square centered on the object land where the face's map takes them.
let path = &found[0][0].0;
let corners: Vec<Point> = [(30.0, 30.0), (70.0, 30.0), (70.0, 70.0), (30.0, 70.0)].map(|(x, y)| map.to_page(Point::new(x, y)).unwrap()).into();
for c in corners {
let near = path.subpaths.iter().flat_map(|s| &s.anchors).map(|a| a.p.distance(c)).fold(f64::INFINITY, f64::min);
assert!(near < 1e-6, "{c:?} is {near} from the drawn graphic");
}
}
#[test]
fn a_graphic_behind_the_eye_leaves_the_others_drawn() {
let d = document();
let view = json!({"rotationX": -60.0, "rotationY": 0.0, "perspectiveAngle": 160.0});
let n = object(EXTRUDE, view.clone());
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let map = frame.map(PlanarFace::Front).unwrap();
let c = frame.bounds.center();
// An offset whose point of the front's plane is at or behind the eye.
let y = [1.0, -1.0]
.into_iter()
.flat_map(|s| (1..60).map(move |k| s * 10f64.powf(f64::from(k) / 10.0)))
.find(|y| map.local_affine(Point::new(c.x, c.y + y)).is_none())
.expect("an offset behind the eye");
let mut params = view;
params["graphics"] = json!([{"symbol": "Mark"}, {"symbol": "Mark", "y": y}]);
let found = graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, params)).unwrap());
assert_eq!(found.len(), 1, "the graphic that projects is still drawn");
// A graphic centered there but large enough to reach over the cap draws the part in front.
let mut params = json!({"rotationX": -60.0, "rotationY": 0.0, "perspectiveAngle": 160.0});
params["graphics"] = json!([{"symbol": "Mark", "y": y, "scale": (20.0 * (y.abs() + 50.0)).clamp(1.0, 10_000.0)}]);
let found = graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, params)).unwrap());
assert_eq!(found.len(), 1, "the part in front is drawn (offset {y})");
assert!(!found[0].is_empty());
}
#[test]
fn the_graphic_takes_the_opacity_of_its_fill() {
let d = document();
for id in [EXTRUDE, ROTATE] {
let mut n = object(id, json!({"graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.opacity = 0.25;
}
let art = solid_art_in(Some(&d), &n).unwrap();
let mut opacities = vec![];
art.walk(&mut |c| {
if matches!(c.kind, NodeKind::Group { clip: true, .. }) {
opacities.push(c.opacity);
}
});
assert_eq!(opacities, vec![0.25], "{id}");
}
}
#[test]
fn the_graphic_takes_the_blending_mode_of_its_fill() {
let d = document();
for id in [EXTRUDE, ROTATE] {
let mut n = object(id, json!({"graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.blend = BlendMode::Multiply;
}
let art = solid_art_in(Some(&d), &n).unwrap();
let mut blends = vec![];
art.walk(&mut |c| {
if matches!(c.kind, NodeKind::Group { clip: true, .. }) {
blends.push(c.blend);
}
});
assert_eq!(blends, vec![BlendMode::Multiply], "{id}");
}
}
#[test]
fn each_fill_of_a_plane_gives_its_graphic_its_own_opacity() {
let d = document();
let mut n = object(ROTATE, json!({"graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.opacity = 0.25;
}
let mut second = FillLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2)));
second.opacity = 0.75;
n.appearance.items.push(AppearanceItem::Fill(second));
let art = solid_art_in(Some(&d), &n).unwrap();
let mut opacities = vec![];
art.walk(&mut |c| {
if matches!(c.kind, NodeKind::Group { clip: true, .. }) {
opacities.push(c.opacity);
}
});
opacities.sort_by(f32::total_cmp);
assert_eq!(opacities, vec![0.25, 0.75]);
}
#[test]
fn a_symbols_gradient_takes_the_size_of_its_art() {
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
let mut d = document();
// Symbol art kept in its 20 × 20 square, drawn 40 × 20.
let mut g = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)]));
g.geom = Some(GradientGeom { start: Point::new(-10.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None });
let art = square(0, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::Gradient(Box::new(g)));
d.symbols.push(Symbol { dynamic: false, name: "Ramp".into(), art: Arc::new(art) });
d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({"Ramp": [40.0, 20.0]}));
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Ramp"}]}));
let out = solid_art_in(Some(&d), &n).unwrap();
let mut found = None;
out.walk(&mut |c| {
if let (Some(p), Some(AppearanceItem::Fill(f))) = (c.path_data(), c.appearance.items.first())
&& let Paint::Gradient(g) = &f.paint
{
found = Some((p.bounds().unwrap(), g.geom.unwrap()));
}
});
let (bounds, geom) = found.unwrap();
assert!(close(bounds, Rect::new(30.0, 40.0, 70.0, 60.0)), "{bounds:?}");
assert!(geom.start.distance(Point::new(30.0, 50.0)) < 1e-6 && geom.end.distance(Point::new(70.0, 50.0)) < 1e-6, "{geom:?}");
}
#[test]
fn a_symbols_pattern_follows_the_graphic() {
let mut d = document();
let tiles = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY };
d.symbols.push(Symbol { dynamic: false, name: "Tiles".into(), art: Arc::new(square(0, Rect::new(-10.0, -10.0, 10.0, 10.0), tiles)) });
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Tiles", "scale": 200.0}]}));
let out = solid_art_in(Some(&d), &n).unwrap();
let mut found = None;
out.walk(&mut |c| {
if let Some(AppearanceItem::Fill(f)) = c.appearance.items.first()
&& let Paint::Pattern { xf, .. } = &f.paint
{
found = Some((c.path_data().unwrap().bounds().unwrap(), *xf));
}
});
let (bounds, xf) = found.unwrap();
// The 20 × 20 art drawn 40 × 40 on the middle of the front: its tiles go with it.
assert!(close(bounds, Rect::new(30.0, 30.0, 70.0, 70.0)), "{bounds:?}");
assert!((xf * Point::new(-10.0, -10.0)).distance(Point::new(30.0, 30.0)) < 1e-6, "{xf:?}");
assert!((xf * Point::new(10.0, 10.0)).distance(Point::new(70.0, 70.0)) < 1e-6, "{xf:?}");
}
#[test]
fn a_curve_in_front_of_the_eye_maps_though_its_control_points_do_not() {
let bounds = Rect::new(10.0, 20.0, 70.0, 60.0);
let view = vectorcraft_three_d::View { rotation_x: -89.0, rotation_y: 40.0, rotation_z: 10.0, perspective: 160.0, ..Default::default() };
let map = vectorcraft_three_d::plane_face_map(bounds, view).unwrap();
// Where the page map stops along the line x = `x`, between the center and a point it does not map.
let edge = |x: f64| {
let inside = Point::new(x, bounds.center().y);
let far = [Point::new(x, -1e6), Point::new(x, 1e6)].into_iter().find(|p| map.to_page(*p).is_none()).unwrap();
let (mut a, mut b) = (inside, far);
for _ in 0..200 {
let m = a.midpoint(b);
if map.to_page(m).is_some() { a = m } else { b = m }
}
a
};
let (b1, b2) = (edge(40.0), edge(60.0));
let u = (b2 - b1).normalize();
let mut n = vectorcraft_geom::Vec2::new(-u.y, u.x);
if map.to_page(b1 + n * 10.0).is_none() {
n = -n;
}
// Ends 219.17 in front of that line and control points 100 and 42 past it: the curve stays
// about 1 in front, while a control point of one of the pieces it is cut into falls behind.
let at = |s: f64, t: f64| b1 + n * s + u * t;
let mut curve = BezPath::new();
curve.move_to(at(219.17, 0.0));
curve.curve_to(at(-100.0, 5.0), at(-42.0, 15.0), at(219.17, 20.0));
let c = CubicBez::new(at(219.17, 0.0), at(-100.0, 5.0), at(-42.0, 15.0), at(219.17, 20.0));
assert!((0..=1000).all(|k| map.to_page(c.eval(k as f64 / 1000.0)).is_some()), "the curve itself is in front");
let pieces = (0..PERSPECTIVE_PIECES).map(|k| c.subsegment(k as f64 / 8.0..(k + 1) as f64 / 8.0));
assert!(pieces.flat_map(|s| [s.p1, s.p2]).any(|p| map.to_page(p).is_none()), "a piece's control point is behind");
let mapped = map_path(&PathData::from_bezpath(&curve), &map, None, usize::MAX).expect("the curve maps");
// The split pieces count toward the room the path is given: without room, the path is full,
// not behind the eye, so it is not clipped.
assert!(mapped.elements().len() > 1 + PERSPECTIVE_PIECES);
assert_eq!(map_path(&PathData::from_bezpath(&curve), &map, None, PERSPECTIVE_PIECES + 1).err(), Some(NotMapped::Full));
assert!(mapped.elements().iter().all(|e| e.end_point().is_none_or(|p| p.x.is_finite() && p.y.is_finite())));
// That piece is split until its halves' control points map, so it stays a curve.
assert!(mapped.elements().iter().all(|e| !matches!(e, PathEl::LineTo(_))), "{mapped:?}");
// With its ends at 214.25 instead, the curve dips about 0.24 behind the line between the ends
// of two pieces, which still map: it has no page point there, and is left to the clipping.
let c = CubicBez::new(at(214.25, 0.0), at(-100.0, 5.0), at(-42.0, 15.0), at(214.25, 20.0));
assert!((0..=PERSPECTIVE_PIECES).all(|k| map.to_page(c.eval(k as f64 / 8.0)).is_some()));
assert!((0..=1000).any(|k| map.to_page(c.eval(k as f64 / 1000.0)).is_none()));
let mut dips = BezPath::new();
dips.move_to(c.p0);
dips.curve_to(c.p1, c.p2, c.p3);
assert_eq!(map_path(&PathData::from_bezpath(&dips), &map, None, usize::MAX).err(), Some(NotMapped::Behind));
}
#[test]
fn members_with_their_own_blending_get_graphics_of_their_own() {
let d = document();
let a = square(1, Rect::new(0.0, 0.0, 50.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
let mut b = square(2, Rect::new(50.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
b.blend = BlendMode::Multiply;
let mut group = Node::group(NodeId(3), vec![Arc::new(a), Arc::new(b)]);
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 1000.0}]});
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
let art = solid_art_in(Some(&d), &group).unwrap();
let found = graphics_in(&art);
// One graphic clipped to each member's cap: the second stays inside the member's Multiply group.
assert_eq!(found.len(), 2);
let mut blended = 0;
art.walk(&mut |c| {
if c.blend == BlendMode::Multiply {
blended += graphics_in(c).len();
}
});
assert_eq!(blended, 1);
}
/// [`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();
let mut poly = BezPath::new();
let mut last = Point::ZERO;
for k in 0..30_000 {
let a = k as f64 / 30_000.0 * std::f64::consts::TAU;
let p = Point::new(5.0 + 5.0 * a.cos(), 5.0 + 5.0 * a.sin());
if k == 0 {
poly.move_to(p);
} else if curved {
poly.curve_to(last.lerp(p, 1.0 / 3.0), last.lerp(p, 2.0 / 3.0), p);
} else {
poly.line_to(p);
}
last = p;
}
poly.close_path();
let art = Node::path(NodeId(0), PathData::from_bezpath(&poly), Appearance::basic(Paint::solid(red()), Paint::None, 0.0));
d.symbols.push(Symbol { dynamic: false, name: "Dense".into(), art: Arc::new(art) });
d
}
/// The graphics drawn on a group of two members, each with its own graphic of symbol "Dense"
/// ([`dense_document`]), seen under a perspective.
fn dense_graphics_drawn(curved: bool) -> usize {
let d = dense_document(curved);
let a = square(1, Rect::new(0.0, 0.0, 50.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
let mut b = square(2, Rect::new(50.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
b.blend = BlendMode::Multiply;
let mut group = Node::group(NodeId(3), vec![Arc::new(a), Arc::new(b)]);
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "perspectiveAngle": 60.0, "shade": false, "graphics": [{"symbol": "Dense", "scale": 1000.0}]});
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
graphics_in(&solid_art_in(Some(&d), &group).unwrap()).len()
}
#[test]
fn members_with_graphics_of_their_own_share_one_element_limit() {
// A perspective cuts each of the 30,000 curves into 8: one copy fits the limit, two do not.
// The first member's graphic is drawn; the second would pass the limit, so it draws none.
assert_eq!(dense_graphics_drawn(true), 1);
}
#[test]
fn straight_sides_count_once_under_a_perspective() {
// A perspective keeps each of the 30,000 straight sides one element: both copies fit the limit.
assert_eq!(dense_graphics_drawn(false), 2);
}
#[test]
fn the_symbol_check_counts_what_the_view_draws() {
// Two graphics of the 30,000-sided polygon under a perspective: straight, they fit the limit;
// curved, they do not.
let two = json!({"perspectiveAngle": 60.0, "graphics": [{"symbol": "Dense"}, {"symbol": "Dense", "face": "back"}]});
let n = object(EXTRUDE, two.clone());
assert!(validate_three_d_in(Some(&dense_document(false)), &n, EXTRUDE, &two).is_ok());
let e = validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &two).unwrap_err();
assert!(e.contains("too complex"), "{e}");
// Without a perspective each curve draws once: curved, they fit too.
let flat = json!({"perspectiveAngle": 0.0, "graphics": two["graphics"].clone()});
assert!(validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &flat).is_ok());
}
#[test]
fn a_plane_and_a_hollow_solid() {
let d = document();
let plane = object(ROTATE, json!({"rotationY": 30.0, "graphics": [{"symbol": "Mark"}]}));
assert_eq!(graphics_in(&solid_art_in(Some(&d), &plane).unwrap()).len(), 1);
let hollow = object(EXTRUDE, json!({"cap": false, "graphics": [{"symbol": "Mark"}]}));
assert!(graphics_in(&solid_art_in(Some(&d), &hollow).unwrap()).is_empty());
}
#[test]
fn a_stroked_graphic_draws_its_stroke_as_an_outline() {
let mut d = document();
let mut ring = square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::None);
ring.appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(red()), 2.0))], ..Default::default() }.into();
d.symbols.push(Symbol { dynamic: false, name: "Ring".into(), art: Arc::new(ring) });
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Ring"}]}));
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
// The 10 × 10 square's 2 pt stroke reaches 1 pt outside it.
assert!(close(bounds_of(&found[0]), Rect::new(44.0, 44.0, 56.0, 56.0)), "{:?}", bounds_of(&found[0]));
}
#[test]
fn graphics_are_checked() {
let n = object(EXTRUDE, json!({}));
let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics}));
assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok());
assert!(check(EXTRUDE, json!([])).is_ok());
for bad in [
json!("Mark"),
json!([{"face": "front"}]),
json!([{"symbol": ""}]),
json!([{"symbol": "Mark", "face": "side"}]),
json!([{"symbol": "Mark", "scale": 0.0}]),
json!([{"symbol": "Mark", "rotation": 400.0}]),
json!([{"symbol": "Mark", "x": "1"}]),
json!([{"symbol": "Mark", "repeat": true}]),
json!(vec![json!({"symbol": "Mark"}); MAX_GRAPHICS + 1]),
] {
assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}");
}
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err());
assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err());
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err());
// A loaded file's invalid entries are left out when drawn.
assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1);
}
#[test]
fn the_frame_at_an_index_is_that_effects() {
let d = document();
let mut n = object(EXTRUDE, json!({}));
n.appearance.effects.push(crate::new_effect(ROTATE, &json!({})).unwrap());
// The first 3D effect is the Extrude & Bevel, with a back cap; the second is a plane, without.
assert!(graphic_frame(Some(&d), &n, None).unwrap().map(PlanarFace::Back).is_some());
assert!(super::super::graphic_frame_at(Some(&d), &n, None, 0).unwrap().map(PlanarFace::Back).is_some());
assert!(super::super::graphic_frame_at(Some(&d), &n, None, 1).unwrap().map(PlanarFace::Back).is_none());
assert!(super::super::graphic_frame_at(Some(&d), &n, None, 2).is_none());
}
#[test]
fn a_change_to_a_plane_drops_the_back_caps_graphics() {
let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]});
let plane = three_d_params_as(EXTRUDE, &p, ROTATE);
assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}]));
assert!(validate_three_d_params(ROTATE, &plane).is_ok());
// Back to Extrude & Bevel, the front's graphic stays.
assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]);
}
#[test]
fn a_stroked_solid_carries_its_graphic_too() {
let d = document();
let mut n = Node::path(
NodeId(7),
shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)),
Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 20.0),
);
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 2000.0}]});
n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
assert_eq!(graphics_in(&solid_art_in(Some(&d), &n).unwrap()).len(), 1);
}
#[test]
fn art_nested_too_deep_is_refused_and_not_drawn() {
let mut d = document();
let mut art = square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()));
for k in 0..=MAX_LEVELS {
art = Node::group(NodeId(k as u64 + 1), vec![Arc::new(art)]);
}
d.symbols.push(Symbol { dynamic: false, name: "Deep".into(), art: Arc::new(art) });
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]}));
let e = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Deep"}]})).unwrap_err();
assert!(e.contains("nested"), "{e}");
assert!(graphics_in(&solid_art_in(Some(&d), &n).unwrap()).is_empty());
// A loaded file draws its other graphics.
let both = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}, {"symbol": "Mark"}]}));
assert_eq!(graphics_in(&solid_art_in(Some(&d), &both).unwrap()).len(), 1);
}
#[test]
fn symbols_nested_too_deep_are_refused_and_not_drawn() {
let mut d = document();
// Symbol `N{k}` holds an instance of `N{k-1}`, and `N0` is a square.
d.symbols.push(Symbol { dynamic: false, name: "N0".into(), art: Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()))) });
for k in 1..=MAX_NESTING + 1 {
let instance = Node::new(NodeId(k as u64), NodeKind::SymbolInstance { symbol: format!("N{}", k - 1), xf: Affine::IDENTITY });
d.symbols.push(Symbol { dynamic: false, name: format!("N{k}"), art: Arc::new(instance) });
}
let deepest = format!("N{MAX_NESTING}");
let p = json!({"graphics": [{"symbol": deepest}]});
assert!(validate_three_d_in(Some(&d), &object(EXTRUDE, p.clone()), EXTRUDE, &p).is_ok());
assert_eq!(graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, p)).unwrap()).len(), 1);
let past = format!("N{}", MAX_NESTING + 1);
let p = json!({"graphics": [{"symbol": past}]});
let e = validate_three_d_in(Some(&d), &object(EXTRUDE, p.clone()), EXTRUDE, &p).unwrap_err();
assert!(e.contains("nest"), "{e}");
assert!(graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, p)).unwrap()).is_empty());
}
#[test]
fn a_solid_in_a_transparent_gradient_keeps_its_graphic() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let d = document();
let mut stop = GradientStop::new(1.0, red());
stop.opacity = 0.25;
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
// Under a colored light the faces are drawn opaque and masked by the gradient's transparency.
let mut n = object(EXTRUDE, json!({"shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Gradient(Box::new(gradient));
}
let art = solid_art_in(Some(&d), &n).unwrap();
let mut masked = false;
art.walk(&mut |c| masked |= c.extras().mask.is_some());
assert!(masked);
assert_eq!(graphics_in(&art).len(), 1);
// Each graphic clip group in `art`, in drawing order: whether it carries an opacity mask.
let masks = |art: &Node| {
let mut out = vec![];
art.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind
&& let [_, inner] = children.as_slice()
&& matches!(inner.kind, NodeKind::Group { clip: false, .. })
{
out.push(c.extras().mask.is_some());
}
});
out
};
// The graphic carries the cap's mask, so it is hidden where the gradient is transparent.
assert_eq!(masks(&art), vec![true]);
// With an opaque stroke drawn after the fill, the fill's cap keeps a masked graphic of its own
// and the stroke's outline gets an unmasked one.
n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0)));
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]);
}
#[test]
fn a_cap_with_a_hole_keeps_the_hole_out_of_the_graphic() {
let d = document();
let outer = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath();
let hole = shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)).to_bezpath().reverse_subpaths();
let mut ring = outer;
ring.extend(hole.iter());
for flip in [false, true] {
let ring = if flip { ring.reverse_subpaths() } else { ring.clone() };
let mut n =
Node::path(NodeId(7), PathData::from_bezpath(&ring), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0));
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 2000.0}]});
n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
let art = solid_art_in(Some(&d), &n).unwrap();
let mut clips = vec![];
art.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind {
clips.push(children[0].path_data().unwrap().to_bezpath());
}
});
assert_eq!(clips.len(), 1, "flip {flip}");
assert_ne!(clips[0].winding(Point::new(10.0, 10.0)), 0, "flip {flip}: the ring is inside the clip");
assert_eq!(clips[0].winding(Point::new(50.0, 50.0)), 0, "flip {flip}: the hole is outside it");
}
}
#[test]
fn a_graphic_starts_inside_its_object() {
let d = document();
let frame = graphic_frame(Some(&d), &object(EXTRUDE, json!({})), None).unwrap();
assert_eq!(frame.fitting_scale(Rect::new(0.0, 0.0, 10.0, 10.0)), 100.0);
assert!((frame.fitting_scale(Rect::new(0.0, 0.0, 400.0, 200.0)) - 25.0).abs() < 1e-9);
assert_eq!(super::super::graphic_bounds(&d, "Mark"), Some(Rect::new(500.0, 500.0, 510.0, 510.0)));
}
#[test]
fn a_symbol_instance_in_a_graphic_draws_as_the_canvas_shows_it() {
let mut d = document();
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
// A dynamic symbol whose instance in "Changed" fills its square blue instead of red.
d.symbols.push(Symbol { dynamic: true, name: "Dynamic".into(), art: Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()))) });
let mut changed = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "Dynamic".into(), xf: Affine::IDENTITY });
changed.extras_mut().symbol_overrides =
vec![vectorcraft_doc::symbol_overrides::SymbolOverride { fill: Some(blue.clone()), ..Default::default() }];
d.symbols.push(Symbol { dynamic: false, name: "Changed".into(), art: Arc::new(changed) });
let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "Changed").unwrap()).unwrap();
assert_eq!(pieces.iter().map(|p| p.paint.clone()).collect::<Vec<_>>(), [blue]);
// A symbol with 9-slice guides, a 100 × 100 square with a 10 × 10 one in its corner, placed
// three times as wide: the corner keeps its width while the rest stretches.
let corner = square(2, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()));
let whole = square(3, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(red()));
d.symbols.push(Symbol { dynamic: false, name: "Sliced".into(), art: Arc::new(Node::group(NodeId(4), vec![Arc::new(whole), Arc::new(corner)])) });
d.set_symbol_nine_slice("Sliced", Some(vectorcraft_doc::SymbolNineSlice::default()));
let wide = Node::new(NodeId(5), NodeKind::SymbolInstance { symbol: "Sliced".into(), xf: Affine::scale_non_uniform(3.0, 1.0) });
d.symbols.push(Symbol { dynamic: false, name: "Wide".into(), art: Arc::new(wide) });
let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "Wide").unwrap()).unwrap();
let widths: Vec<f64> = pieces.iter().map(|p| p.path.bounds().unwrap().width()).collect();
assert_eq!(widths.len(), 2);
assert!((widths[1] / widths[0] - 1.0 / 30.0).abs() < 1e-6, "{widths:?}");
// With a gradient, the square crossing the guides is cut at them: its pieces cover the
// placed 300 × 100 once, not one whole copy for each cell.
use vectorcraft_doc::color::{Gradient, GradientPaint};
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
let shaded = square(6, Rect::new(0.0, 0.0, 100.0, 100.0), gradient);
d.symbols.push(Symbol { dynamic: false, name: "Shaded".into(), art: Arc::new(Node::group(NodeId(7), vec![Arc::new(shaded)])) });
d.set_symbol_nine_slice("Shaded", Some(vectorcraft_doc::SymbolNineSlice::default()));
let wide = Node::new(NodeId(8), NodeKind::SymbolInstance { symbol: "Shaded".into(), xf: Affine::scale_non_uniform(3.0, 1.0) });
d.symbols.push(Symbol { dynamic: false, name: "WideShaded".into(), art: Arc::new(wide) });
let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "WideShaded").unwrap()).unwrap();
let area: f64 = pieces.iter().map(|p| p.path.to_bezpath().area().abs()).sum();
assert!((area - 30_000.0).abs() < 1e-3, "{area}");
}
@@ -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 {
+21 -3
View File
@@ -6,20 +6,38 @@
use std::sync::Arc;
use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_geom::{Point, Rect, Shape};
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
/// The largest distance between the edges of `a` and `b`.
fn off(a: Rect, b: Rect) -> f64 {
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()))
}
/// "Type" at 48 pt in a face the test adds, so its glyphs draw on a machine without craft-fonts or
/// system fonts.
fn type_in_test_face() -> TextObject {
assert!(vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()) > 0, "the test face loads");
TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { font_family: HEIGHT_FAMILY.into(), size: 48.0, ..Default::default() })
}
/// The box of the outlines `t`'s glyphs draw, in document space, measured glyph by glyph.
fn outline_box(t: &TextObject) -> Rect {
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let outlines: Vec<Rect> = laid.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| (t.xf * &g.outline).bounding_box()).collect();
assert_eq!(outlines.len(), 4, "every glyph of \"Type\" draws an outline");
outlines.into_iter().reduce(|a, b| a.union(b)).unwrap()
}
#[test]
fn live_evaluation_measures_type_in_envelopes_by_its_glyphs() {
let t = TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { size: 48.0, ..Default::default() });
let t = type_in_test_face();
let n = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
let laid = n.geometric_bounds().unwrap();
let ink = t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap());
let ink = outline_box(&t);
assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}");
let measured = vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap();
assert!(off(measured, ink) < 1e-6, "the envelope measure gives the glyphs' box: {measured:?} vs {ink:?}");
let before = vectorcraft_doc::live::envelope_content_bounds(std::slice::from_ref(&n)).unwrap();
assert!(off(before, laid) < 1e-6, "with nothing registered, type keeps its laid-out box: {before:?} vs {laid:?}");
+7 -2
View File
@@ -426,8 +426,13 @@ pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
pub(crate) fn f64_or(p: &Value, key: &str, default: f64) -> f64 {
p.get(key).and_then(Value::as_f64).unwrap_or(default)
}
/// The number `p` gives for `key`. A missing key or null is "missing number `{key}`"; any other
/// value, such as `"40"`, is "`{key}` must be a number, not {v}", as [`number_or`] words it.
pub(crate) fn f64_req(p: &Value, key: &str, cmd: &str) -> Result<f64> {
p.get(key).and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("missing number `{key}`")))
match p.get(key) {
None | Some(Value::Null) => Err(bad(cmd, format!("missing number `{key}`"))),
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
}
}
/// The number `p` gives for `key`, or `default` when `p` leaves it out or gives null. Any other
/// value, such as `"40"`, is an error: "`{key}` must be a number, not {v}".
@@ -772,7 +777,7 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
/// The most presets one presets file imports: each is looked up among the saved ones.
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::DecodedImages;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
pub use docmenu::guide_indexes;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
+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;
+6 -5
View File
@@ -12,7 +12,7 @@ use vectorcraft_doc::{CharStyle, Document, Justify, Node, NodeId, NodeKind, Para
use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit};
use crate::cmd::fonts::{edit_symbol_texts, symbol_texts};
use crate::cmd::fonts::{art_texts_of, edit_art_texts_of};
use crate::cmd::textedit::{editing_range, editing_story};
use crate::cmd::typecmd::refresh_bounds;
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Missing Fonts…",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in the art of its symbols included) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in its opacity masks and in the art of its symbols and patterns included, hidden or locked type and disabled masks too) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
has_doc,
replace_fonts
),
@@ -982,8 +982,9 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
}
});
}
// The type in the symbols' art too, which exports name when its font is missing.
if ids.is_empty() && !symbol_texts(d, None).into_iter().any(|(t, _)| lacks(t)) {
// The type in opacity masks and in the art of symbols and patterns too, hidden or locked type
// included, which exports name when its font is missing.
if ids.is_empty() && !art_texts_of(d).into_iter().any(|(_, t, _)| lacks(t)) {
return Err(EngineError::Other("No fonts are missing".into()));
}
let runs = s.edit("Replace Missing Fonts", |d, _| {
@@ -1008,7 +1009,7 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
replace(t);
}
}
edit_symbol_texts(d, None, &|t, _| lacks(t), &mut replace);
edit_art_texts_of(d, &lacks, &mut replace);
Ok(runs)
})?;
Ok(json!({ "runs": runs, "font": family }))
@@ -415,3 +415,53 @@ fn replace_missing_fonts_reaches_the_type_in_symbols() {
s.execute("symbol.exitEditing", &json!({})).unwrap();
assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None);
}
/// Replace Missing Fonts reaches the type in opacity masks (of a hidden object, disabled, in a
/// symbol's art) and in a pattern swatch nothing paints with, and the export warning, the missing
/// fonts list and Find Font name that type's font until it is replaced.
#[test]
fn replace_missing_fonts_reaches_the_type_in_masks_and_patterns() {
let mut s = session();
let mask = |s: &mut Session, owner: NodeId, art: NodeId| {
s.edit("Mask", |d, _| {
let art = d.remove(art)?;
d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
Ok(())
})
.unwrap();
};
let lost = |s: &mut Session| text(s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family"}));
let rect =
|s: &mut Session| NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap());
let (hidden, disabled, in_symbol) = (rect(&mut s), rect(&mut s), rect(&mut s));
for owner in [hidden, disabled, in_symbol] {
let t = lost(&mut s);
mask(&mut s, owner, t);
}
s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap();
s.execute("object.hide", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [disabled.0]})).unwrap();
s.execute("transparency.disableOpacityMask", &json!({})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap();
let t = lost(&mut s);
s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap();
select(&mut s, &[t]);
s.execute("edit.clear", &json!({})).unwrap();
let mut on_layers = 0;
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
assert_eq!(on_layers, 0, "the type is only in masks, a symbol and a pattern");
let missing = |s: &Session| crate::cmd::fontfiles::missing_fonts(&s.doc().unwrap().doc).into_iter().map(|f| f.family).collect::<Vec<_>>();
assert_eq!(missing(&s), ["No Such Font Family"]);
assert!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc).is_some_and(|w| w.contains("No Such Font Family")));
let listed = s.execute("text.fonts", &json!({})).unwrap();
assert_eq!((listed[0]["family"].as_str(), listed[0]["objects"].as_u64()), (Some("No Such Font Family"), Some(4)), "{listed}");
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap();
assert_eq!(r["runs"].as_u64(), Some(4), "{r}");
assert_eq!(steps(&s), before + 1);
assert!(missing(&s).is_empty());
assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None);
assert_eq!(other(s.execute("addon.cleanup.replaceFonts", &json!({}))), "No fonts are missing");
assert_eq!(steps(&s), before + 1);
}
+1 -1
View File
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Weed Box and Lines…",
["Object", "Plug-ins", "Cutting Tools"],
None,
"{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt (instead of count: as few lines as keep them at most this far apart), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}",
"{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt more than 0 and at most 100000 (instead of count, never with it: as few lines as keep them at most this far apart, up to 1000 each way), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}",
has_selection,
weed
)]
@@ -723,12 +723,13 @@ pub(super) fn lines(region: &Region, outline: &[Segment], frame: Rect, n: Counts
continue;
}
// The lines (0-based) each outline segment comes within `gap` of: lines k (1-based) lie at
// v0 + k·step.
// v0 + k·step. The range is widened by a small tolerance so that a line whose position
// rounds just past a segment's end is still measured; `near` drops lines the segment misses.
let reach = |&(a, b): &Segment| {
let (va, vb) = (uv(a, vertical).1, uv(b, vertical).1);
let (lo, hi) = (va.min(vb) - gap, va.max(vb) + gap);
let first = ((lo - v0) / step).ceil().max(1.0);
let last = ((hi - v0) / step).floor().min(count as f64);
let first = ((lo - v0) / step - 1e-9).ceil().max(1.0);
let last = ((hi - v0) / step + 1e-9).floor().min(count as f64);
if step > 0.0 && first <= last { (first as usize - 1)..(last as usize) } else { 0..0 }
};
// The outlines near each line, found once for all of them, by index into `outline`.
@@ -541,6 +541,24 @@ fn indexed_crossings_find_the_same_stretches() {
}
}
/// An outline that lies on a weeding line stops it even when the line's position rounds just past
/// the outline's: the one line across 0.1 to 0.5 lies at 0.1 + 0.2, which is 0.30000000000000004,
/// and (0.30000000000000004 - 0.1) / 0.2 is 1.0000000000000002.
#[test]
fn an_outline_on_a_rounded_line_position_stops_the_line() {
let doc = vectorcraft_doc::Document::new(800.0, 600.0);
let c = 0.1 + 0.2;
let mut p = BezPath::new();
p.move_to((20.0, c));
p.line_to((80.0, c));
let n = Node::path(NodeId(1), PathData::from_bezpath(&p), Appearance::default());
let region = super::geometry::Reader::new(&doc).read(&[&n]).unwrap().unwrap();
let outline = region.outline().unwrap();
let counts = super::geometry::Counts { horizontal: 1, vertical: 0 };
let pieces = super::geometry::lines(&region, &outline, Rect::new(0.0, 0.1, 100.0, 0.5), counts, 0.0, 100).unwrap();
assert_eq!(pieces, [(Point::new(0.0, c), Point::new(20.0, c)), (Point::new(80.0, c), Point::new(100.0, c))]);
}
#[test]
fn art_nested_too_deep_is_refused() {
// A rectangle inside `levels` groups, each holding the next. A document keeps none this deep,
+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));
}
+13 -4
View File
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Align",
[],
None,
"{index? | indices?: [n…], selectedArtboards?: [n…] (as artboard.duplicate; default: the artboards the Artboard tool has selected, else its active one), horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\" (one of the two is needed), to?: \"selection\"|\"artboard\" (default \"selection\": the bounds of the artboards together; \"artboard\": artboard `artboard`, which stays where it is), artboard?: n (0-based; the artboard to align to with to: \"artboard\"; default: the Artboard tool's active one; it need not be one of the artboards aligned), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it), moveArt?: bool (the art fully inside each artboard moves with it; default: the Artboard tool's Move Artwork with Artboard option), patterns?: bool, lockedAndHidden?: bool (as artboard.move)} (Align panel › Align Objects with the Artboard tool chosen) each artboard moves until its edge or center is on that edge or center of what it aligns to, with its guides, in one undo step; a locked artboard stays where it is and still counts in the bounds, and the call fails with `the artboard is locked` when every artboard it names is locked; when no artboard moves, no undo step is recorded → {moved: [index…]}",
"{index? | indices?: [n…], selectedArtboards?: [n…] (as artboard.duplicate; default: the artboards the Artboard tool has selected, else its active one), horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\" (one of the two is needed), to?: \"selection\"|\"artboard\" (default \"selection\": the bounds of the artboards together; \"artboard\": artboard `artboard`, which stays where it is), artboard?: n (0-based; the artboard to align to with to: \"artboard\"; default: the Artboard tool's active one; it need not be one of the artboards aligned), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it), moveArt?: bool (the art fully inside each artboard moves with it, art inside two of them with the first by index, which may stay; default: the Artboard tool's Move Artwork with Artboard option), patterns?: bool, lockedAndHidden?: bool (as artboard.move)} (Align panel › Align Objects with the Artboard tool chosen) each artboard moves until its edge or center is on that edge or center of what it aligns to, with its guides, in one undo step; a locked artboard stays where it is and still counts in the bounds, and the call fails with `the artboard is locked` when every artboard it names is locked; when no artboard moves, no undo step is recorded → {moved: [index…]}",
has_doc,
align
),
@@ -114,18 +114,27 @@ fn kept(b: &Boards, items: &[(usize, Rect)], gap: Option<f64>) -> Result<Option<
}
/// Moves each artboard of `moves` by its offset as undo step `label`, with its guides and, when
/// `b` says so, the art inside it. Locked artboards stay where they are. When no artboard moves
/// `b` says so, the art inside it; art inside two of the artboards `b` names goes with the one
/// first in artboard order, and stays when that one stays. Locked artboards stay where they are.
/// When no artboard moves
/// more than 1e-9 pt on either axis, the document and its undo history stay as they are. The edit
/// fails with nothing changed when an artboard would end up past the canvas, as every edit does.
fn apply(s: &mut Session, label: &str, p: &Value, b: &Boards, moves: &[(usize, Vec2)]) -> Result<Value> {
let d = &s.doc()?.doc;
let moves: Vec<(usize, Vec2)> =
let mut moves: Vec<(usize, Vec2)> =
moves.iter().copied().filter(|(i, dv)| (dv.x.abs() > 1e-9 || dv.y.abs() > 1e-9) && d.artboards.get(*i).is_some_and(|a| !a.locked)).collect();
// In artboard order, as the other artboard edits take them, whatever order the Distribute
// commands spaced them in.
moves.sort_by_key(|(i, _)| *i);
let moved: Vec<usize> = moves.iter().map(|(i, _)| *i).collect();
if moves.is_empty() {
return Ok(json!({ "moved": moved }));
}
let arts = artboards_art(s, &moved, b.move_art, b.locked_art, true)?;
// The art of every artboard named, those that stay included, so that art on overlapping
// artboards goes with the first by index; then that of the artboards that move.
let named: Vec<usize> = b.items.iter().map(|(i, _)| *i).collect();
let arts: Vec<(usize, Vec<NodeId>)> =
artboards_art(s, &named, b.move_art, b.locked_art, true)?.into_iter().filter(|(i, _)| moved.contains(i)).collect();
let ids: Vec<NodeId> = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect();
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() };
s.edit(label, |d, _| {
@@ -265,6 +265,39 @@ fn bad_params_are_errors() {
assert_eq!((undo_steps(&s), corners(&s)), (steps, before));
}
/// Art inside two overlapping artboards moves with the one first in artboard order, as with the
/// other artboard edits, even when Distribute spaces the other one first: artboard 2 at x 140 is
/// left of artboard 1 at x 200, and the square inside both goes with artboard 1.
#[test]
fn art_on_overlapping_artboards_moves_with_the_first_by_index() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 140, "y": 0, "width": 100, "height": 100})).unwrap();
let sq = s.execute("shape.rectangle", &json!({"x": 210, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.none", &json!({})).unwrap();
let p = json!({"indices": ALL, "to": "artboard", "artboard": 0, "spacing": 10});
assert_eq!(s.execute("artboard.distributeSpacing", &p).unwrap(), json!({"moved": [1, 2]}));
assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 0.0), (110.0, 0.0)]);
assert_eq!(corner(&s, sq), (230.0, 10.0), "with artboard 1, 20 pt to the right");
}
/// Art inside an artboard that stays and a later one that moves stays with the first: artboard 2
/// overlaps artboard 0, and aligning it to artboard 0 leaves the square inside both in place.
#[test]
fn art_shared_with_an_artboard_that_stays_stays() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 60, "y": 0, "width": 100, "height": 100})).unwrap();
let sq = s.execute("shape.rectangle", &json!({"x": 70, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.none", &json!({})).unwrap();
let p = json!({"indices": [0, 2], "horizontal": "left", "to": "artboard", "artboard": 0});
assert_eq!(s.execute("artboard.align", &p).unwrap(), json!({"moved": [2]}));
assert_eq!(corners(&s)[2], (0.0, 0.0));
assert_eq!(corner(&s, sq), (70.0, 10.0), "with artboard 0, which stays");
}
/// An artboard's own guides move with it.
#[test]
fn an_artboards_guides_move_with_it() {
+2 -2
View File
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbol Options…",
[],
None,
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
has_doc,
symbol_options
),
@@ -326,7 +326,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select All Unused",
[],
None,
"{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used",
"{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics mapped onto 3D objects (threeD.mapGraphic), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used",
has_doc,
symbol_unused
),
+31
View File
@@ -115,6 +115,8 @@ fn art_symbols(n: &Node, out: &mut Vec<String>) {
if let NodeKind::SymbolInstance { symbol, .. } = &m.kind {
out.push(symbol.clone());
}
// A graphic on a 3D object draws its symbol's art too.
out.extend(vectorcraft_render::effects::graphic_symbols(m));
});
}
@@ -129,6 +131,8 @@ pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result<Value> {
let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()));
let trees = d.layers.iter().map(|l| &**l).chain(d.graph_designs.iter().map(|g| &*g.art));
trees.chain(patterns.flat_map(|p| p.art.iter().map(|n| &**n))).chain(lib.iter().flat_map(|b| b.art())).for_each(|n| art_symbols(n, &mut todo));
// A graphic in a graphic style draws its symbol's art wherever the style is applied.
todo.extend(d.graphic_styles.iter().flat_map(|g| vectorcraft_render::effects::appearance_graphic_symbols(&g.appearance)));
let mut used = std::collections::BTreeSet::new();
while let Some(name) = todo.pop() {
if !used.contains(&name) {
@@ -290,6 +294,33 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
*symbol = n.clone();
}
}
// The graphics mapped onto 3D objects follow the new name: in the layers, the art of
// symbols, patterns, graph designs and brushes, their opacity masks, and graphic styles.
let patterns = d.patterns.iter_mut().chain(d.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()));
let trees = d
.layers
.iter_mut()
.chain(d.symbols.iter_mut().map(|sym| &mut sym.art))
.chain(d.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(patterns.flat_map(|p| p.art.iter_mut()));
for art in trees.filter(|art| vectorcraft_render::effects::names_graphic_symbol(art, &name)) {
vectorcraft_render::effects::rename_graphic_symbol_in(Arc::make_mut(art), &name, n);
}
let styled = |g: &vectorcraft_doc::GraphicStyle| vectorcraft_render::effects::appearance_graphic_symbols(&g.appearance).contains(&name);
if d.graphic_styles.iter().any(styled) {
for style in d.graphic_styles.iter_mut() {
vectorcraft_render::effects::rename_appearance_graphic_symbol(&mut style.appearance, &name, n);
}
}
// The brush library is stored again only when a brush's art changed.
let mut lib = brush::library(d);
let mut brushes = false;
for art in lib.iter_mut().flat_map(|b| b.art_mut()) {
brushes |= vectorcraft_render::effects::rename_graphic_symbol_in(art, &name, n);
}
if brushes {
brush::store(d, &lib);
}
rename_natural_size(d, &name, n);
d.rename_symbol_registration(&name, n);
d.rename_symbol_export_type(&name, n);
+51 -70
View File
@@ -86,6 +86,10 @@ fn paint_refs(p: &Paint, f: Visit) {
}
fn appearance_refs(a: &Appearance, f: Visit) {
// The graphics mapped onto the faces of its 3D effects name symbols.
for s in vectorcraft_render::effects::appearance_graphic_symbols(a) {
f(Ref::Name(Res::Symbol, &s));
}
for it in &a.items {
paint_refs(it.paint(), f);
if let AppearanceItem::Stroke(l) = it
@@ -119,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 {
@@ -620,6 +628,17 @@ impl Relink {
}
}
}
// A 3D effect's mapped graphics follow their symbols' names in the document. Each name is
// looked up once, so renames that chain (A to B, B to C) do not apply twice.
let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
for e in a.effects.iter_mut().chain(items).filter(|e| vectorcraft_render::effects::takes_graphics(&e.id)) {
let list = e.params.get_mut(vectorcraft_render::effects::GRAPHICS).and_then(Value::as_array_mut);
for g in list.into_iter().flatten() {
if let Some(Value::String(s)) = g.get_mut("symbol") {
self.name(Res::Symbol, s);
}
}
}
for it in &mut a.items {
self.paint(it.paint_mut());
if let AppearanceItem::Stroke(l) = it
@@ -648,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 {
@@ -697,15 +720,6 @@ fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool {
relinked(&Relink::default(), ours) == relinked(r, theirs)
}
/// Does brush `b`'s art show symbols or patterns?
fn shows_definitions(b: &Brush) -> bool {
let mut found = false;
for a in b.art() {
node_refs(a, &mut |r| found |= matches!(r, Ref::Name(Res::Symbol | Res::Pattern, _)));
}
found
}
/// A symbol's Symbol Options, which its document keeps by symbol name: copied with the symbol and
/// given to it under the name pasting adds it as.
#[derive(Clone, Debug, PartialEq)]
@@ -739,7 +753,7 @@ impl SymbolOptions {
}
/// A character or paragraph style, symbol (with the Symbol Options copied with it), pattern or
/// brush (placed with the others only when they are placed in use order) to place
/// brush to place
/// ([`Clipboard::import_used`]).
#[derive(Clone, Copy)]
enum Def<'c> {
@@ -1055,49 +1069,40 @@ impl Clipboard {
}
/// Add the resources the objects use to `d` (inside the paste's undo step) and work out how
/// pasted copies relink to them. An error, with `d` unchanged, when a pasted SVG filter finds no
/// free name ([`Self::filter_links`]).
/// pasted copies relink to them. Each style, symbol, pattern and brush is placed after those it
/// uses, as [`import_text_styles`] places them, so that a style that paints with a pattern added
/// under a free name ("Dots 2") is compared and added with that name. An error, with `d`
/// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]).
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
self.import_used(d, &self.used(), choices, same_doc, false)
self.import_used(d, &self.used(), choices, same_doc)
}
/// [`Self::import_into`] for the resources `used` names. The character and paragraph styles
/// come before the symbols and patterns, whose art may set type in them; with `in_use_order`,
/// each style, symbol, pattern and brush comes after the styles, symbols, patterns and brushes it uses
/// ([`use_order`]), so that it is compared and relinked with their names here, and each loop
/// of definitions that use each other is matched on its own ([`loop_groups`]).
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Result<Imported> {
/// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush
/// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is
/// compared and relinked with their names here, and each loop of definitions that use each
/// other is matched on its own ([`loop_groups`]). Pasted back into its own document
/// (`same_doc`), each definition of a loop is the document's of its name.
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
let mut out = Imported::default();
out.relink.filters = self.filter_links(d, same_doc)?;
self.import_images(d, used, same_doc, &mut out);
self.import_swatches(d, used, choices, same_doc, &mut out);
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
// they may brush; the others once those are in. With `in_use_order`, the brushes are
// placed in use order with the others.
let mut added_brushes: HashSet<String> =
if in_use_order { HashSet::new() } else { self.import_brushes(d, used, same_doc, false, &mut out).into_iter().collect() };
let mut defs: Vec<Def<'_>> = vec![];
for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] {
defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s)));
}
defs.extend(self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).map(|s| Def::Symbol(s, self.symbol_options.get(&s.name))));
defs.extend(self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).map(Def::Pattern));
if in_use_order {
defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush));
}
defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush));
// Groups to place in order; true for a loop of definitions that use each other.
let groups: Vec<(Vec<Def<'_>>, bool)> = if in_use_order {
let (order, rest) = use_order(defs);
let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped));
std::iter::once((order, false)).chain(loops).collect()
} else {
vec![(defs, false)]
};
// Styles (their colors relinked first), symbols and patterns (compared once relinked,
// symbols with their options too). The symbols and patterns added are relinked at the end,
// when every new name and graphic style id is known; with `in_use_order`, so are the
// styles added, which a loop of uses may place before a pattern they paint with.
let (mut added_symbols, mut added_patterns, mut added_styles) = (HashSet::new(), HashSet::new(), vec![]);
let (order, rest) = use_order(defs);
let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped));
let groups: Vec<(Vec<Def<'_>>, bool)> = std::iter::once((order, false)).chain(loops).collect();
// Styles (their colors relinked first), symbols, patterns and brushes (compared once
// relinked, symbols with their options too). The styles, symbols, patterns and brushes
// added are relinked at the end, when every new name and graphic style id is known: a loop
// of uses may place one before a definition it uses.
let (mut added_symbols, mut added_patterns, mut added_brushes, mut added_styles) = (HashSet::new(), HashSet::new(), HashSet::new(), vec![]);
// Each definition, whether it is in a loop, and the loop it starts.
let steps = groups
.iter()
@@ -1107,8 +1112,8 @@ impl Clipboard {
let mut fresh = false;
// The names in the document of the loop being placed, when it has them all at once.
let mut matched: BTreeMap<(Res, String), String> = BTreeMap::new();
// The document's brush library, read the first time a brush is placed in use order and
// stored again after each brush added; nothing else in the loop changes it.
// The document's brush library, read the first time a brush is placed and stored again
// after each brush added; nothing else in the loop changes it.
let mut library: Option<Vec<Brush>> = None;
for (def, looped, starts) in steps {
fresh &= looped;
@@ -1116,8 +1121,9 @@ impl Clipboard {
matched.clear();
}
// A loop of uses that the document has all at once is known under those names before
// its definitions are compared.
if let Some(group) = starts {
// its definitions are compared. In its own document, each definition is the
// document's of its name, as outside a loop.
if let Some(group) = starts.filter(|_| !same_doc) {
matched.clear();
match names_of_loop(d, group, &out.relink) {
Some(names) => {
@@ -1146,7 +1152,7 @@ impl Clipboard {
out.relink.attrs(&mut s.attrs);
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
let p = place(theirs, &s, same_doc, |a, b| !fresh && a == b);
if in_use_order && let Some(name) = p.new_name(&def.name) {
if let Some(name) = p.new_name(&def.name) {
added_styles.push((r, name, def));
}
out.placed(r, &def.name, &p);
@@ -1200,9 +1206,6 @@ impl Clipboard {
}
}
}
if !in_use_order {
added_brushes.extend(self.import_brushes(d, used, same_doc, true, &mut out));
}
self.import_graphic_styles(d, used, same_doc, &mut out);
for (r, name, def) in added_styles {
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
@@ -1323,28 +1326,6 @@ impl Clipboard {
}
}
/// The brushes whose art shows symbols or patterns (`late`), or the others: each one the
/// document has (its art compared once relinked) is used, the others are added. → the names of
/// those added, whose art is relinked at the end.
fn import_brushes(&self, d: &mut Document, used: &Used, same_doc: bool, late: bool, out: &mut Imported) -> Vec<String> {
let brushes: Vec<&Brush> = self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name) && shows_definitions(b) == late).collect();
if brushes.is_empty() {
return vec![];
}
let mut lib = vectorcraft_brush::library(d);
let mut added = vec![];
for b in brushes {
let r = &out.relink;
let p = place(&mut lib, b, same_doc, |ours, theirs| same_brush(r, ours, theirs));
added.extend(p.new_name(&b.name));
out.placed(Res::Brush, &b.name, &p);
}
if !added.is_empty() {
vectorcraft_brush::store(d, &lib);
}
added
}
/// Global and spot colours (a name conflict merges or adds as `choices` say), then the tint
/// swatches of the tints used and the gradient swatches.
fn import_swatches(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, out: &mut Imported) {
@@ -1429,7 +1410,7 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
let used = Used::of_text_styles(&Defs::of(src, &library), chars, paras);
let clip = Clipboard::with_used(src, &used, &library, vec![]);
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true)?;
let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?;
let mut placed: Vec<LoadedStyle> = vec![];
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
for s in list {
+84 -7
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Info",
["Window", "Document Info"],
None,
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
has_doc,
info
),
@@ -627,16 +627,22 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
}
});
}
// The document's fonts include those of the type in opacity masks and in the art of its
// symbols and patterns, as Find Font lists them.
if !selection_only {
fonts.extend(super::fonts::art_texts_of(d).into_iter().flat_map(|(_, t, _)| t.runs.iter().map(|r| super::fonts::font_of(&r.style))));
}
let font_names: Vec<String> = fonts.iter().map(super::fonts::font_label).collect();
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the last of two
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type.
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type
// as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them.
let kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = library.iter().map(|b| (b.name.as_str(), &b.kind)).collect();
let brush_entries: Vec<Value> =
brushes.iter().map(|name| json!({ "name": name, "type": kinds.get(name.as_str()).map(|k| k.type_id()) })).collect();
let brush_rows: Vec<(String, String)> = brushes
.iter()
.map(|name| {
(name.clone(), kinds.get(name.as_str()).map_or_else(|| "missing from the Brushes panel".to_string(), |k| format!("{} brush", k.label())))
(name.clone(), kinds.get(name.as_str()).map_or_else(|| "missing from the Brushes panel".to_string(), |k| format!("{} Brush", k.label())))
})
.collect();
let mut out = json!({
@@ -755,6 +761,40 @@ mod tests {
assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1);
}
/// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a
/// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's.
#[test]
fn info_fonts_include_masks_symbols_and_patterns() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let id = |v: Value| NodeId(v["id"].as_u64().unwrap());
let text = |s: &mut Session, font: &str| id(s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": font})).unwrap());
let rect = |s: &mut Session| id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap());
let (masked, in_symbol) = (rect(&mut s), rect(&mut s));
for (owner, font) in [(masked, "Mask Family"), (in_symbol, "Symbol Mask Family")] {
let t = text(&mut s, font);
s.edit("Mask", |d, _| {
let art = d.remove(t)?;
d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
Ok(())
})
.unwrap();
}
s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap();
let t = text(&mut s, "Pattern Family");
s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let plain = text(&mut s, "Source Sans 3");
let fonts = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["fonts"].clone();
assert_eq!(
fonts(&mut s, json!({})),
json!(["Mask Family Regular", "Pattern Family Regular", "Source Sans 3 Regular", "Symbol Mask Family Regular"])
);
s.execute("select.set", &json!({"ids": [plain.0]})).unwrap();
assert_eq!(fonts(&mut s, json!({"selectionOnly": true})), json!(["Source Sans 3 Regular"]));
}
/// Document Info › Objects gives the paths' total length in the document's units (#1958): an
/// open line, a closed rectangle's perimeter and a compound path's pieces count, a guide doesn't.
#[test]
@@ -805,10 +845,10 @@ mod tests {
let i = brushes(&mut s, json!({"category": "brushes"}));
assert_eq!(i["brushNames"], json!(["Charcoal", "Dots"]));
assert_eq!(i["brushes"], json!([{"name": "Charcoal", "type": "art"}, {"name": "Dots", "type": "scatter"}]));
assert_eq!(i["sections"][0]["rows"], json!([["Charcoal", "Art brush"], ["Dots", "Scatter brush"]]));
assert_eq!(i["sections"][0]["rows"], json!([["Charcoal", "Art Brush"], ["Dots", "Scatter Brush"]]));
assert!(panel.contains(&json!("3 pt. Round")) && i["panelBrushNames"] == json!(panel));
let text = brushes(&mut s, json!({"category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string();
assert!(text.contains("\nBRUSHES\nCharcoal: Art brush\nDots: Scatter brush\n") && !text.contains("3 pt. Round"), "{text}");
assert!(text.contains("\nBRUSHES\nCharcoal: Art Brush\nDots: Scatter Brush\n") && !text.contains("3 pt. Round"), "{text}");
assert!(!text.contains("OBJECTS"), "{text}");
// Selection Only: the brushes the selected objects' strokes use.
let selected = |s: &mut Session| brushes(s, json!({"selectionOnly": true, "category": "brushes"}));
@@ -818,10 +858,10 @@ mod tests {
let i = selected(&mut s);
assert_eq!(
(i["brushes"].clone(), i["sections"][0]["rows"].clone()),
(json!([{"name": "Dots", "type": "scatter"}]), json!([["Dots", "Scatter brush"]]))
(json!([{"name": "Dots", "type": "scatter"}]), json!([["Dots", "Scatter Brush"]]))
);
let text = brushes(&mut s, json!({"selectionOnly": true, "category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string();
assert!(text.contains("\nBRUSHES\nDots: Scatter brush\n") && !text.contains("Charcoal"), "{text}");
assert!(text.contains("\nBRUSHES\nDots: Scatter Brush\n") && !text.contains("Charcoal"), "{text}");
// A stroke without a brush lists none.
let plain = s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [plain]})).unwrap();
@@ -1378,6 +1418,43 @@ mod tests {
assert_eq!(i["objects"]["spots"].as_u64(), Some(1), "{}", i["objects"]);
}
/// Spot Color Objects leaves out a fill or stroke at an opacity of 0, which prints no ink, and
/// keeps the object while another of its fills or strokes prints the spot color. Gradient
/// Objects leaves out a clear gradient fill as well.
#[test]
fn spot_color_objects_skip_clear_fills_and_strokes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [rect], "swatch": "Ink"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [rect], "swatch": "Ink"})).unwrap();
let ramp = s.execute("shape.rectangle", &json!({"x": 50, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let stops = json!([{"offset": 0, "color": "#000", "swatch": "Ink"}, {"offset": 1, "color": "#fff", "swatch": "Ink"}]);
s.execute("paint.setFill", &json!({"ids": [ramp], "gradient": {"kind": "linear", "stops": stops}})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [ramp], "none": true})).unwrap();
let items = |s: &Session, id: &Value| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().appearance.items.clone();
let spots = |s: &mut Session| {
let i = s.execute("document.info", &json!({})).unwrap();
let mut ids: Vec<u64> = i["spotObjects"].as_array().unwrap().iter().map(|o| o["id"].as_u64().unwrap()).collect();
ids.sort_unstable();
(ids, i["objects"]["spots"].as_u64(), i["objects"]["gradients"].as_u64())
};
// The rectangle's fill at an opacity of 0: its stroke still prints the spot color.
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
let fill = items(&s, &rect).iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
s.execute("appearance.setItem", &json!({"index": fill, "opacity": 0})).unwrap();
assert_eq!(spots(&mut s), (vec![rect.as_u64().unwrap(), ramp.as_u64().unwrap()], Some(2), Some(1)));
// Every fill and stroke of both objects at an opacity of 0.
for id in [&rect, &ramp] {
s.execute("select.set", &json!({"ids": [id]})).unwrap();
for index in 0..items(&s, id).len() {
s.execute("appearance.setItem", &json!({"index": index, "opacity": 0})).unwrap();
}
}
assert_eq!(spots(&mut s), (vec![], None, None));
}
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
/// it counts that object once.
+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
),
+55 -5
View File
@@ -34,8 +34,15 @@ fn svg_filter_name(s: &Session, xml: &str, cmd: &str) -> Result<String> {
Ok(name)
}
/// The effect commands of the Effect menu and the Appearance panel.
/// The effect commands of the Effect menu and the Appearance panel, and the 3D and Materials
/// panel's Graphics.
pub fn specs() -> Vec<CommandSpec> {
let mut specs = effect_specs();
specs.extend(graphics::specs());
specs
}
fn effect_specs() -> Vec<CommandSpec> {
vec![
cmd!(
"effect.apply",
@@ -87,7 +94,7 @@ pub fn 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
),
@@ -454,6 +461,9 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten();
let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len())));
effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?;
if let Some(name) = effects::missing_symbol(d, &effect.params, None) {
return Err(bad(C, format!("no symbol named `{name}`")));
}
if id == effects::REVOLVE && effects::has_revolve(n) {
return Err(bad(C, "A profile supports one Revolve effect. Edit the existing effect's options instead."));
}
@@ -758,6 +768,9 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(to, &params)) {
cur.extend(new);
}
if let Some(name) = effects::missing_symbol(d, &prospective, Some(&e.params)) {
return Err(bad(C, format!("no symbol named `{name}`")));
}
if visible != Some(false) {
effects::validate_three_d_at_in(Some(d), n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?;
} else {
@@ -835,8 +848,9 @@ fn load_texture(params: &mut Value, cmd: &str) -> Result<()> {
/// Has `n` an appearance Expand Appearance turns into objects: a path that isn't basic (several
/// fills or strokes, effects, transparency of a fill or stroke, a brush), a group or layer with
/// fills, strokes or effects of its own or such members, other objects with effects, or type with
/// fills or strokes of its own?
/// fills, strokes or effects of its own or such members, other objects with effects, type with
/// fills or strokes of its own, or a symbol instance whose active fill or stroke has a geometry
/// effect ([`effects::has_item_geometry`])?
pub(crate) fn expandable(n: &Node) -> bool {
expandable_except(n, &[])
}
@@ -853,7 +867,7 @@ pub(crate) fn expandable_except(n: &Node, skip: &[NodeId]) -> bool {
!n.appearance.items.is_empty() || !n.appearance.effects.is_empty() || children.iter().any(|c| expandable_except(c, skip))
}
NodeKind::Text(_) => !n.appearance.items.is_empty() || !n.appearance.effects.is_empty(),
NodeKind::Image(_) => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(),
NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(),
_ => !n.appearance.effects.is_empty(),
}
}
@@ -926,6 +940,38 @@ fn expand_pieces(
expanded
}
/// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose
/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as
/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so
/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more
/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art
/// would take the objects placed so far past `budget`.
fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) {
for c in m.children_mut().into_iter().flatten() {
if !matches!(c.kind, NodeKind::SymbolInstance { .. }) {
if c.children().is_some() {
expand_nested_instances(d, Arc::make_mut(c), depth, budget);
}
continue;
}
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue };
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) {
continue;
}
let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue };
let count = sym.art.count() as u64;
if count > *budget {
continue;
}
*budget -= count;
let art = vectorcraft_render::instance_art(&sym.art, c);
if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) {
expand_nested_instances(d, &mut a, depth + 1, budget);
*c = Arc::new(a);
}
}
}
/// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids?
fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
let mut ids = std::collections::HashSet::new();
@@ -1081,6 +1127,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
_ => None,
};
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
expand_nested_instances(d, &mut m, 1, &mut budget);
expand_pieces(d, &mut m, true, brushes, &mut stroke_art);
m
})
@@ -1201,6 +1249,8 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
mod graphics;
#[cfg(test)]
mod lighting_presets_tests;
+153
View File
@@ -0,0 +1,153 @@
//! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single
//! Graphic) and mapped onto the planar faces of 3D objects (Extrude & Bevel's caps, a plane). The
//! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams`
//! also edits.
use serde_json::{Map, Value, json};
use vectorcraft_doc::{Effect, Node};
use vectorcraft_render::effects;
use super::super::appearance::{appearance_targets, index_param, item_target};
use super::super::brushsym::{normalize, selection_art, store_symbol};
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_doc, has_selection, str_param};
use super::{effect_targets, ids_json};
pub(super) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"threeD.addGraphic",
"Add as Single Graphic",
[],
None,
"{name?: string (default Graphic; made unique), ids?|id?} keep the selection's art as a new document symbol, listed among the 3D and Materials panel's Graphics; the selection stays as it is → {name}",
has_selection,
add_graphic
),
cmd!(
"threeD.mapGraphic",
"Map Graphic",
[],
None,
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane), scale?: % (1..10000; default 100, or less so the graphic fits inside the object), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it; every object's 3D effect must be Extrude & Bevel (on a solid cap) or Rotate (the Plane type); one undo step → {ids, graphic}",
has_doc,
map_graphic
),
]
}
/// `threeD.addGraphic`: stores the selection's art as a symbol without replacing it with an
/// instance.
fn add_graphic(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "threeD.addGraphic";
if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !["name", "ids", "id"].contains(&k.as_str()))) {
return Err(bad(C, format!("unknown parameter `{key}`")));
}
if p.get("name").is_some_and(|v| v.as_str().is_none_or(|n| n.trim().is_empty())) {
return Err(bad(C, "`name` must be a name that is not empty"));
}
let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?;
crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art);
let (art, size, _) = normalize(art)?;
let name = s.doc()?.doc.unique_symbol_name(str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Graphic"));
s.edit("Add as Single Graphic", |d, _| {
store_symbol(d, &art, &name, size);
Ok(())
})?;
Ok(json!({ "name": name }))
}
/// The 3D effect of `n` that a graphic goes on when none is named: its own first, then its fills'
/// and strokes', as the 3D and Materials panel finds it.
fn first_three_d(n: &Node) -> Option<(Option<usize>, usize)> {
let at = |fx: &[Effect]| fx.iter().position(|e| effects::is_three_d(&e.id));
at(&n.appearance.effects)
.map(|i| (None, i))
.or_else(|| n.appearance.items.iter().enumerate().find_map(|(k, item)| at(item.effects()).map(|i| (Some(k), i))))
}
/// `threeD.mapGraphic`: appends a graphic to the 3D effect of each target, after checking that every
/// target takes it.
fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "threeD.mapGraphic";
const KEYS: [&str; 10] = ["symbol", "face", "x", "y", "scale", "rotation", "index", "item", "ids", "id"];
if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !KEYS.contains(&k.as_str()))) {
return Err(bad(C, format!("unknown parameter `{key}`")));
}
// An item names where the effect is in that item's list, so it takes an index too.
if p.get("item").is_some() && p.get("index").is_none() {
return Err(bad(C, "`item` needs `index`"));
}
// The graphic's own settings, checked as the effect checks them.
let mut given = Map::new();
for key in ["symbol", "face", "x", "y", "scale", "rotation"] {
if let Some(v) = p.get(key) {
given.insert(key.into(), v.clone());
}
}
let base = effects::MappedGraphic::from_value(&Value::Object(given)).map_err(|e| bad(C, e))?;
let d = &s.doc()?.doc;
if !d.symbols.iter().any(|sym| sym.name == base.symbol) {
return Err(bad(C, format!("no symbol named `{}`", base.symbol)));
}
let targets: Vec<(NodeId, Option<usize>, usize)> = if p.get("index").is_some() {
let index = index_param(p, "index", C)?;
let item = item_target(s, p, C)?;
effect_targets(s, p, item, index, C)?
} else {
let mut out = vec![];
for id in appearance_targets(s, p)? {
let (item, index) = d.node(id).and_then(first_three_d).ok_or_else(|| bad(C, format!("object {} needs a 3D effect", id.0)))?;
out.push((id, item, index));
}
out
};
if targets.is_empty() {
return Err(bad(C, "select an object with a 3D effect"));
}
let mut edits = Vec::with_capacity(targets.len());
for &(id, item, index) in &targets {
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
let Some(effect) = n.appearance.effects_at(item).and_then(|fx| fx.get(index)).filter(|e| effects::is_three_d(&e.id)) else {
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
};
if !effects::takes_graphics(&effect.id) {
return Err(bad(C, format!("object {}: Graphics map onto planar faces: use the Extrude or Plane object type", id.0)));
}
// A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again,
// but has no cap to show a new one on.
let merged = effects::merged_params(&effect.id, &effect.params);
let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged));
if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0)));
}
// With a depth of 0 the art is a plane, which has only a front.
if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) {
return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0)));
}
let mut graphic = base.clone();
if p.get("scale").is_none()
&& let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol))
{
graphic.scale = frame.fitting_scale(art);
}
let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic);
effects::validate_three_d_at_in(Some(d), n, &effect.id, &params, item.map(|i| (i, index))).map_err(|e| bad(C, e))?;
edits.push((id, item, index, graphic));
}
let first = edits.first().map(|(.., g)| g.to_value());
let ids = s.edit("Map Graphic", |d, _| {
let mut done = vec![];
for (id, item, index, graphic) in &edits {
let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects_mut(*item)).and_then(|fx| fx.get_mut(*index)) else { continue };
let current = effects::upgrade_params(&e.id, &e.params);
e.params = effects::with_graphic(&current, graphic);
done.push(*id);
}
Ok(done)
})?;
Ok(json!({ "ids": ids_json(&ids), "graphic": first }))
}
#[cfg(test)]
#[path = "graphics_tests.rs"]
mod tests;
@@ -0,0 +1,289 @@
#![allow(clippy::unwrap_used, clippy::panic)]
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use crate::Session;
/// A 100 × 100 square with `effect`, and a 10 × 20 red rectangle beside it kept as graphic "Mark".
fn setup(effect: &str) -> (Session, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
let mark = s.execute("path.create", &json!({"d":"M300 300L310 300L310 320L300 320Z"})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap();
let made = s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [mark]})).unwrap();
assert_eq!(made["name"], "Mark");
let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap();
s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":{"rotationX":0.0,"rotationY":0.0,"rotationZ":0.0}})).unwrap();
(s, id)
}
fn graphics(s: &Session, id: NodeId) -> Value {
s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params["graphics"].clone()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
#[test]
fn add_as_single_graphic_keeps_the_art_and_makes_a_symbol() {
let (s, _) = setup("threeD.extrude");
let d = &s.doc().unwrap().doc;
assert!(d.symbols.iter().any(|sym| sym.name == "Mark"));
// The art stays a plain path: no instance replaced it.
let mut instances = 0;
for l in &d.layers {
l.walk(&mut |n| instances += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. })));
}
assert_eq!(instances, 0);
// The 10 × 20 rectangle and its 1 pt stroke.
assert_eq!(vectorcraft_render::effects::graphic_bounds(d, "Mark").map(|r| (r.width(), r.height())), Some((11.0, 21.0)));
}
#[test]
fn map_graphic_adds_to_the_selected_object_in_one_undo_step_and_undoes() {
let (mut s, id) = setup("threeD.extrude");
let before = s.doc().unwrap().doc.clone();
let history = undo_len(&s);
let r = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "x": 5.0, "rotation": 30.0})).unwrap();
assert_eq!(r["ids"], json!([id.0]));
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 5.0, "y": 0.0, "scale": 100.0, "rotation": 30.0}]));
assert_eq!(undo_len(&s), history + 1);
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back"})).unwrap();
assert_eq!(graphics(&s, id).as_array().unwrap().len(), 2);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
}
#[test]
fn a_large_graphic_starts_inside_its_object() {
let (mut s, id) = setup("threeD.rotate");
let big = s.execute("path.create", &json!({"d":"M0 0L400 0L400 200L0 200Z"})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Big", "ids": [big]})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Big", "ids": [id.0]})).unwrap();
// 401 pt wide with its stroke, in a 100 pt square.
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
assert!((scale - 100.0 * 100.0 / 401.0).abs() < 1e-9, "{scale}");
}
#[test]
fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
let (mut s, id) = setup("threeD.inflate");
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("Extrude or Plane"), "{e}");
let (mut s, id) = setup("threeD.rotate");
for (p, says) in [
(json!({"symbol": "Gone"}), "no symbol named"),
(json!({"face": "front"}), "needs `symbol`"),
(json!({"symbol": "Mark", "face": "back"}), "one face"),
(json!({"symbol": "Mark", "scale": 0.0}), "scale"),
(json!({"symbol": "Mark", "tile": true}), "`tile`"),
(json!({"symbol": "Mark", "item": 0}), "`item` needs `index`"),
(json!({"symbol": "Mark", "item": null}), "`item` needs `index`"),
] {
let mut p = p;
p["ids"] = json!([id.0]);
let e = s.execute("threeD.mapGraphic", &p).unwrap_err().to_string();
assert!(e.contains(says), "{p}: {e}");
}
assert_eq!(undo_len(&s), history);
// An object without a 3D effect.
let plain = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].clone();
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [plain]})).unwrap_err().to_string();
assert!(e.contains("3D effect"), "{e}");
// A hollow Extrude & Bevel has no cap to show a new graphic on.
let (mut s, id) = setup("threeD.extrude");
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap();
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("turn on Cap"), "{e}");
assert_eq!(undo_len(&s), history);
// With a depth of 0 there is no back.
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": true, "depth": 0.0}})).unwrap();
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("one face"), "{e}");
assert_eq!(undo_len(&s), history);
assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok());
}
#[test]
fn set_params_edits_graphics_and_checks_them() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let moved = json!([{"symbol": "Mark", "face": "front", "x": -12.0, "y": 8.0, "scale": 150.0, "rotation": 0.0}]);
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": moved}})).unwrap();
assert_eq!(graphics(&s, id), moved);
let bad = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": [{"symbol": "Mark", "face": "top"}]}});
assert!(s.execute("effect.setParams", &bad).is_err());
let null = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": null}});
assert!(s.execute("effect.setParams", &null).is_err());
assert_eq!(graphics(&s, id), moved);
// Extrude to Plane keeps the graphics; to Inflate drops them.
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "plane"})).unwrap();
assert_eq!(graphics(&s, id), moved);
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "inflate"})).unwrap();
assert_eq!(graphics(&s, id), Value::Null);
}
#[test]
fn effect_commands_refuse_an_unknown_symbol_but_keep_a_deleted_ones_graphic() {
let (mut s, id) = setup("threeD.extrude");
let unknown = json!([{"symbol": "Nowhere"}]);
let history = undo_len(&s);
assert!(s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": unknown}})).is_err());
s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap();
let created = undo_len(&s);
assert!(s.execute("effect.apply", &json!({"effect": "threeD.extrude", "item": null, "params": {"graphics": unknown}})).is_err());
assert_eq!((history + 1, undo_len(&s)), (created, created));
// A graphic whose symbol was deleted stays while the effect's other settings change.
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap();
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).symbols.retain(|sym| sym.name != "Mark");
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"depth": 30.0}})).unwrap();
assert_eq!(graphics(&s, id)[0]["symbol"], "Mark");
}
#[test]
fn a_symbol_a_graphic_uses_is_used_and_follows_a_rename() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let unused = s.execute("symbol.unused", &json!({})).unwrap();
assert!(!unused["names"].as_array().unwrap().iter().any(|n| n == "Mark"), "{unused}");
// A 3D object with the graphic kept in another symbol's art follows the rename too.
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
s.execute("symbol.new", &json!({"name": "Holder"})).unwrap();
s.execute("symbol.options", &json!({"name": "Mark", "newName": "Label"})).unwrap();
assert_eq!(graphics(&s, id)[0]["symbol"], "Label");
let d = &s.doc().unwrap().doc;
let holder = d.symbols.iter().find(|sym| sym.name == "Holder").unwrap();
let mut held = vec![];
holder.art.walk(&mut |n| held.extend(vectorcraft_render::effects::graphic_symbols(n)));
assert_eq!(held, vec!["Label".to_string()]);
}
#[test]
fn a_rename_reaches_graphics_in_graph_designs_and_opacity_masks() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let held = d.node(id).unwrap().clone();
d.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Bars".into(), art: std::sync::Arc::new(held.clone()) });
d.graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Boxed", (*held.appearance).clone()));
let mut lib = vectorcraft_brush::library(d);
let scatter = lib.iter_mut().find(|b| !b.art().is_empty()).unwrap();
*scatter.art_mut()[0] = held.clone();
vectorcraft_brush::store(d, &lib);
d.node_mut(id).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(held, true)));
s.execute("symbol.options", &json!({"name": "Mark", "newName": "Label"})).unwrap();
let d = &s.doc().unwrap().doc;
let style = d.graphic_styles.iter().find(|g| g.name == "Boxed").unwrap();
assert_eq!(vectorcraft_render::effects::appearance_graphic_symbols(&style.appearance), vec!["Label".to_string()]);
let brush: Vec<String> =
vectorcraft_brush::library(d).iter().flat_map(|b| b.art()).flat_map(vectorcraft_render::effects::graphic_symbols).collect();
assert_eq!(brush, vec!["Label".to_string()]);
let names = |n: &vectorcraft_doc::Node| {
let mut out = vec![];
n.walk(&mut |c| out.extend(vectorcraft_render::effects::graphic_symbols(c)));
out
};
assert_eq!(names(&d.graph_designs[0].art), vec!["Label".to_string()]);
let mask = d.node(id).unwrap().extras().mask.as_deref().map(|m| names(&m.art));
assert_eq!(mask, Some(vec!["Label".to_string()]));
}
#[test]
fn pasted_into_another_document_a_graphic_brings_its_symbol() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// The symbol the pasted object's graphic names, and the size of that symbol's art.
let pasted = |s: &mut Session| {
s.execute("edit.paste", &json!({})).unwrap();
let st = s.doc().unwrap();
let n = st.doc.node(st.selection.objects[0]).unwrap();
let name = n.appearance.effects[0].params["graphics"][0]["symbol"].as_str().unwrap().to_string();
let size = vectorcraft_render::effects::graphic_bounds(&st.doc, &name).map(|r| (r.width(), r.height()));
(name, size)
};
// A document without the symbol gets it.
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
assert_eq!(pasted(&mut s), ("Mark".to_string(), Some((11.0, 21.0))));
// A document whose symbol "Mark" is other art gets the copied symbol under a free name.
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
let other = s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [other]})).unwrap();
let (name, size) = pasted(&mut s);
assert_ne!(name, "Mark");
assert_eq!(size, Some((11.0, 21.0)));
}
#[test]
fn a_symbol_only_a_graphic_style_uses_is_used() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let appearance = (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone();
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"graphics": []}})).unwrap();
let unused = |s: &mut Session| s.execute("symbol.unused", &json!({})).unwrap()["names"].clone();
assert!(unused(&mut s).as_array().unwrap().iter().any(|n| n == "Mark"));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Boxed", appearance));
assert!(!unused(&mut s).as_array().unwrap().iter().any(|n| n == "Mark"));
}
#[test]
fn add_graphic_refuses_bad_parameters_and_changes_nothing() {
let (mut s, _) = setup("threeD.extrude");
let art = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].clone();
let (symbols, history) = (s.doc().unwrap().doc.symbols.len(), undo_len(&s));
for p in [
json!({"name": 5, "ids": [art]}),
json!({"name": null, "ids": [art]}),
json!({"name": "", "ids": [art]}),
json!({"name": " ", "ids": [art]}),
json!({"tile": true, "ids": [art]}),
] {
assert!(s.execute("threeD.addGraphic", &p).is_err(), "{p}");
}
assert_eq!((s.doc().unwrap().doc.symbols.len(), undo_len(&s)), (symbols, history));
}
#[test]
fn map_graphic_refuses_a_selection_with_an_object_without_a_3d_effect() {
let (mut s, id) = setup("threeD.extrude");
let plain = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].as_u64().unwrap();
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0, plain]})).unwrap_err().to_string();
assert!(e.contains(&format!("object {plain} needs a 3D effect")), "{e}");
assert_eq!(undo_len(&s), history);
assert_eq!(graphics(&s, id).as_array().map_or(0, Vec::len), 0);
}
#[test]
fn the_graphic_is_drawn_on_the_object() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let d = &s.doc().unwrap().doc;
let art = vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap()).unwrap();
let mut red = None;
art.walk(&mut |n| {
if let (Some(p), Some(vectorcraft_doc::AppearanceItem::Fill(f))) = (n.path_data(), n.appearance.items.first())
&& f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1)
{
red = p.bounds();
}
});
// Seen straight on, the 10 × 20 graphic sits at the center of the square.
let r = red.unwrap();
assert!(
(r.center().x - 150.0).abs() < 1e-6
&& (r.center().y - 150.0).abs() < 1e-6
&& (r.width() - 10.0).abs() < 1e-6
&& (r.height() - 20.0).abs() < 1e-6,
"{r:?}"
);
}
+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))
}
+31 -11
View File
@@ -408,15 +408,31 @@ pub(crate) fn anti_alias(id: &str) -> std::result::Result<AntiAlias, String> {
/// The `useArtboards` param of a PDF, AI, DXF or raster export (SVG has its own): `true` writes every
/// chosen artboard (default all), `false` the bounds of the visible art instead, absent one
/// artboard (raster, DXF) or the chosen pages (PDF, AI).
fn use_artboards(p: &Value) -> Result<Option<bool>> {
/// artboard (raster, DXF) or the chosen pages (PDF, AI). Errors name the command `cmd`.
pub(super) fn use_artboards(cmd: &str, p: &Value) -> Result<Option<bool>> {
match p.get("useArtboards") {
None | Some(Value::Null) => Ok(None),
Some(Value::Bool(b)) => Ok(Some(*b)),
Some(v) => Err(bad(C, format!("useArtboards must be true or false, not {v}"))),
Some(v) => Err(bad(cmd, format!("useArtboards must be true or false, not {v}"))),
}
}
/// With `useArtboards: false` in `p`: `doc` without its opacity-mask or symbol editing layer and
/// with one artboard, the bounds of its visible art, and `p` without the artboard choice. `None`
/// when `useArtboards` is absent, null or true. A document with no visible art is refused.
pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(Document, Value)>> {
if use_artboards(cmd, p)? != Some(false) {
return Ok(None);
}
let doc = &*doc.without_edit_modes();
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?;
let mut q = super::export::without_artboards(p);
if let Some(o) = q.as_object_mut() {
o.remove("useArtboards");
}
Ok(Some((single_artboard(doc, bounds, "Art"), q)))
}
/// The `rect` param of a raster export: `[x, y, width, height]` in points, y down. `None` when
/// absent; an error when it is not four finite numbers with a positive size, when the format isn't
/// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would
@@ -596,7 +612,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
let doc = &*doc.without_edit_modes();
let n = doc.artboards.len();
// SVG reads its own `useArtboards` (an SVG option).
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(p)? } else { None };
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(C, p)? } else { None };
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
if let Some(rect) = page_rect(f, p)? {
let mut q = super::export::without_artboards(p);
@@ -606,13 +622,17 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
}
return encode_files(&single_artboard(doc, rect, "Rect"), f, &q);
}
if use_artboards == Some(false) {
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(C, "nothing to export: the document has no visible art"))?;
let mut q = super::export::without_artboards(p);
if let Some(o) = q.as_object_mut() {
o.remove("useArtboards");
}
return encode_files(&single_artboard(doc, bounds, "Art"), f, &q);
// A PDF of the art's bounds carries no editing data (it would replace the artboards).
if use_artboards == Some(false)
&& f.id == "pdf"
&& let Some((bytes, notes)) = super::pdf::encode_art_page(C, doc, p)?
{
return Ok(Encoded::one_with_notes(bytes, notes));
}
if use_artboards == Some(false)
&& let Some((art, q)) = art_page(C, doc, p)?
{
return encode_files(&art, f, &q);
}
let bytes = match f.id {
"vectorcraft" => super::native::encode(C, f, doc, p)?,
+11 -8
View File
@@ -782,9 +782,9 @@ pub fn open_extensions() -> &'static [&'static str] {
/// File › Open's filters: "All readable files" first, then one per readable format, then one per
/// importer plug-in (under its name, with the extensions [`open_extensions`] takes from it), then
/// swatch libraries (which open in the library panel), Libraries panel libraries, flattener, PDF,
/// print and export presets (imported), scripts (checked without running them) and plug-ins
/// (installed).
/// swatch and graphic style libraries (which open in their library panels), Libraries panel
/// libraries, flattener, PDF, print, perspective grid and export presets and composite fonts
/// (imported), shortcut sets, scripts (checked without running them) and plug-ins (installed).
pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
let (all, importers) = importer_open_part();
std::iter::once(("All readable files", all)).chain(format_filters()).chain(importers).chain(other_open_filters())
@@ -797,14 +797,17 @@ pub fn builtin_open_filters() -> impl Iterator<Item = (&'static str, &'static [&
std::iter::once(("All readable files", OPEN_EXTS)).chain(format_filters()).chain(other_open_filters())
}
/// The open-dialog filters after the document formats: swatch libraries, Libraries panel
/// libraries, presets, composite fonts, shortcut sets, scripts and plug-ins.
/// The open-dialog filters after the document formats: swatch and graphic style libraries,
/// Libraries panel libraries, presets (perspective grid presets among them), composite fonts,
/// shortcut sets, scripts and plug-ins.
fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once(("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS))
.chain(std::iter::once(("Graphic Style Libraries", std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT))))
.chain(std::iter::once(("Libraries", crate::cmd::library::LIBRARY_EXTS)))
.chain(std::iter::once(("Flattener presets", crate::cmd::flatten::PRESET_EXTS)))
.chain(std::iter::once(("PDF presets", crate::cmd::pdfcmds::PRESET_EXTS)))
.chain(std::iter::once(("Print presets", crate::cmd::printpresets::PRESET_EXTS)))
.chain(std::iter::once(("Perspective grid presets", crate::cmd::perspgrid::PRESET_EXTS)))
.chain(std::iter::once(("Export presets", screens::PRESET_FILE_EXTS)))
.chain(std::iter::once(("Composite fonts", crate::cmd::compositefonts::EXTS)))
.chain(std::iter::once(("Shortcut sets", crate::cmd::shortcutset::EXTS)))
@@ -815,13 +818,13 @@ fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'stati
/// Open-dialog filters for Swatch Libraries and Graphic Style Libraries Other Library… and Locate
/// Library…. The library formats come first so Linux file portals (which grey out files that don't
/// match the default filter) still list `.ase` and the other library extensions; then the same
/// filters as [`builtin_open_filters`] so a document can be picked for its swatches or graphic
/// styles.
/// filters as [`builtin_open_filters`], without a second copy of the library filter, so a document
/// can be picked for its swatches or graphic styles.
pub fn library_open_filters(
library_label: &'static str,
library_exts: &'static [&'static str],
) -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once((library_label, library_exts)).chain(builtin_open_filters())
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts)))
}
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
+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)))
File diff suppressed because one or more lines are too long
+18 -2
View File
@@ -390,9 +390,20 @@ fn open_exts_cover_every_readable_format() {
assert_eq!(filters[0], ("All readable files", OPEN_EXTS));
assert_eq!(
filters.len(),
11 + FORMATS.iter().filter(|f| f.read).count(),
"and swatch libraries, libraries, flattener, PDF, print and export presets, composite fonts, shortcut sets, scripts, plug-ins"
13 + FORMATS.iter().filter(|f| f.read).count(),
"and swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export presets, composite \
fonts, shortcut sets, scripts, plug-ins"
);
let at = |label: &str| filters.iter().position(|f| f.0 == label).unwrap_or_else(|| panic!("File › Open has no {label} filter"));
let styles: &[&str] = &[vectorcraft_doc::style_libs::STYLES_EXT];
assert_eq!(filters[at("Graphic Style Libraries")].1, styles, "File › Open opens graphic style libraries");
assert_eq!(at("Graphic Style Libraries"), at("Swatch libraries") + 1, "next to the swatch libraries");
assert_eq!(filters[at("Perspective grid presets")].1, crate::cmd::perspgrid::PRESET_EXTS, "File › Open imports perspective grid presets");
assert_eq!(at("Perspective grid presets"), at("Print presets") + 1, "among the presets");
assert_eq!(at("Export presets"), at("Perspective grid presets") + 1, "among the presets");
for e in [vectorcraft_doc::style_libs::STYLES_EXT].iter().chain(crate::cmd::perspgrid::PRESET_EXTS) {
assert!(!filters[0].1.contains(e), "All readable files lists documents only, not .{e}");
}
assert!(filters.contains(&("Export presets", SCREEN_EXPORT_PRESET_EXTS)), "File › Open imports export presets");
assert!(filters.contains(&("Scripts", crate::cmd::scripts::EXTS)), "File › Open checks scripts");
assert_eq!(filters.last(), Some(&("Plug-ins", crate::cmd::plugin::EXTS)), "File › Open installs plug-ins");
@@ -404,6 +415,11 @@ fn library_open_filters_list_library_formats_first() {
assert_eq!(filters[0], ("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS));
assert!(filters[0].1.contains(&"ase"));
assert_eq!(filters[1], ("All readable files", OPEN_EXTS));
let styles: &'static [&'static str] = std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT);
for (label, exts) in [("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS), ("Graphic Style Libraries", styles)] {
let filters: Vec<_> = library_open_filters(label, exts).collect();
assert_eq!(filters.iter().filter(|f| f.0 == label).count(), 1, "{label} is listed once");
}
}
/// The extensions usage texts list for export: one per writable format, each picking that format
+120
View File
@@ -56,6 +56,126 @@ fn export_pdf_writes_the_compatibility_header_and_the_range() {
assert!(b64(&v).starts_with(b"%PDF-1.6"));
}
/// `useArtboards: false` writes one page, the bounds of the visible art, as `document.export`
/// does, whatever artboards are chosen. Art longer than 200 in keeps its size with
/// `longPagesInPoints`. A document with no visible art and a value that isn't a boolean are
/// refused.
#[test]
fn use_artboards_false_writes_one_page_of_the_arts_bounds() {
let mut s = session(3);
let page = |bytes: &[u8]| {
let d = vectorcraft_pdf::import(bytes).unwrap();
(d.artboards.len(), d.artboards[0].rect.size())
};
let through_export = page(&b64(&s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap()));
assert!(through_export.0 == 1 && through_export.1.width < 50.0 && through_export.1.height < 40.0, "{through_export:?}");
for p in [
json!({"useArtboards": false}),
json!({"useArtboards": false, "range": "2"}),
json!({"useArtboards": false, "artboards": [0, 1]}),
json!({"useArtboards": false, "artboard": 2}),
] {
assert_eq!(page(&b64(&export(&mut s, p.clone()))), through_export, "{p}");
}
assert_eq!(pages(&b64(&export(&mut s, json!({"useArtboards": true})))), 3);
assert_eq!(pages(&b64(&export(&mut s, json!({"useArtboards": null})))), 3);
// A 10 m drawing on a small artboard: its page is 10 m long, in points.
s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 28_346.46, "height": 100})).unwrap();
let v = export(&mut s, json!({"useArtboards": false, "longPagesInPoints": true}));
let pdf = b64(&v);
let (n, size) = page(&pdf);
assert!(n == 1 && size.width > 28_346.0 && size.width < 28_350.0, "{size:?}");
assert!(!String::from_utf8_lossy(&pdf).contains("/UserUnit"));
assert!(warnings(&v).iter().any(|w| w.contains("written without a UserUnit, in points")), "{v}");
// The Summary's export in memory writes the same page.
let mut long = |p: Value| warnings(&s.execute("document.pdfSettings", &p).unwrap()).iter().any(|w| w.contains("longer than PDF's page limit"));
assert!(long(json!({"includeDocument": true, "useArtboards": false})));
assert!(!long(json!({"includeDocument": true})), "the artboards are small");
let e = s.execute("document.pdfSettings", &json!({"useArtboards": "no"})).unwrap_err();
assert!(matches!(e, crate::EngineError::BadParams { .. }), "without includeDocument too: {e}");
s.execute("select.all", &json!({})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
for p in [json!({"useArtboards": false}), json!({"useArtboards": "no"})] {
let e = s.execute("document.exportPdf", &p).unwrap_err();
assert!(matches!(e, crate::EngineError::BadParams { .. }), "{p}: {e}");
}
}
/// A PDF of the art's bounds carries no Preserve Editing data, through `document.exportPdf`,
/// `document.export` and the Summary's export in memory, and says so in a warning: reopened, its
/// editing data would replace the document's artboards with the one around the art. A PDF of the
/// artboards keeps the data, and it reopens with every artboard. With Preserve Editing off, there
/// is no warning.
#[test]
fn a_pdf_of_the_arts_bounds_carries_no_editing_data() {
let mut s = session(3);
let left_out = |v: &Value| warnings(v).iter().any(|w| w == super::pdf::EDITING_NEEDS_THE_ARTBOARDS);
let art = json!({"useArtboards": false});
for v in [export(&mut s, art.clone()), s.execute("document.export", &as_export(&art)).unwrap()] {
let pdf = b64(&v);
assert!(vectorcraft_pdf::editing(&pdf).is_none(), "{:?}", warnings(&v));
assert!(left_out(&v), "{:?}", warnings(&v));
assert_eq!(pages(&pdf), 1);
}
let summary = s.execute("document.pdfSettings", &json!({"includeDocument": true, "useArtboards": false})).unwrap();
assert!(left_out(&summary), "{summary}");
let quiet = export(&mut s, json!({"useArtboards": false, "preserveEditing": false}));
assert!(!left_out(&quiet), "{:?}", warnings(&quiet));
for v in [export(&mut s, json!({})), export(&mut s, json!({"useArtboards": true}))] {
let editing = vectorcraft_pdf::editing(&b64(&v)).expect("editing data");
let reopened = vectorcraft_format::load(&editing.data).unwrap();
assert_eq!(reopened.artboards.len(), 3);
assert!(!left_out(&v), "{:?}", warnings(&v));
}
}
/// While an opacity mask is edited, a PDF of the art's bounds measures the art without the
/// editing layer, as `document.export` does: a mask shape drawn past the masked object doesn't
/// widen the page.
#[test]
fn a_pdf_of_the_art_leaves_out_the_mask_editing_layer() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let obj = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()["id"].clone();
let mask = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"color": "#ffffff", "ids": [mask]})).unwrap();
s.execute("select.set", &json!({"ids": [obj, mask]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("transparency.editOpacityMask", &json!({})).unwrap();
s.execute("shape.ellipse", &json!({"x": 250, "y": 250, "width": 40, "height": 40})).unwrap();
assert!(s.doc().unwrap().doc.mask_edit.is_some());
let width = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().artboards[0].rect.width();
let through_export = width(&b64(&s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap()));
assert!(through_export < 250.0, "{through_export}");
assert_eq!(width(&b64(&export(&mut s, json!({"useArtboards": false})))), through_export);
}
/// While an opacity mask is edited, a PDF of the artboards leaves out the editing layer too, as
/// `document.export` does: from the drawn page and from the Preserve Editing data.
#[test]
fn a_pdf_of_the_artboards_leaves_out_the_mask_editing_layer() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let obj = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()["id"].clone();
let mask = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"color": "#ffffff", "ids": [mask]})).unwrap();
s.execute("select.set", &json!({"ids": [obj, mask]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("transparency.editOpacityMask", &json!({})).unwrap();
s.execute("shape.ellipse", &json!({"x": 250, "y": 250, "width": 40, "height": 40})).unwrap();
assert!(s.doc().unwrap().doc.mask_edit.is_some());
let nodes = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().node_count();
let plain = json!({"preserveEditing": false});
let through_export = nodes(&b64(&s.execute("document.export", &as_export(&plain)).unwrap()));
assert_eq!(nodes(&b64(&export(&mut s, plain))), through_export, "the drawn page");
let layers = |v: &Value| vectorcraft_format::load(&vectorcraft_pdf::editing(&b64(v)).unwrap().data).unwrap().layers;
let through_export = layers(&s.execute("document.export", &as_export(&json!({}))).unwrap());
assert_eq!(layers(&export(&mut s, json!({}))), through_export, "the Preserve Editing data");
}
#[test]
fn bad_options_are_refused() {
let mut s = session(2);
+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;
}
+2 -2
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Missing Fonts",
[],
None,
"{} → {fonts: [{family, style, status: missing|substitute, resolved: {family, style}}] (sorted by name; at most 1000), count, fontsNextToDocument?} the fonts the active document's type uses, in its layers and its symbols (for type in a composite font, the fonts of the parts its characters are drawn in), that aren't available as named: missing (the family is unknown and the fallback family stands in) or substitute (the family is there but not the style; resolved names the stand-in), as text.fonts says. CSS generic families such as sans-serif and names longer than 256 bytes are left out. fontsNextToDocument: the Fonts folder next to the saved document (File › Package writes it), when there is one and a search may start there (not in another app's folders, such as a mail app's attachments)",
"{} → {fonts: [{family, style, status: missing|substitute, resolved: {family, style}}] (sorted by name; at most 1000), count, fontsNextToDocument?} the fonts the active document's type uses, in its layers, its symbols and its patterns, opacity masks included (for type in a composite font, the fonts of the parts its characters are drawn in), that aren't available as named: missing (the family is unknown and the fallback family stands in) or substitute (the family is there but not the style; resolved names the stand-in), as text.fonts says. CSS generic families such as sans-serif and names longer than 256 bytes are left out. fontsNextToDocument: the Fonts folder next to the saved document (File › Package writes it), when there is one and a search may start there (not in another app's folders, such as a mail app's attachments)",
has_doc,
missing
),
@@ -103,7 +103,7 @@ pub struct MissingFont {
pub resolved: Option<(String, String)>,
}
/// The fonts the type of `d` uses, in its layers and its symbols (a composite font's parts, those
/// The fonts the type of `d` uses, in its layers, symbols and patterns, opacity masks included (a composite font's parts, those
/// its characters are drawn in, in place of its name), that aren't available as named (sorted by family and style, each once whatever version its type names; at most 1000). CSS generic families such as `sans-serif`
/// ([`GENERIC_FAMILIES`]) and names longer than 256 bytes are left out.
pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
+617 -177
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fonts in Document",
[],
None,
"{selectionOnly?} (the type in the art of the symbols in scope included: all of the document's, or those the selected instances show) → [{family, style, runs, objects, missing, status: exact|substitute|missing, resolved: {family, style}, missingGlyphs, version?: the installed version the type names (when it names one)}] sorted by name. A font is found by any of its names (ヒラギノ角ゴシック = Hiragino Sans) among the loaded and installed fonts; substitute: the family is there but not the style (resolved names the stand-in); missing: the family is unknown (the fallback family stands in); missingGlyphs: characters of its text the resolved font lacks (drawn by a fallback font). For a composite font, status is the worst among the parts its characters are drawn in, and missingGlyphs counts the characters their part's font lacks",
"{selectionOnly?} (the type in the opacity masks of the objects in scope and in the art of the symbols and patterns in scope included: all of the document's, a pattern swatch that nothing paints included, or those the selected objects show through their instances and paints; disabled masks too) → [{family, style, runs, objects, missing, status: exact|substitute|missing, resolved: {family, style}, missingGlyphs, version?: the installed version the type names (when it names one)}] sorted by name. A font is found by any of its names (ヒラギノ角ゴシック = Hiragino Sans) among the loaded and installed fonts; substitute: the family is there but not the style (resolved names the stand-in); missing: the family is unknown (the fallback family stands in); missingGlyphs: characters of its text the resolved font lacks (drawn by a fallback font). For a composite font, status is the worst among the parts its characters are drawn in, and missingGlyphs counts the characters their part's font lacks",
has_doc,
fonts
),
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Font",
[],
None,
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name, a composite font's as its own name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the art of the symbols in scope changes too (all of the document's, or those the selected instances show, so every instance of them follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's art), or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name, a composite font's as its own name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the opacity masks of the objects in scope (disabled masks too) and in the art of the symbols and patterns in scope changes too (all of the document's, or those the selected objects show through their instances and paints, so every instance of a symbol and every object a pattern paints follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's, pattern's or mask's art), in the mask of a hidden or locked object, or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
has_doc,
replace
),
@@ -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, and the instances of the symbols whose art uses it, that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; 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 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}",
has_doc,
select_font
),
@@ -64,15 +64,23 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// Text objects in scope: the selection's (and their descendants') or the whole document's.
fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> {
/// Text objects in scope: the selection's (and their descendants') or the whole document's, and
/// the objects among them that have an opacity mask (not the object whose mask is being edited:
/// its art is on the editing layer).
fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<(Vec<NodeId>, Vec<NodeId>)> {
let st = s.doc()?;
let mut v = vec![];
let editing = st.doc.mask_edit.map(|m| m.object);
let (mut texts, mut masked) = (vec![], vec![]);
let mut seen = HashSet::new();
let mut add = |n: &vectorcraft_doc::Node| {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::Text(_)) && seen.insert(c.id) {
v.push(c.id);
if seen.insert(c.id) {
if matches!(c.kind, NodeKind::Text(_)) {
texts.push(c.id);
}
if c.extras().mask.is_some() && Some(c.id) != editing {
masked.push(c.id);
}
}
})
};
@@ -87,7 +95,7 @@ fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Resu
add(l);
}
}
Ok(v)
Ok((texts, masked))
}
/// Whether `name` is the symbol being edited, whose art is on the editing layer.
@@ -95,106 +103,269 @@ fn being_edited(d: &Document, name: &str) -> bool {
d.symbol_edit.as_ref().is_some_and(|e| e.symbol == name)
}
/// The symbols that the selected objects of `s` show: those of the instances among them and their
/// descendants, and of the instances in those symbols' art that are not hidden or locked, nor in a
/// hidden or locked group of the art. Returned as (all of them, those shown by instances the
/// Selection tool can reach: not hidden or locked, as `Document::editable` says).
fn selected_symbols(s: &Session, selected: Option<&[NodeId]>) -> Result<(BTreeSet<String>, BTreeSet<String>)> {
fn open_instances(n: &Node, out: &mut BTreeSet<String>) {
/// Whether `name` is the pattern being edited, whose tile art is on the editing layer.
fn pattern_being_edited(d: &Document, name: &str) -> bool {
d.pattern_edit.as_ref().is_some_and(|e| e.pattern == name)
}
/// 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,
})
}
/// Symbols and patterns, by name: those whose art is in scope.
#[derive(Clone, Debug, Default)]
struct Resources {
symbols: BTreeSet<String>,
patterns: BTreeSet<String>,
}
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).
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));
if let Some(m) = n.extras().mask.as_deref() {
self.add(&m.art);
}
}
/// Adds what `n` and its descendants show, leaving out hidden or locked objects and what they
/// hold.
fn add(&mut self, n: &Node) {
if !n.visible || n.locked {
return;
}
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
out.insert(symbol.clone());
}
self.add_own(n);
for c in n.children().map(Vec::as_slice).unwrap_or_default() {
open_instances(c, out);
self.add(c);
}
}
let expand = |names: &mut BTreeSet<String>, d: &Document| loop {
let mut more = BTreeSet::new();
for sym in d.symbols.iter().filter(|sym| names.contains(&sym.name)) {
open_instances(&sym.art, &mut more);
/// Adds what the art of the symbols and patterns named shows, until nothing more is added; each
/// symbol and pattern is read once, so art that shows itself ends.
fn expand(&mut self, d: &Document) {
let mut symbols: Vec<String> = self.symbols.iter().cloned().collect();
let mut patterns: Vec<String> = self.patterns.iter().cloned().collect();
while !symbols.is_empty() || !patterns.is_empty() {
let mut more = Resources::default();
for name in symbols.drain(..) {
if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) {
more.add(&sym.art);
}
}
for name in patterns.drain(..) {
for art in d.pattern(&name).map(|p| p.art.as_slice()).unwrap_or_default() {
more.add(art);
}
}
symbols.extend(more.symbols.into_iter().filter(|name| self.symbols.insert(name.clone())));
patterns.extend(more.patterns.into_iter().filter(|name| self.patterns.insert(name.clone())));
}
let before = names.len();
names.extend(more);
if names.len() == before {
break;
}
/// The symbols and patterns of `self` that are not in `other`.
fn difference(&self, other: &Self) -> Self {
Self {
symbols: self.symbols.difference(&other.symbols).cloned().collect(),
patterns: self.patterns.difference(&other.patterns).cloned().collect(),
}
};
}
}
/// The symbols and patterns that the selected objects of `s` show: those of the instances among
/// them and their descendants and the patterns their paints name (also in the art of their
/// opacity masks), and those that the art of these symbols and patterns shows through objects that
/// are not hidden or locked, nor in a hidden or locked group of the art. Returned as (all of them,
/// those shown by objects the Selection tool can reach: not hidden or locked, as
/// `Document::editable` says).
fn selected_art(s: &Session, selected: Option<&[NodeId]>) -> Result<(Resources, Resources)> {
let st = s.doc()?;
let (mut all, mut open) = (BTreeSet::new(), BTreeSet::new());
let (mut all, mut open) = (Resources::default(), Resources::default());
let editable = st.doc.editable();
for id in selected.unwrap_or(&st.selection.objects) {
if let Some(n) = st.doc.node(*id) {
n.walk(&mut |c| {
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
all.insert(symbol.clone());
if editable(c.id) {
open.insert(symbol.clone());
}
all.add_own(c);
if editable(c.id) {
open.add_own(c);
}
});
}
}
drop(editable);
expand(&mut all, &st.doc);
expand(&mut open, &st.doc);
all.expand(&st.doc);
open.expand(&st.doc);
Ok((all, open))
}
/// The text objects in the art of `d`'s symbols (with `only`, of those it names), each with
/// whether it is open: neither it nor a group around it in the art is hidden or locked. The symbol
/// being edited is left out: its art is on the editing layer.
pub(super) fn symbol_texts<'a>(d: &'a Document, only: Option<&BTreeSet<String>>) -> Vec<(&'a TextObject, bool)> {
fn visit<'a>(n: &'a Node, open: bool, out: &mut Vec<(&'a TextObject, bool)>) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &n.kind {
out.push((&**t, open));
}
for c in n.children().map(Vec::as_slice).unwrap_or_default() {
visit(c, open, out);
}
/// A text object found in art: its id, the text and whether it is open (neither it nor a group
/// around it, nor an object whose opacity mask holds it, is hidden or locked).
pub(super) type ArtText<'a> = (NodeId, &'a TextObject, bool);
/// Adds the text objects of `n` and its descendants, the art of their opacity masks included, to
/// `out`; each is open when `open` holds and [`ArtText`] says so.
fn art_texts<'a>(n: &'a Node, open: bool, out: &mut Vec<ArtText<'a>>) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &n.kind {
out.push((n.id, &**t, open));
}
if let Some(m) = n.extras().mask.as_deref() {
art_texts(&m.art, open, out);
}
for c in n.children().map(Vec::as_slice).unwrap_or_default() {
art_texts(c, open, out);
}
}
/// The text objects in the art of the opacity masks of the objects `masked` (each with whether
/// the object is open: when it isn't, none of its mask's text is).
fn mask_texts<'a>(d: &'a Document, masked: &[(NodeId, bool)]) -> Vec<ArtText<'a>> {
let mut out = vec![];
for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.contains(&s.name))) {
visit(&s.art, true, &mut out);
for (id, open) in masked {
if let Some(m) = d.node(*id).and_then(|n| n.extras().mask.as_deref()) {
art_texts(&m.art, *open, &mut out);
}
}
out
}
/// Calls `f` on each text object in the art of `d`'s symbols (with `only`, of those it names) for
/// which `wants(text, open)` holds (open as in [`symbol_texts`]), the symbol being edited left out.
/// Art without such text is left as it is.
pub(super) fn edit_symbol_texts(
d: &mut Document,
only: Option<&BTreeSet<String>>,
wants: &impl Fn(&TextObject, bool) -> bool,
f: &mut impl FnMut(&mut TextObject),
) {
fn wanted(n: &Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool) -> bool {
let open = open && n.visible && !n.locked;
matches!(&n.kind, NodeKind::Text(t) if wants(t, open)) || n.children().is_some_and(|ch| ch.iter().any(|c| wanted(c, open, wants)))
/// The text objects in the art of `d`'s symbols and patterns (with `only`, of those it names, a
/// pattern's art read once however many objects it paints), opacity masks in that art included.
/// The symbol and the pattern being edited are left out: their art is on the editing layer.
fn resource_texts<'a>(d: &'a Document, only: Option<&Resources>) -> Vec<ArtText<'a>> {
let mut out = vec![];
for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.symbols.contains(&s.name))) {
art_texts(&s.art, true, &mut out);
}
fn visit(n: &mut Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &mut n.kind
&& wants(t, open)
{
f(t);
for p in d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name) && only.is_none_or(|o| o.patterns.contains(&p.name))) {
for art in &p.art {
art_texts(art, true, &mut out);
}
for c in n.children_mut().into_iter().flatten() {
if wanted(c, open, wants) {
visit(Arc::make_mut(c), open, wants, f);
}
out
}
/// The text objects in the art of `d`'s symbols (with `only`, of those it names), as
/// [`resource_texts`] finds them, each with whether it is open.
#[cfg(test)]
pub(super) fn symbol_texts<'a>(d: &'a Document, only: Option<&BTreeSet<String>>) -> Vec<(&'a TextObject, bool)> {
let mut out = vec![];
for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.contains(&s.name))) {
art_texts(&s.art, true, &mut out);
}
out.into_iter().map(|(_, t, open)| (t, open)).collect()
}
/// Whether `n` or a descendant (the art of their opacity masks included) holds a text object for
/// which `wants(text, open)` holds, open as [`ArtText`] says.
fn wanted(n: &Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool) -> bool {
let open = open && n.visible && !n.locked;
matches!(&n.kind, NodeKind::Text(t) if wants(t, open))
|| n.extras().mask.as_deref().is_some_and(|m| wanted(&m.art, open, wants))
|| n.children().is_some_and(|ch| ch.iter().any(|c| wanted(c, open, wants)))
}
/// Calls `f` on each text object of `n` and its descendants (the art of their opacity masks
/// included) for which `wants(text, open)` holds; only the nodes on the way to such text are
/// copied.
fn edit_art(n: &mut Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &mut n.kind
&& wants(t, open)
{
f(t);
}
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& wanted(&m.art, open, wants)
{
edit_art(Arc::make_mut(&mut m.art), open, wants, f);
}
for c in n.children_mut().into_iter().flatten() {
if wanted(c, open, wants) {
edit_art(Arc::make_mut(c), open, wants, f);
}
}
}
/// Calls `f` on each text object in the opacity masks of the objects `masked` (as [`mask_texts`]
/// finds them) for which `wants(text, open)` holds. Masks without such text are left as they are.
fn edit_mask_texts(d: &mut Document, masked: &[(NodeId, bool)], wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
for (id, open) in masked {
if d.node(*id).and_then(|n| n.extras().mask.as_deref()).is_some_and(|m| wanted(&m.art, *open, wants))
&& let Some(m) = d.node_mut(*id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut())
{
edit_art(Arc::make_mut(&mut m.art), *open, wants, f);
}
}
}
/// Calls `f` on each text object in the art of `d`'s symbols and patterns (as [`resource_texts`]
/// finds them) for which `wants(text, open)` holds. Art without such text is left as it is.
fn edit_resource_texts(d: &mut Document, only: Option<&Resources>, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
let symbol = d.symbol_edit.as_ref().map(|e| e.symbol.clone());
let pattern = d.pattern_edit.as_ref().map(|e| e.pattern.clone());
for s in &mut d.symbols {
if symbol.as_ref() != Some(&s.name) && only.is_none_or(|o| o.symbols.contains(&s.name)) && wanted(&s.art, true, wants) {
edit_art(Arc::make_mut(&mut s.art), true, wants, f);
}
}
for p in &mut d.patterns {
if pattern.as_ref() != Some(&p.name) && only.is_none_or(|o| o.patterns.contains(&p.name)) {
for art in &mut p.art {
if wanted(art, true, wants) {
edit_art(Arc::make_mut(art), true, wants, f);
}
}
}
}
let edited = d.symbol_edit.as_ref().map(|e| e.symbol.clone());
for s in &mut d.symbols {
if edited.as_ref() != Some(&s.name) && only.is_none_or(|o| o.contains(&s.name)) && wanted(&s.art, true, wants) {
visit(Arc::make_mut(&mut s.art), true, wants, f);
}
/// Every text object of `d` outside the objects of its layers: in the opacity masks of the
/// objects on its layers, and in the art of its symbols and patterns (as [`mask_texts`] and
/// [`resource_texts`] find them, each mask's text open).
pub(super) fn art_texts_of(d: &Document) -> Vec<ArtText<'_>> {
let masked = masked_objects(d);
let mut out = mask_texts(d, &masked);
out.extend(resource_texts(d, None));
out
}
/// Calls `f` on each text object of [`art_texts_of`] for which `wants(text)` holds.
pub(super) fn edit_art_texts_of(d: &mut Document, wants: &impl Fn(&TextObject) -> bool, f: &mut impl FnMut(&mut TextObject)) {
let masked = masked_objects(d);
edit_mask_texts(d, &masked, &|t, _| wants(t), f);
edit_resource_texts(d, None, &|t, _| wants(t), f);
}
/// The objects on the layers of `d` that have an opacity mask (not the object whose mask is being
/// edited), each as open.
fn masked_objects(d: &Document) -> Vec<(NodeId, bool)> {
let editing = d.mask_edit.map(|m| m.object);
let mut out = vec![];
d.walk(|n| {
if n.extras().mask.is_some() && Some(n.id) != editing {
out.push((n.id, true));
}
}
});
out
}
/// A font as type names it: family, style and, when it names one, the installed version.
@@ -218,14 +389,16 @@ pub(super) fn run_fonts(r: &TextRun) -> Vec<UsedFont> {
}
}
/// The fonts (family, style, version) the type in the layers and symbols of `d` is drawn in, a
/// composite font's parts in place of its name ([`run_fonts`]).
/// The fonts (family, style, version) the type in the layers, symbols and patterns of `d` is drawn
/// in, the type in opacity masks included, a composite font's parts in place of its name
/// ([`run_fonts`]).
pub(super) fn used_fonts(d: &Document) -> BTreeSet<UsedFont> {
art_fonts(d, &[])
}
/// The fonts (family, style, version) of the type in the layers and symbols of `d` and in `art`
/// (art read from a file, its resources in `d`).
/// The fonts (family, style, version) of the type in the layers, symbols and patterns of `d` and
/// in `art` (art read from a file, its resources in `d`), the type in opacity masks included. The
/// pattern being edited is read from the editing layer only.
pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
let mut fonts = BTreeSet::new();
let mut add = |n: &Node| {
@@ -233,12 +406,9 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
fonts.extend(t.runs.iter().flat_map(run_fonts));
}
};
d.walk(&mut add);
for s in &d.symbols {
s.art.walk(&mut add);
}
for n in art {
n.walk(&mut add);
let patterns = d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name)).flat_map(|p| p.art.iter().map(|a| &**a));
for n in d.layers.iter().map(|l| &**l).chain(d.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(art) {
vectorcraft_doc::swatches::walk_with_masks(n, &mut add);
}
fonts
}
@@ -513,50 +683,78 @@ impl Session {
pub fn skipped_font_ids(&self, params: &Value, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> {
let (family, style) = font_param(params, "from", "text.replaceFont")?;
let selection_only = bool_or(params, "selectionOnly", false);
let selected_symbols = selection_only.then(|| selected_symbols(self, selected)).transpose()?;
let d = &self.doc()?.doc;
let other: Vec<NodeId> = {
let editable = d.editable();
scope(self, selection_only, selected)?.into_iter().filter(|id| !editable(*id)).collect()
};
let in_scope = ReplaceScope::read(self, selection_only, selected)?;
let uses = |t: &TextObject| {
t.runs.iter().any(|r| {
r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|name| r.style.font_style.eq_ignore_ascii_case(name))
})
};
let mut ids = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).collect::<Vec<_>>();
fn visit(n: &Node, open: bool, closed: bool, uses: &impl Fn(&TextObject) -> bool, ids: &mut Vec<NodeId>) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &n.kind
&& (!open || closed)
&& uses(t)
{
ids.push(n.id);
}
for child in n.children().map(Vec::as_slice).unwrap_or_default() {
visit(child, open, closed, uses, ids);
}
Ok(in_scope.skipped(&self.doc()?.doc, &uses))
}
}
/// What Replace Font looks at: the text objects in scope that the Selection tool can reach and
/// those it can't, the objects with an opacity mask (each with whether it can reach them), and the
/// symbols and patterns whose art is in scope (`None`: all of the document's) with those shown
/// only by hidden or locked objects of the selection.
struct ReplaceScope {
ids: Vec<NodeId>,
other: Vec<NodeId>,
masked: Vec<(NodeId, bool)>,
resources: Option<Resources>,
closed: Resources,
}
impl ReplaceScope {
fn read(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<Self> {
// With selectionOnly: the symbols and patterns the selection shows; those shown only by
// hidden or locked objects keep their type, counted in `skipped`.
let (resources, closed) = if selection_only {
let (all, open) = selected_art(s, selected)?;
let closed = all.difference(&open);
(Some(open), closed)
} else {
(None, Resources::default())
};
let d = &s.doc()?.doc;
let editable = d.editable();
let (texts, masked) = scope(s, selection_only, selected)?;
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = texts.into_iter().partition(|id| editable(*id));
let masked = masked.into_iter().map(|id| (id, editable(id))).collect();
Ok(Self { ids, other, masked, resources, closed })
}
/// The text objects in the art of opacity masks, symbols and patterns in scope.
fn art<'a>(&self, d: &'a Document) -> Vec<ArtText<'a>> {
let mut texts = mask_texts(d, &self.masked);
texts.extend(resource_texts(d, self.resources.as_ref()));
texts
}
/// The text objects in scope set in a font `uses` matches that Replace Font leaves as they are:
/// those the Selection tool can't reach, hidden or locked text in art, and the text of the
/// symbols and patterns shown only by hidden or locked objects of the selection.
fn skipped(&self, d: &Document, uses: &impl Fn(&TextObject) -> bool) -> Vec<NodeId> {
let mut ids: Vec<NodeId> = self.other.iter().copied().filter(|id| text(d, *id).is_some_and(uses)).collect();
ids.extend(self.art(d).into_iter().filter(|(_, t, open)| !open && uses(t)).map(|(id, ..)| id));
if !self.closed.symbols.is_empty() || !self.closed.patterns.is_empty() {
ids.extend(resource_texts(d, Some(&self.closed)).into_iter().filter(|(_, t, _)| uses(t)).map(|(id, ..)| id));
}
for symbol in d
.symbols
.iter()
.filter(|symbol| !being_edited(d, &symbol.name) && selected_symbols.as_ref().is_none_or(|(all, _)| all.contains(&symbol.name)))
{
let closed = selected_symbols.as_ref().is_some_and(|(_, open)| !open.contains(&symbol.name));
visit(&symbol.art, true, closed, &uses, &mut ids);
}
Ok(ids)
ids
}
}
fn font_inventory(s: &Session, selected: Option<&[NodeId]>) -> Result<Value> {
let ids = scope(s, selected.is_some(), selected)?;
let (ids, masked) = scope(s, selected.is_some(), selected)?;
let d = &s.doc()?.doc;
let db = vectorcraft_text::FontDb::global();
// The type in the art of the symbols in scope too: all of them, or those the selection shows.
let symbols = if selected.is_some() { Some(selected_symbols(s, selected)?.0) } else { None };
// The type in the art of the opacity masks of the objects in scope, and of the symbols and
// patterns in scope: all of them, or those the selection shows.
let resources = if selected.is_some() { Some(selected_art(s, selected)?.0) } else { None };
let mut texts: Vec<&TextObject> = ids.iter().filter_map(|id| text(d, *id)).collect();
texts.extend(symbol_texts(d, symbols.as_ref()).into_iter().map(|(t, _)| t));
let masked: Vec<(NodeId, bool)> = masked.into_iter().map(|id| (id, true)).collect();
texts.extend(mask_texts(d, &masked).into_iter().map(|(_, t, _)| t));
texts.extend(resource_texts(d, resources.as_ref()).into_iter().map(|(_, t, _)| t));
// Each font's runs, objects and the text of its runs.
let mut found: BTreeMap<UsedFont, (usize, usize, Vec<&str>)> = BTreeMap::new();
for t in texts {
@@ -617,21 +815,6 @@ fn font_param(p: &Value, k: &str, c: &str) -> Result<(String, Option<String>)> {
Ok((family.to_string(), v.get("style").and_then(Value::as_str).map(str::to_string)))
}
fn skipped_font_texts(
d: &Document,
other: &[NodeId],
symbols: &[(&TextObject, bool)],
closed: &BTreeSet<String>,
uses: &impl Fn(&TextObject) -> bool,
) -> usize {
let mut skipped = other.iter().filter(|id| text(d, **id).is_some_and(uses)).count();
skipped += symbols.iter().filter(|(t, open)| !open && uses(t)).count();
if !closed.is_empty() {
skipped += symbol_texts(d, Some(closed)).into_iter().filter(|(t, _)| uses(t)).count();
}
skipped
}
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.replaceFont";
let (ff, fs) = font_param(p, "from", C)?;
@@ -660,35 +843,25 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
};
// Only text the Selection tool can reach changes: not hidden or locked, in a hidden or locked
// group or layer, or on a locked artboard. The text left in the font is counted. The type in
// the art of the symbols in scope (all of them, or those the selection shows) changes too,
// unless it or a group around it in the art is hidden or locked.
// the opacity masks of the objects in scope, and in the art of the symbols and patterns in
// scope (all of them, or those the selection shows), changes too, unless it, a group around it
// in the art or the object whose mask holds it is hidden or locked.
let selection_only = bool_or(p, "selectionOnly", false);
// With selectionOnly: the symbols the selection shows; those shown only by hidden or locked
// instances keep their type, counted in `skipped`.
let (symbols, closed) = if selection_only {
let (all, open) = selected_symbols(s, None)?;
let closed: BTreeSet<String> = all.difference(&open).cloned().collect();
(Some(open), closed)
} else {
(None, BTreeSet::new())
};
let uses = |t: &TextObject| t.runs.iter().any(|r| matches(&r.style));
// Whether a run of `t` changes.
let changes = |t: &TextObject| t.runs.iter().any(|r| new_style(&r.style).is_some());
let (ids, skipped, in_symbols) = {
let in_scope = ReplaceScope::read(s, selection_only, None)?;
let (ids, skipped, in_art) = {
let d = &s.doc()?.doc;
let editable = d.editable();
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only, None)?.into_iter().partition(|id| editable(*id));
let texts = symbol_texts(d, symbols.as_ref());
let skipped = skipped_font_texts(d, &other, &texts, &closed, &uses);
let skipped = in_scope.skipped(d, &uses).len();
// The text that changes: when none does, the document and its undo history stay as they are.
let ids: Vec<NodeId> = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect();
let in_symbols = texts.iter().any(|(t, open)| *open && changes(t));
(ids, skipped, in_symbols)
let ids: Vec<NodeId> = in_scope.ids.iter().copied().filter(|id| text(d, *id).is_some_and(changes)).collect();
let in_art = in_scope.art(d).iter().any(|(_, t, open)| *open && changes(t));
(ids, skipped, in_art)
};
// The fonts the replaced runs are set in, for the warning.
let mut set = BTreeSet::new();
let n = if ids.is_empty() && !in_symbols {
let n = if ids.is_empty() && !in_art {
0
} else {
s.edit("Replace Font", |d, _| {
@@ -717,7 +890,9 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
replace_in(t);
}
}
edit_symbol_texts(d, symbols.as_ref(), &|t, open| open && changes(t), &mut replace_in);
let wants = |t: &TextObject, open: bool| open && changes(t);
edit_mask_texts(d, &in_scope.masked, &wants, &mut replace_in);
edit_resource_texts(d, in_scope.resources.as_ref(), &wants, &mut replace_in);
Ok(n)
})?
};
@@ -734,13 +909,26 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// 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.
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))
|| 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))))
}
/// What Replace Font says when it left text in the font that it can't reach.
const REPLACE_SKIPPED: &str = "some text is hidden or locked, so its font wasn't replaced";
fn select_font(s: &mut Session, p: &Value) -> Result<Value> {
let family = str_param(p, "family").ok_or_else(|| bad("select.font", "missing `family`"))?.to_string();
let style = str_param(p, "style").map(str::to_string);
let ids = scope(s, false, None)?;
let (ids, masked) = scope(s, false, None)?;
let d = &s.doc()?.doc;
let within = FontScope::read(d, p)?;
// Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group
@@ -752,37 +940,40 @@ fn select_font(s: &mut Session, p: &Value) -> Result<Value> {
.any(|r| r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|x| r.style.font_style.eq_ignore_ascii_case(x)))
};
let mut hits: Vec<NodeId> = ids.into_iter().filter(|id| editable(*id) && text(d, *id).is_some_and(uses)).collect();
// The symbols whose art uses the font in type that is not hidden or locked, nor in a hidden or
// locked group of the art, also through the instances of other symbols it holds.
fn reaches(n: &Node, uses: &impl Fn(&TextObject) -> bool, symbols: &BTreeSet<&str>) -> bool {
n.visible
&& !n.locked
&& match &n.kind {
NodeKind::Text(t) => uses(t),
NodeKind::SymbolInstance { symbol, .. } => symbols.contains(symbol.as_str()),
_ => n.children().is_some_and(|ch| ch.iter().any(|c| reaches(c, uses, symbols))),
}
}
let mut symbols: BTreeSet<&str> = BTreeSet::new();
// The symbols and patterns whose art uses the font in type that is not hidden or locked, nor in
// a hidden or locked group of the art, also through the instances, patterns and opacity masks
// it holds. The pattern being edited is left out: its art is on the editing layer.
let mut found = Resources::default();
loop {
let found: Vec<&str> = d
let symbols: Vec<String> = d
.symbols
.iter()
.filter(|sym| !symbols.contains(sym.name.as_str()) && reaches(&sym.art, &uses, &symbols))
.map(|sym| sym.name.as_str())
.filter(|sym| !found.symbols.contains(&sym.name) && reaches(&sym.art, &uses, &found))
.map(|sym| sym.name.clone())
.collect();
if found.is_empty() {
let patterns: Vec<String> = d
.patterns
.iter()
.filter(|p| !pattern_being_edited(d, &p.name) && !found.patterns.contains(&p.name) && p.art.iter().any(|a| reaches(a, &uses, &found)))
.map(|p| p.name.clone())
.collect();
if symbols.is_empty() && patterns.is_empty() {
break;
}
symbols.extend(found);
found.symbols.extend(symbols);
found.patterns.extend(patterns);
}
// Their instances the Selection tool can reach.
if !symbols.is_empty() {
// 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).
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| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& symbols.contains(symbol.as_str())
&& editable(n.id)
{
let shows = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if found.symbols.contains(symbol))
|| paint_patterns(n).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);
}
});
@@ -1311,6 +1502,255 @@ mod tests {
assert_eq!(s.execute("text.replaceFont", &serif_to_sans).unwrap(), json!({"runs": 0}));
}
/// Moves object `art` of the layers into the opacity mask of `owner` (a layer or an object).
fn mask_with(s: &mut Session, owner: u64, art: u64) {
s.edit("Mask", |d, _| {
let art = d.remove(NodeId(art))?;
d.node_mut(NodeId(owner)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
Ok(())
})
.unwrap();
}
/// The font families of the first runs of the text in the opacity mask of `owner`.
fn mask_families(s: &Session, owner: u64) -> Vec<String> {
let d = &s.doc().unwrap().doc;
mask_texts(d, &[(NodeId(owner), true)]).iter().map(|(_, t, _)| t.runs[0].style.font_family.clone()).collect()
}
/// The font families of the first runs of the text in the art of pattern `name`.
fn pattern_families(s: &Session, name: &str) -> Vec<String> {
let d = &s.doc().unwrap().doc;
let mut out = vec![];
for art in &d.pattern(name).unwrap().art {
art_texts(art, true, &mut out);
}
out.iter().map(|(_, t, _)| t.runs[0].style.font_family.clone()).collect()
}
/// The rows of `text.fonts` with `p`: family, runs and objects.
fn font_rows(s: &mut Session, p: Value) -> Vec<(String, u64, u64)> {
let fonts = s.execute("text.fonts", &p).unwrap();
fonts
.as_array()
.unwrap()
.iter()
.map(|f| (f["family"].as_str().unwrap().to_string(), f["runs"].as_u64().unwrap(), f["objects"].as_u64().unwrap()))
.collect()
}
/// Find Font lists, selects and changes the type in opacity masks: on objects, on a layer,
/// disabled and inside the art of another mask. The type in the mask of a locked object is
/// listed and left in its font; Find selects the objects whose mask holds the type.
#[test]
fn find_font_reaches_the_type_in_opacity_masks() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let text = |s: &mut Session, y: i32| {
s.execute("text.create", &json!({"x": 10, "y": y, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap()
};
let rect = |s: &mut Session, y: i32| {
s.execute("shape.rectangle", &json!({"x": 0, "y": y, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap()
};
let mut owners = vec![];
for y in [20, 50, 80] {
let owner = rect(&mut s, y);
let t = text(&mut s, y);
mask_with(&mut s, owner, t);
owners.push(owner);
}
let (open, locked, disabled) = (owners[0], owners[1], owners[2]);
s.execute("select.set", &json!({"ids": [locked]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [disabled]})).unwrap();
s.execute("transparency.disableOpacityMask", &json!({})).unwrap();
// A mask whose art is an object with a mask of its own, and a layer's mask.
let nested = rect(&mut s, 110);
let inner = rect(&mut s, 110);
let t = text(&mut s, 110);
mask_with(&mut s, inner, t);
mask_with(&mut s, nested, inner);
let layer = s.doc().unwrap().doc.layers[0].id.0;
let t = text(&mut s, 140);
mask_with(&mut s, layer, t);
let mut on_layers = 0;
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
assert_eq!(on_layers, 0, "the type is only in masks");
assert_eq!(font_rows(&mut s, json!({})), [("Source Serif 4".to_string(), 5, 5)]);
s.execute("select.set", &json!({"ids": [open]})).unwrap();
assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), [("Source Serif 4".to_string(), 1, 1)]);
// Find selects the objects whose mask holds the type, not the locked one or the layer.
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 3);
let mut selected = s.doc().unwrap().selection.objects.clone();
selected.sort();
assert_eq!(selected, [NodeId(open), NodeId(disabled), NodeId(nested)]);
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4", "scope": {"artboards": [0]}})).unwrap()["count"], 3);
// Change All: one undo step, the locked object's mask left in its font and counted.
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
let serif_to_sans = json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}});
let r = s.execute("text.replaceFont", &serif_to_sans).unwrap();
assert_eq!((r["runs"].as_u64(), r["skipped"].as_u64()), (Some(4), Some(1)), "{r}");
assert_eq!(steps(&s), before + 1);
for owner in [open, disabled, nested, layer] {
assert_eq!(mask_families(&s, owner), ["Source Sans 3"], "the mask of {owner}");
}
assert_eq!(mask_families(&s, locked), ["Source Serif 4"]);
let r = s.execute("text.replaceFont", &serif_to_sans).unwrap();
assert_eq!(r, json!({"runs": 0, "skipped": 1, "warning": REPLACE_SKIPPED}));
assert_eq!(steps(&s), before + 1);
s.execute("edit.undo", &json!({})).unwrap();
for owner in [open, disabled, nested, layer] {
assert_eq!(mask_families(&s, owner), ["Source Serif 4"], "the mask of {owner} after Undo");
}
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(mask_families(&s, nested), ["Source Sans 3"]);
// While a mask is edited, its type on the editing layer is counted and changed once.
s.execute("transparency.editOpacityMask", &json!({"id": open})).unwrap();
assert_eq!(font_rows(&mut s, json!({})), [("Source Sans 3".to_string(), 4, 4), ("Source Serif 4".to_string(), 1, 1)]);
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap();
assert_eq!(r["runs"].as_u64(), Some(4), "{r}");
let families: Vec<String> = used_fonts(&s.doc().unwrap().doc).into_iter().map(|(family, ..)| family).collect();
assert_eq!(families, ["Inter", "Source Serif 4"], "the edited mask is written back after each edit");
s.execute("transparency.stopEditingOpacityMask", &json!({})).unwrap();
assert_eq!(mask_families(&s, open), ["Inter"]);
}
/// Find Font lists the type in pattern swatches once, also when nothing paints with them;
/// Find selects the objects the pattern paints, and Change changes the pattern's art once for
/// every object it paints. While a pattern is edited, its type is taken from the editing layer.
#[test]
fn find_font_reaches_the_type_in_patterns() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let pattern = |s: &mut Session, name: &str, font: &str| {
let t = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab", "font": font})).unwrap()["id"].as_u64().unwrap();
s.execute("object.pattern.make", &json!({"ids": [t], "name": name, "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [t]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
};
pattern(&mut s, "Dots", "Source Serif 4");
pattern(&mut s, "Unused", "Inter");
let mut on_layers = 0;
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
assert_eq!(on_layers, 0, "the type is only in patterns");
let all = [("Inter".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)];
assert_eq!(font_rows(&mut s, json!({})), all);
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0);
let mut painted = vec![];
for y in [20, 60] {
painted.push(s.execute("shape.rectangle", &json!({"x": 0, "y": y, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap());
}
s.execute("paint.setFill", &json!({"swatch": "Dots", "ids": painted})).unwrap();
assert_eq!(font_rows(&mut s, json!({})), all, "a pattern's type counts once");
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 2);
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(painted[0]), NodeId(painted[1])]);
assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 0);
// Only the selection: the patterns the selected objects paint with.
s.execute("select.set", &json!({"ids": [painted[0]]})).unwrap();
assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), [("Source Serif 4".to_string(), 1, 1)]);
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
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!(steps(&s), before + 1);
assert_eq!(pattern_families(&s, "Dots"), ["Source Sans 3"]);
assert_eq!(pattern_families(&s, "Unused"), ["Inter"]);
// No run changes: no undo step.
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Source Sans 3"}})).unwrap();
assert_eq!(r, json!({"runs": 0}));
assert_eq!(steps(&s), before + 1);
// Change All reaches the swatch nothing paints with.
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Serif 4"}})).unwrap();
assert_eq!(r, json!({"runs": 1}));
assert_eq!(pattern_families(&s, "Unused"), ["Source Serif 4"]);
// A pattern in a hidden fill doesn't show: Find doesn't select the object for its type.
let hidden = s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Unused", "ids": [hidden]})).unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1);
s.edit("Hide the fill", |d, _| {
for it in d.node_mut(NodeId(hidden)).unwrap().appearance.items.iter_mut() {
if let AppearanceItem::Fill(f) = it {
f.visible = false;
}
}
Ok(())
})
.unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0);
// Nor does a pattern on a stroke of no width.
s.execute("paint.setStroke", &json!({"swatch": "Unused", "ids": [hidden]})).unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1);
s.edit("Thin the stroke", |d, _| {
for it in d.node_mut(NodeId(hidden)).unwrap().appearance.items.iter_mut() {
if let AppearanceItem::Stroke(st) = it {
st.width = 0.0;
}
}
Ok(())
})
.unwrap();
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0);
// A locked painted object: its pattern's type is listed and left in its font.
s.execute("select.set", &json!({"ids": [painted[1]]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [painted[1]]})).unwrap();
let r =
s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}, "selectionOnly": true})).unwrap();
assert_eq!((r["runs"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}");
assert_eq!(s.execute("select.font", &json!({"family": "Source Sans 3"})).unwrap()["count"], 1);
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(painted[0])]);
// While the pattern is edited, its type on the editing layer is counted and changed once.
s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap();
let rows = font_rows(&mut s, json!({}));
assert_eq!(rows, [("Source Sans 3".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)]);
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap();
assert_eq!(r, json!({"runs": 1}));
let families: Vec<String> = used_fonts(&s.doc().unwrap().doc).into_iter().map(|(family, ..)| family).collect();
assert_eq!(families, ["Inter", "Source Serif 4"], "the pattern's stored art is left out while it is edited");
s.execute("object.pattern.done", &json!({})).unwrap();
assert_eq!(pattern_families(&s, "Dots"), ["Inter"]);
}
/// A pattern whose art holds a symbol instance, painting objects inside and outside a symbol:
/// Find Font lists each pattern's and symbol's type once and reaches the symbol's type through
/// the pattern.
#[test]
fn find_font_reaches_symbols_through_patterns() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let inter = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "In", "font": "Inter"})).unwrap()["id"].clone();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [inter]})).unwrap();
let instance = s.doc().unwrap().selection.objects[0].0;
let serif = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Se", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap();
let tile = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 80})).unwrap()["id"].as_u64().unwrap();
s.execute("object.pattern.make", &json!({"ids": [tile, serif, instance], "name": "Loop", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [tile, serif, instance]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
// Another object paints with the pattern too: its type is still read once.
let other = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [other]})).unwrap();
s.execute("symbol.new", &json!({"name": "Outer", "ids": [other]})).unwrap();
let outer = s.doc().unwrap().selection.objects[0];
let painted = s.execute("shape.rectangle", &json!({"x": 0, "y": 100, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Loop", "ids": [painted]})).unwrap();
let both = [("Inter".to_string(), 1, 1), ("Source Serif 4".to_string(), 1, 1)];
assert_eq!(font_rows(&mut s, json!({})), both);
s.execute("select.set", &json!({"ids": [painted]})).unwrap();
assert_eq!(font_rows(&mut s, json!({"selectionOnly": true})), both);
// Find reaches the symbol's type through the pattern, and through a symbol whose art paints
// with the pattern.
assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 2);
assert_eq!(s.doc().unwrap().selection.objects, [outer, NodeId(painted)]);
s.execute("select.set", &json!({"ids": [painted]})).unwrap();
let r =
s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "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");
}
/// 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()
+2
View File
@@ -1060,6 +1060,8 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps
};
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
}
// Color masks of images whose files were read again are made for the new pixels.
super::refresh_color_masks(None, d);
out
}
+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 }))
}
}
+13 -5
View File
@@ -701,7 +701,9 @@ fn colorized_images(d: &Document, ids: &[NodeId], paint: &Paint) -> std::result:
out.push(*id);
continue;
}
let Some(gray) = d.image_blob(im).and_then(|b| b.gray_source()) else { continue };
// A color-masked image is colorized as it shows: its masked pixels, which have an alpha
// channel.
let Some(gray) = d.image_blob(&d.shown_image(n, im)).and_then(|b| b.gray_source()) else { continue };
match paint {
// Without a color, `none` goes to the image's fill item.
Paint::None => continue,
@@ -758,11 +760,17 @@ pub(super) fn check_colorized_kept(was_ok: bool, d: &Document) -> std::result::R
if was_ok { check_colorized(d) } else { Ok(()) }
}
/// How the pixels of `n` are gray, when `n` is a grayscale or 1-bit image colorized with a color
/// that [`colorizes_transparency`] refuses. Such an image can't have an alpha channel.
/// Is `n` an image colorized with a color that [`colorizes_transparency`] refuses? When its pixels
/// are grayscale or 1-bit, they can't have an alpha channel.
pub(super) fn colorized_with_process(d: &Document, n: &Node) -> bool {
matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.as_deref().is_some_and(|paint| !colorizes_transparency(d, paint))
}
/// How the pixels `n` shows are gray, when `n` is a grayscale or 1-bit image colorized with a
/// color that [`colorizes_transparency`] refuses ([`colorized_with_process`]).
pub(super) fn gray_colorized_with_process(d: &Document, n: &Node) -> Option<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`]?
File diff suppressed because one or more lines are too long
+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));
}
});
}
@@ -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",
@@ -472,6 +475,7 @@ pub(super) const ALLOWED: &[&str] = &[
"perspective.transform",
"recolor.apply",
"recolor.colors",
"recolor.pickTheme",
"recolor.randomize",
"recolor.reduce",
"select.add",
@@ -479,6 +483,7 @@ pub(super) const ALLOWED: &[&str] = &[
"select.allOnArtboard",
"select.anchors",
"select.anchorsMany",
"select.byNote",
"select.color",
"select.font",
"select.globalEdit",
@@ -627,6 +632,8 @@ pub(super) const ALLOWED: &[&str] = &[
"text.thread.releaseSelection",
"text.thread.remove",
"text.touchType",
"threeD.addGraphic",
"threeD.mapGraphic",
"transparency.disableOpacityMask",
"transparency.editOpacityMask",
"transparency.enableOpacityMask",
File diff suppressed because it is too large Load Diff
+128
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;
@@ -103,6 +104,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",
@@ -730,6 +740,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 {
File diff suppressed because one or more lines are too long
+12 -2
View File
@@ -215,6 +215,8 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
("tateChuYoko", json!(v.tate_chu_yoko)),
("tcyUpDown", json!(v.tcy_up_down)),
("tcyLeftRight", json!(v.tcy_left_right)),
("akiLeft", json!(v.aki_left)),
("akiRight", json!(v.aki_right)),
("standardVerticalRoman", json!(v.standard_vertical_roman)),
("noBreak", json!(v.no_break)),
("digits", json!(v.digits)),
@@ -558,6 +560,12 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max)));
}
}
let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI);
for (key, value) in [("akiLeft", st.aki_left), ("akiRight", st.aki_right)] {
if changed(key) && !(lo..=hi).contains(&value) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
}
// A language of the list, stored as its tag (as text.setFormat takes it).
if let Some(l) = &st.language
&& kept.and_then(|k| k.get("language")) != m.get("language")
@@ -1042,17 +1050,19 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, whose
/// scales, leading, shifts, Insert Aki or stroke width are out of the range `charStyle.new` takes, whose
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
/// `src` of those skipped)
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
const RANGED: [&str; 16] = [
const RANGED: [&str; 18] = [
"size",
"h_scale",
"v_scale",
"leading",
"baseline_shift",
"akiLeft",
"akiRight",
"tcyUpDown",
"tcyLeftRight",
"stroke_width",
+4 -1
View File
@@ -395,6 +395,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
json!({"baseline_shift": 1296.1}),
json!({"tcyUpDown": 1296.1}),
json!({"tcyLeftRight": -1296.1}),
json!({"akiLeft": -0.1}),
json!({"akiRight": 1000.1}),
] {
let key = attrs.as_object().unwrap().keys().next().unwrap();
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
@@ -416,7 +418,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
"size": 1296.0, "leading": 5000.0,
"h_scale": 1.0, "v_scale": 10000.0,
"baseline_shift": -1296.0,
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0,
"akiLeft": 0.0, "akiRight": 1000.0
}}),
)
.unwrap();
@@ -1663,6 +1663,63 @@ fn tate_chu_yoko_settings_are_character_attributes_saved_only_when_set() {
assert_eq!(offsets(&s), before);
}
/// Insert Aki Left and Right (Character panel, East Asian options): character attributes in
/// thousandths of an em, 0 by default and saved only when not 0. Both commands set either side
/// alone, keeping the other side of every run, in one undo step; a value that is not a number or
/// lies outside 0 to 1000 is refused, naming the key, before anything changes; a character style
/// captured from the characters carries them.
#[test]
fn insert_aki_is_a_character_attribute_set_one_side_at_a_time() {
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 runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.runs.clone(),
_ => panic!("text"),
};
let aki = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.aki_left, r.style.aki_right)).collect::<Vec<_>>();
let saved = serde_json::to_value(&runs(&s)[0].style).unwrap();
assert!(saved.get("akiLeft").is_none() && saved.get("akiRight").is_none());
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("text.setFormat", &json!({"akiLeft": 250})).unwrap();
assert_eq!(aki(&s), [("(日本)".to_string(), 250.0, 0.0)]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(aki(&s), [("(日本)".to_string(), 0.0, 0.0)], "one undo step");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(aki(&s), [("(日本)".to_string(), 250.0, 0.0)]);
// One side on part of the text: the runs keep their other side.
let paren = "(".len();
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": paren, "akiRight": 500})).unwrap();
assert_eq!(aki(&s), [("(".to_string(), 250.0, 500.0), ("日本)".to_string(), 250.0, 0.0)]);
s.execute("text.setFormat", &json!({"akiLeft": 0})).unwrap();
assert_eq!(aki(&s), [("(".to_string(), 0.0, 500.0), ("日本)".to_string(), 0.0, 0.0)]);
let saved = serde_json::to_value(&runs(&s)[0].style).unwrap();
assert_eq!((saved.get("akiLeft"), saved["akiRight"].clone()), (None, json!(500.0)));
// Saved and reopened as they were.
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.aki_left, r.style.aki_right)).collect();
assert_eq!(reopened, aki(&s));
let attrs = super::super::textstyles::char_attrs(&runs(&s)[0].style);
assert_eq!((attrs["akiLeft"].clone(), attrs["akiRight"].clone()), (json!(0.0), json!(500.0)));
let before = aki(&s);
let undo = s.doc().unwrap().history.undo.len();
for (cmd, p, want) in [
("text.setFormat", json!({"akiLeft": "250"}), "`akiLeft` must be a number"),
("text.setFormat", json!({"akiRight": -1}), "`akiRight` must be from 0 to 1000"),
("text.setFormat", json!({"akiLeft": 250, "akiRight": 1000.5}), "`akiRight` must be from 0 to 1000"),
("text.setRangeStyle", json!({"id": id, "akiRight": true}), "`akiRight` must be a number"),
("text.setRangeStyle", json!({"id": id, "start": 0, "end": paren, "akiLeft": 2000}), "`akiLeft` must be from 0 to 1000"),
] {
let e = s.execute(cmd, &p).unwrap_err();
assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{cmd} {p}: {e}");
}
assert_eq!(aki(&s), before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call");
}
/// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character
/// attribute, off by default and saved only when on. Documents written before it read as off; a
/// character style captured from the characters carries it.
+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.
+3 -3
View File
@@ -2179,8 +2179,8 @@ fn failure_text(report: &Value) -> String {
let s = |k: &str| report[k].as_str().unwrap_or_default();
let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0));
let at = match report["file"].as_str() {
Some(file) if line > 0 => format!(" line {line}, column {column} of {file}"),
_ if line > 0 => format!(" line {line}, column {column}"),
Some(file) if line > 0 => format!(": line {line}, column {column} of {file}"),
_ if line > 0 => format!(": line {line}, column {column}"),
_ => String::new(),
};
let written = report["written"].as_array().map_or(0, Vec::len);
@@ -2190,7 +2190,7 @@ fn failure_text(report: &Value) -> String {
} else {
String::new()
};
format!("{}:{at}: {} ({}){kept}", s("name"), s("message"), s("kind"))
format!("{}{at}: {} ({}){kept}", s("name"), s("message"), s("kind"))
}
/// A run's slice: the working copy in, the real session lent to the host functions, one measured
+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);
+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.
+216
View File
@@ -492,6 +492,222 @@ fn pasting_again_reuses_what_an_earlier_paste_added() {
assert!(doc(&s).swatch("Brand 3").is_none() && doc(&s).char_styles.len() == 1);
}
/// The active document, to edit its definitions directly.
fn doc_mut(s: &mut Session) -> &mut Document {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
}
/// The pattern a paint paints with.
fn pattern_of(p: &Paint) -> Option<&str> {
match p {
Paint::Pattern { pattern, .. } => Some(pattern),
_ => None,
}
}
/// The pattern the fill of the active document's character style `name` paints with.
fn style_pattern(s: &Session, name: &str) -> Option<String> {
let attrs = &doc(s).char_styles.iter().find(|x| x.name == name)?.attrs;
pattern_of(&serde_json::from_value::<Paint>(attrs.get("fill")?.clone()).ok()?).map(str::to_string)
}
/// A pattern "Dots" made from a `size` square of `color` in the active document.
fn dots(s: &mut Session, size: f64, color: &str) {
let square = rect(s, 300.0, 200.0, size, size);
s.execute("paint.setFill", &json!({"ids": [square.0], "color": color})).unwrap();
s.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [square.0]})).unwrap();
}
/// Type "Hi" filled with the pattern "Dots" (a small red square), set in a character style
/// "Patterned" whose fill is that pattern.
fn patterned_type(s: &mut Session) -> NodeId {
dots(s, 10.0, "#ff0000");
let t = id_of(&s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hi"})).unwrap());
s.execute("paint.setFill", &json!({"ids": [t.0], "swatch": "Dots"})).unwrap();
s.execute("charStyle.new", &json!({"name": "Patterned", "id": t.0})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Patterned", "id": t.0})).unwrap();
t
}
/// The character style name of a type object's first run, and the pattern that run paints with.
fn type_links(s: &Session, id: NodeId) -> (Option<String>, Option<String>) {
let NodeKind::Text(tx) = node(s, id).kind else { panic!("not type") };
(tx.runs[0].style.style_name.clone(), pattern_of(&tx.runs[0].style.fill).map(str::to_string))
}
/// Type set in a style that paints with a pattern, pasted into a document with another pattern of
/// that name: the pattern comes in as "Dots 2", and the style paints with "Dots 2" too, so applying
/// it later paints with the pasted pattern. Pasting again adds nothing.
#[test]
fn pasted_styles_paint_with_the_renamed_pattern_they_use() {
let mut s = session();
let t = patterned_type(&mut s);
copy(&mut s, &[t]);
new_doc(&mut s);
dots(&mut s, 30.0, "#0000ff");
let v = s.execute("edit.paste", &json!({})).unwrap();
assert!(doc(&s).pattern("Dots 2").is_some(), "{v}");
assert_eq!(style_pattern(&s, "Patterned").as_deref(), Some("Dots 2"), "{v}");
let named = |n: &str| Some(n.to_string());
assert_eq!(type_links(&s, ids_of(&v)[0]), (named("Patterned"), named("Dots 2")));
let other = id_of(&s.execute("text.create", &json!({"x": 10, "y": 150, "text": "Yo"})).unwrap());
s.execute("charStyle.apply", &json!({"name": "Patterned", "id": other.0})).unwrap();
assert_eq!(type_links(&s, other).1.as_deref(), Some("Dots 2"), "the applied style paints with the pasted pattern");
let counts = |s: &Session| (doc(s).patterns.len(), doc(s).char_styles.len());
let before = counts(&s);
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(v["added"], 0, "{v}");
assert_eq!(counts(&s), before);
assert_eq!(type_links(&s, ids_of(&v)[0]), (named("Patterned"), named("Dots 2")));
}
/// A document whose "Patterned" style has the pasted style's attributes but whose "Dots" is
/// another pattern: that style paints with the document's "Dots", so the pasted one comes in as
/// "Patterned 2", painting with "Dots 2", and the document's own is left as it was. Pasting again
/// uses the numbered copies.
#[test]
fn pasted_styles_are_not_matched_to_styles_that_paint_with_another_pattern() {
let mut s = session();
let t = patterned_type(&mut s);
let style = doc(&s).char_styles.iter().find(|x| x.name == "Patterned").unwrap().clone();
copy(&mut s, &[t]);
new_doc(&mut s);
dots(&mut s, 30.0, "#0000ff");
doc_mut(&mut s).char_styles.push(style);
let own = (doc(&s).char_styles.clone(), doc(&s).pattern("Dots").cloned());
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(style_pattern(&s, "Patterned 2").as_deref(), Some("Dots 2"), "{v}");
let d = doc(&s);
assert_eq!((&d.char_styles[..own.0.len()], d.pattern("Dots")), (&own.0[..], own.1.as_ref()), "the document's own are unchanged");
let named = |n: &str| Some(n.to_string());
let links = (named("Patterned 2"), named("Dots 2"));
assert_eq!(type_links(&s, ids_of(&v)[0]), links);
let counts = |s: &Session| (doc(s).patterns.len(), doc(s).char_styles.len());
let before = counts(&s);
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(v["added"], 0, "{v}");
assert_eq!(counts(&s), before);
assert_eq!(type_links(&s, ids_of(&v)[0]), links);
}
/// A style that paints with a pattern whose tile sets type in that same style is pasted with the
/// pattern: when the pattern comes in as "Dots 2", the style paints with "Dots 2", and the tile's
/// type is set in the style. Pasting again adds nothing. The commands do not make that loop, so the
/// source is a document edited directly.
#[test]
fn a_pasted_style_and_the_pattern_whose_tile_uses_it_come_in_together() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Tile"})).unwrap());
s.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 40}})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Accent", "id": t.0})).unwrap();
s.execute("object.pattern.make", &json!({"name": "Dots", "edit": false, "ids": [t.0]})).unwrap();
let other = id_of(&s.execute("text.create", &json!({"x": 10, "y": 90, "text": "B"})).unwrap());
s.execute("charStyle.apply", &json!({"name": "Accent", "id": other.0})).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Dots", "ids": [other.0]})).unwrap();
s.execute("charStyle.new", &json!({"name": "Painted", "id": other.0})).unwrap();
let d = doc_mut(&mut s);
let painted = d.char_styles.iter().find(|x| x.name == "Painted").unwrap().attrs.clone();
d.char_styles.retain(|x| x.name != "Painted");
d.char_styles.iter_mut().find(|x| x.name == "Accent").unwrap().attrs = painted;
assert_eq!(style_pattern(&s, "Accent").as_deref(), Some("Dots"));
copy(&mut s, &[other]);
new_doc(&mut s);
dots(&mut s, 30.0, "#0000ff");
let v = s.execute("edit.paste", &json!({})).unwrap();
assert!(doc(&s).pattern("Dots 2").is_some(), "{v}");
assert_eq!(style_pattern(&s, "Accent").as_deref(), Some("Dots 2"), "{v}");
let NodeKind::Text(tile) = &doc(&s).pattern("Dots 2").unwrap().art[0].kind else { panic!("the tile is type") };
assert_eq!(tile.runs[0].style.style_name.as_deref(), Some("Accent"));
let after = doc(&s).clone();
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(v["added"], 0, "{v}");
assert!(doc(&s).patterns == after.patterns && doc(&s).char_styles == after.char_styles, "nothing is added");
// Back in the source document, the loop is the document's own.
s.execute("document.activate", &json!({"index": 0})).unwrap();
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!((v["added"].as_u64(), v["renamed"].as_array().map(Vec::len)), (Some(0), Some(0)), "{v}");
}
/// A symbol whose art paints with a pattern is not matched to the document's symbol of that name
/// and art when the document's pattern of that name is another one: it comes in as "Mark 2",
/// painting with "Dots 2".
#[test]
fn pasted_symbols_are_not_matched_to_symbols_that_paint_with_another_pattern() {
let mut s = session();
dots(&mut s, 10.0, "#ff0000");
let r = rect(&mut s, 20.0, 20.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"ids": [r.0], "swatch": "Dots"})).unwrap();
sel(&mut s, &[r]);
let mark = id_of(&s.execute("symbol.new", &json!({"name": "Mark"})).unwrap());
copy(&mut s, &[mark]);
// The document gets "Mark" and "Dots" from a first paste; then its "Dots" gets another tile.
new_doc(&mut s);
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(v["renamed"], json!([]), "{v}");
let tile = &mut doc_mut(&mut s).patterns.iter_mut().find(|p| p.name == "Dots").unwrap().tile;
*tile = Rect::new(tile.x0, tile.y0, tile.x1 + 30.0, tile.y1 + 30.0);
let v = s.execute("edit.paste", &json!({})).unwrap();
assert!(renamed(&v).contains(&("symbol".to_string(), "Mark".to_string(), "Mark 2".to_string())), "{v}");
let art = |s: &Session, name: &str| fill_of(&doc(s).symbols.iter().find(|x| x.name == name).unwrap().art);
assert_eq!((art(&s, "Mark").as_deref(), art(&s, "Mark 2").as_deref()), (Some("Dots"), Some("Dots 2")));
assert!(matches!(node(&s, ids_of(&v)[0]).kind, NodeKind::SymbolInstance { ref symbol, .. } if symbol == "Mark 2"));
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(v["added"], 0, "{v}");
}
/// The pattern the first filled object in `n` paints with.
fn fill_of(n: &Node) -> Option<String> {
let mut found = None;
n.walk(&mut |m| {
if found.is_none() {
found = pattern_of(&m.appearance.fill_paint()).map(str::to_string);
}
});
found
}
/// A brush whose art sets type in a character style is not matched to the document's brush of
/// that name and art when the document's style of that name is another one: the style comes in as
/// "Accent 2", and the brush as a copy whose type is set in "Accent 2".
#[test]
fn pasted_brushes_are_not_matched_to_brushes_that_use_another_style() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ink"})).unwrap());
s.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 40}})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Accent", "id": t.0})).unwrap();
let name = s.execute("brush.new", &json!({"type": "art", "name": "Lettering", "ids": [t.0]})).unwrap()["name"].as_str().unwrap().to_string();
let path = rect(&mut s, 200.0, 200.0, 40.0, 10.0);
s.execute("brush.apply", &json!({"name": name, "ids": [path.0]})).unwrap();
let brush = vectorcraft_brush::find(doc(&s), &name).unwrap();
copy(&mut s, &[path]);
new_doc(&mut s);
s.execute("charStyle.new", &json!({"name": "Accent", "attrs": {"kerning": 10}})).unwrap();
let d = doc_mut(&mut s);
let mut lib = vectorcraft_brush::library(d);
lib.push(brush);
vectorcraft_brush::store(d, &lib);
let v = s.execute("edit.paste", &json!({})).unwrap();
let names = renamed(&v);
let copied = names.iter().find(|(k, from, _)| k == "brush" && *from == name).map(|(_, _, to)| to.clone());
assert!(names.contains(&("charStyle".to_string(), "Accent".to_string(), "Accent 2".to_string())), "{v}");
let copied = copied.unwrap_or_else(|| panic!("the brush is added under a free name: {v}"));
let style_of = |s: &Session, b: &str| {
let b = vectorcraft_brush::find(doc(s), b).unwrap();
let mut found = None;
for a in b.art() {
a.walk(&mut |m| {
if let NodeKind::Text(tx) = &m.kind {
found = found.take().or_else(|| tx.runs[0].style.style_name.clone());
}
});
}
found
};
assert_eq!((style_of(&s, &name).as_deref(), style_of(&s, &copied).as_deref()), (Some("Accent"), Some("Accent 2")));
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(v["added"], 0, "{v}");
}
#[test]
fn brushes_travel_with_their_strokes() {
let mut s = session();
+3 -1
View File
@@ -77,10 +77,12 @@ fn saturate_needs_a_number_intensity() {
let mut s = session();
let a = rect(&mut s, json!("#cc6666"));
let undo = s.doc().unwrap().history.undo.len();
for p in [json!({}), json!({"intensity": "40"}), json!({"intensity": null})] {
for p in [json!({}), json!({"intensity": null})] {
let e = s.execute("edit.colors.saturate", &p).unwrap_err().to_string();
assert!(e.contains("missing number `intensity`"), "{p}: {e}");
}
let e = s.execute("edit.colors.saturate", &json!({"intensity": "40"})).unwrap_err().to_string();
assert!(e.contains("`intensity` must be a number, not \"40\""), "{e}");
assert_eq!(fill_of(&s, a).to_hex(), "#cc6666");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
s.execute("edit.colors.saturate", &json!({"intensity": 100})).unwrap();
+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();
+39
View File
@@ -104,6 +104,45 @@ fn the_object_brought_over_shows_no_seam_of_the_one_below() {
assert!(worst < 8, "blue shows through ring A at the top crossing (blue {worst})");
}
fn green(r: &Rendered, x: u32, y: u32) -> bool {
let p = r.pixel(x, y);
p[3] > 200 && p[1] > 200 && p[0] < 60 && p[2] < 60
}
/// The margin an object brought over another is raised in past their overlap reaches only where
/// that object alone paints: a third member that meets the overlap's edge stays in front of it
/// there. Red A (20..80 × 20..60) and blue B (40..60 × 30..70) overlap in 40..60 × 30..60; the
/// green sliver C (38..40 × 40..50), in front of both, meets that overlap at x = 40 over A only.
#[test]
fn raising_one_overlap_keeps_an_adjacent_third_member_above_its_seam() {
let mut s = session();
let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64, color: &str| {
let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap());
s.execute("paint.setFill", &json!({"ids": [id.0], "color": color})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap();
id
};
let a = rect(&mut s, 20.0, 20.0, 60.0, 40.0, "#ff0000");
let b = rect(&mut s, 40.0, 30.0, 20.0, 40.0, "#0000ff");
let c = rect(&mut s, 38.0, 40.0, 2.0, 10.0, "#00ff00");
select(&mut s, &[a, b, c]);
let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
let r = render(&s);
assert!(green(&r, 39, 45) && blue(&r, 50, 45) && red(&r, 39, 55));
let v = arrange(&mut s, json!({"at": [50, 45], "order": "front", "member": a.0}));
assert_eq!((&v["count"], &v["top"]), (&json!(1), &json!([a.0])));
assert_eq!(order_at(&s.doc().unwrap().doc, g, 50.0, 45.0), [b, a]);
let r = render(&s);
assert!(red(&r, 50, 45), "A is brought over B");
assert!(green(&r, 39, 45), "C stays in front of A within the margin");
assert!(red(&r, 39, 55));
let raised = area(&s, a).unwrap();
let inside = |x, y| vectorcraft_tools::intertwine::contains(&raised, vectorcraft_geom::Point::new(x, y));
assert!(inside(50.5, 45.5), "the overlap");
assert!(inside(39.5, 55.5), "the margin where only A paints");
assert!(!inside(39.5, 45.5), "the margin leaves out where C paints too");
}
#[test]
fn clicking_the_same_overlap_again_swaps_back() {
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");
+51
View File
@@ -484,6 +484,57 @@ fn a_malformed_object_id_is_not_reported_as_missing() {
assert_eq!(undo(&s), before);
}
/// A required number given as something other than a number (`"40"`, `true`, `[]`, `{}`) is refused
/// as the wrong type, naming its key and showing the value as given, not as a missing number; one left
/// out or given as null is still a missing number. Neither changes the document or records an undo step.
#[test]
fn a_malformed_required_number_is_not_reported_as_missing() {
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 doc = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let with = |base: &serde_json::Value, key: &str, v: Option<serde_json::Value>| {
let mut p = base.clone();
let o = p.as_object_mut().unwrap();
match v {
Some(v) => o.insert(key.into(), v),
None => o.remove(key),
};
p
};
let cases = [
("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}), "x"),
("edit.colors.saturate", json!({"intensity": 40}), "intensity"),
("object.envelope.setMeshPoint", json!({"id": 1, "index": 0, "x": 0, "y": 0}), "index"),
("object.envelope.setMeshPoint", json!({"id": 1, "index": 0, "x": 0, "y": 0}), "x"),
("object.mesh.movePoint", json!({"id": 1, "index": 0, "x": 0, "y": 0}), "y"),
("guide.add", json!({"pos": 40}), "pos"),
];
for (cmd, base, key) in &cases {
for (v, shown) in [(json!("40"), "\"40\""), (json!(true), "true"), (json!([]), "[]"), (json!({}), "{}")] {
let p = with(base, key, Some(v));
match s.execute(cmd, &p) {
Err(EngineError::BadParams { cmd: c, msg }) => {
assert_eq!((c.as_str(), msg), (*cmd, format!("`{key}` must be a number, not {shown}")), "{p}");
}
other => panic!("{cmd} {p}: {other:?}"),
}
}
for p in [with(base, key, None), with(base, key, Some(json!(null)))] {
match s.execute(cmd, &p) {
Err(EngineError::BadParams { cmd: c, msg }) => assert_eq!((c.as_str(), msg), (*cmd, format!("missing number `{key}`")), "{p}"),
other => panic!("{cmd} {p}: {other:?}"),
}
}
}
assert_eq!(s.doc().unwrap().doc, doc);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
// A whole JSON number is a number for a fractional parameter.
s.execute("guide.add", &json!({"pos": 40})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
}
/// A command that takes the keys of one that isn't checked yet isn't checked either.
#[test]
fn a_reference_to_an_unchecked_command_is_unchecked() {
+23
View File
@@ -329,6 +329,29 @@ fn expanding_a_fill_gives_its_plug_in_effect_the_fill_it_sits_on() {
assert_eq!(clip.path_data().unwrap().bounds(), triangle().bounds(), "the triangle the canvas fills");
}
/// A plug-in effect on a fill, before the fill's own 3D Revolve, is given the fill it sits on
/// (`_context.item`), so the fill revolves the shape the plug-in returns for it.
#[test]
fn a_fills_revolve_gives_the_plug_in_effect_before_it_the_fill_it_sits_on() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let tri = json!({"objects": [{"path": triangle()}]}).to_string();
let on_fill = tpl::when_given(&tpl::manifest("test.engine.revolvefill", "effect", "{}"), tpl::Given::Params, r#""item":{"fill":0}"#, &tri);
install_wat(&mut s, &on_fill);
let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap();
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.revolvefill", "item": fill}));
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "threeD.revolve", "item": fill}));
let n = node(&s, id);
// The same object with the triangle as its path and only the Revolve on its fill.
let mut expected = n.clone();
if let vectorcraft_doc::NodeKind::Path { path, .. } = &mut expected.kind {
*path = triangle();
}
expected.appearance.items[fill].effects_mut().retain(|e| e.id == "threeD.revolve");
let art = vectorcraft_render::effects::revolve_art(&n).unwrap();
assert_eq!(art, vectorcraft_render::effects::revolve_art(&expected).unwrap(), "the fill revolves the triangle");
}
/// The manifest of a test live effect `id` that declares `paintOutput` (at `api` 2), or that
/// doesn't (`paints` off).
fn painting(id: &str, paints: bool) -> String {
+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");
}
}
+269
View File
@@ -1079,3 +1079,272 @@ fn global_adjust_refuses_params_of_the_wrong_form() {
run(&mut s, "recolor.apply", json!({"map": map, "globalAdjust": {"saturation": null, "temperature": -100}}));
assert_ne!(fill(&s, art).to_hex(), "#ff0000", "an amount at the end of the range applies");
}
/// A placed `w` × `h` px image whose left half is `left` and right half `right` (RGBA), and its
/// bounds on the page.
fn halves_image(s: &mut Session, w: u32, h: u32, left: [u8; 4], right: [u8; 4]) -> (NodeId, vectorcraft_geom::Rect) {
let img = image::RgbaImage::from_fn(w, h, |x, _| image::Rgba(if x < w / 2 { left } else { right }));
let mut png = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let r = run(s, "file.place", json!({"name": "halves.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
let id = NodeId(r["ids"][0].as_u64().unwrap());
let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap();
(id, b)
}
fn pick_theme(s: &mut Session, p: Value) -> Vec<String> {
keys(&run(s, "recolor.pickTheme", p)["colors"])
}
/// A click takes the palette of the object a Selection tool click takes (a whole group), the most
/// used color first, each in its own model; a click on empty canvas or on a hidden object takes
/// nothing. Locked objects are read. Picking changes nothing.
#[test]
fn theme_picker_click_takes_the_palette_of_the_whole_object() {
let mut s = session();
let a = rect(&mut s, json!("#ff0000"));
let b = rect(&mut s, json!({"c": 0, "m": 0, "y": 100, "k": 0}));
let c = rect(&mut s, json!("#ff0000"));
run(&mut s, "paint.setStroke", json!({"ids": [c.0], "color": "#0000ff"}));
// x 70 to 85 and 90 to 105.
let hidden = rect(&mut s, json!("#00ff00"));
let locked = rect(&mut s, json!("#ff00ff"));
run(&mut s, "select.set", json!({"ids": [a.0, b.0, c.0]}));
run(&mut s, "object.group", json!({}));
run(&mut s, "object.hide", json!({"ids": [hidden.0]}));
run(&mut s, "object.lock", json!({"ids": [locked.0]}));
let undo = s.doc().unwrap().history.undo.len();
let doc = s.doc().unwrap().doc.clone();
// A click on `b` (x 30 to 45): the group's three rectangles, red the most used.
let r = run(&mut s, "recolor.pickTheme", json!({"picks": [{"at": [37, 17]}]}));
assert_eq!(keys(&r["colors"]), ["rgb 255 0 0", "cmyk 0 0 100 0", "rgb 0 0 255"], "{r}");
assert_eq!(r["objects"], 3);
assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [37, 17]}], "colors": 2})).len(), 2, "at most `colors`");
assert!(pick_theme(&mut s, json!({"picks": [{"at": [300, 150]}]})).is_empty(), "empty canvas");
assert!(pick_theme(&mut s, json!({"picks": [{"at": [77, 17]}]})).is_empty(), "a hidden object");
assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [97, 17]}]})), ["rgb 255 0 255"], "a locked object");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &doc), "the document stays as it was");
}
/// A marquee takes the part of an image inside it and every painted object it touches; several
/// picks (Shift) add up. A click on an image takes all its pixels.
#[test]
fn theme_picker_marquee_takes_the_area_and_picks_add_up() {
let mut s = session();
let (_, b) = halves_image(&mut s, 64, 32, [255, 0, 0, 255], [0, 0, 255, 255]);
let (mid, y) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
let left = json!({"rect": [b.x0 + 1.0, b.y0 + 1.0, mid - 1.0, b.y1 - 1.0]});
assert_eq!(pick_theme(&mut s, json!({"picks": [left]})), ["rgb 255 0 0"], "the left half alone");
let right_backwards = json!({"rect": [b.x1 - 1.0, b.y1 - 1.0, mid + 1.0, b.y0 + 1.0]});
assert_eq!(pick_theme(&mut s, json!({"picks": [right_backwards]})), ["rgb 0 0 255"], "a marquee drawn backwards");
let both = pick_theme(&mut s, json!({"picks": [left, right_backwards]}));
assert_eq!(both.len(), 2, "Shift adds a second area: {both:?}");
assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [mid, y]}]})).len(), 2, "a click takes the whole image");
// Two rectangles away from the image: a marquee touching both takes both.
let r1 = rect(&mut s, json!("#00ff00"));
let r2 = rect(&mut s, json!("#ffff00"));
let (b1, b2) = {
let d = &s.doc().unwrap().doc;
(d.node(r1).unwrap().visual_bounds().unwrap(), d.node(r2).unwrap().visual_bounds().unwrap())
};
let over = json!({"rect": [b1.x1 - 2.0, b1.y0 + 2.0, b2.x0 + 2.0, b1.y0 + 4.0]});
let mut got = pick_theme(&mut s, json!({"picks": [over]}));
got.sort();
assert_eq!(got, ["rgb 0 255 0", "rgb 255 255 0"]);
}
/// Pixels less than half opaque are left out, and so is an image whose pixels can't be read.
#[test]
fn theme_picker_leaves_out_clear_pixels_and_unreadable_images() {
let mut s = session();
let (_, b) = halves_image(&mut s, 8, 8, [255, 0, 0, 255], [0, 0, 255, 100]);
let all = json!({"rect": [b.x0, b.y0, b.x1, b.y1]});
assert_eq!(pick_theme(&mut s, json!({"picks": [all]})), ["rgb 255 0 0"]);
let cut = super::menucmds::place_undecodable_png(&mut s);
let cb = s.doc().unwrap().doc.node(cut).unwrap().visual_bounds().unwrap();
let r = run(&mut s, "recolor.pickTheme", json!({"picks": [{"rect": [cb.x0, cb.y0, cb.x1, cb.y1]}]}));
assert!(r["colors"].as_array().unwrap().iter().all(|k| k == "rgb 255 0 0"), "the undecodable image adds nothing: {r}");
}
/// A large image is read through about 65,536 pixels: its palette still holds both halves.
#[test]
fn theme_picker_reads_a_large_image_within_its_pixel_budget() {
let mut s = session();
let (_, b) = halves_image(&mut s, 2000, 1000, [10, 200, 30, 255], [250, 240, 10, 255]);
let (mid, y) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
let mut got = pick_theme(&mut s, json!({"picks": [{"at": [mid, y]}]}));
got.sort();
assert_eq!(got, ["rgb 10 200 30", "rgb 250 240 10"]);
}
/// A symbol instance gives the colors of the art it shows, by a click or a marquee; a pattern fill
/// gives the colors of its tile and of the patterns the tile uses.
#[test]
fn theme_picker_reads_symbol_art_and_nested_patterns() {
let mut s = session();
let r = rect(&mut s, json!("#00ff00"));
run(&mut s, "select.set", json!({"ids": [r.0]}));
let inst = NodeId(run(&mut s, "symbol.new", json!({"name": "Dot"}))["id"].as_u64().unwrap());
let b = s.doc().unwrap().doc.node(inst).unwrap().visual_bounds().unwrap();
let (cx, cy) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [cx, cy]}]})), ["rgb 0 255 0"], "a click on the instance");
assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [cx, cy, cx + 1.0, cy + 1.0]}]})), ["rgb 0 255 0"], "a marquee");
select_all(&mut s);
run(&mut s, "edit.clear", json!({}));
// Pattern "inner" of a red square fills a square, which becomes pattern "outer".
let red = rect(&mut s, json!("#ff0000"));
let inner = run(&mut s, "object.pattern.make", json!({"ids": [red.0], "edit": false}))["name"].as_str().unwrap().to_string();
let tile = rect(&mut s, json!("#0000ff"));
run(&mut s, "paint.setFill", json!({"ids": [tile.0], "swatch": inner}));
let outer = run(&mut s, "object.pattern.make", json!({"ids": [tile.0], "edit": false}))["name"].as_str().unwrap().to_string();
let art = rect(&mut s, json!("#0000ff"));
run(&mut s, "paint.setFill", json!({"ids": [art.0], "swatch": outer}));
let b = s.doc().unwrap().doc.node(art).unwrap().visual_bounds().unwrap();
let got = pick_theme(&mut s, json!({"picks": [{"at": [(b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]}]}));
assert!(got.contains(&"rgb 255 0 0".to_string()), "the inner pattern's red: {got:?}");
}
/// A grayscale image that a fill color colorizes gives that color, not its grays.
#[test]
fn theme_picker_reads_the_color_of_a_colorized_image() {
let mut s = session();
let mut png = Vec::new();
image::GrayImage::from_pixel(8, 8, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let r = run(&mut s, "file.place", json!({"name": "gray.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
let id = NodeId(r["ids"][0].as_u64().unwrap());
let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap();
let at = json!({"picks": [{"at": [(b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]}]});
assert_eq!(pick_theme(&mut s, at.clone()), ["rgb 90 90 90"], "uncolorized: its grays");
run(&mut s, "paint.setFill", json!({"ids": [id.0], "color": "#ff0000"}));
assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "the fill colorizes the image");
assert_eq!(pick_theme(&mut s, at), ["rgb 255 0 0"]);
}
/// A hidden fill gives no color, and a marquee in a clip group reads only what the clipping path
/// lets through.
#[test]
fn theme_picker_leaves_out_hidden_fills_and_clipped_art() {
let mut s = session();
let shape = |s: &mut Session, x: f64, w: f64, fill: &str| {
let id = NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": w, "height": 15}))["id"].as_u64().unwrap());
run(s, "paint.setFill", json!({"ids": [id.0], "color": fill}));
run(s, "paint.setStroke", json!({"ids": [id.0], "none": true}));
id
};
let hidden = shape(&mut s, 200.0, 15.0, "#ff00ff");
run(&mut s, "select.set", json!({"ids": [hidden.0]}));
run(&mut s, "appearance.setItem", json!({"index": 0, "visible": false}));
assert!(pick_theme(&mut s, json!({"picks": [{"rect": [205, 12, 210, 20]}]})).is_empty(), "a hidden fill");
// A marquee inside an outlined square without a fill misses it; inside a filled one it takes it.
let outline = shape(&mut s, 250.0, 40.0, "#00ffff");
run(&mut s, "paint.setFill", json!({"ids": [outline.0], "none": true}));
run(&mut s, "paint.setStroke", json!({"ids": [outline.0], "color": "#ffff00"}));
assert!(pick_theme(&mut s, json!({"picks": [{"rect": [260, 13, 270, 20]}]})).is_empty(), "inside the outline");
assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [245, 13, 260, 20]}]})), ["rgb 255 255 0"], "across the outline");
run(&mut s, "paint.setFill", json!({"ids": [outline.0], "color": "#00ffff"}));
assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [260, 13, 270, 20]}]})).len(), 2, "inside the fill");
// Red runs from x 10 to 110 and green from 50 to 60; the clipping path lets x 10 to 40 through.
let red = shape(&mut s, 10.0, 100.0, "#ff0000");
let green = shape(&mut s, 50.0, 10.0, "#00ff00");
let clip = shape(&mut s, 10.0, 30.0, "#0000ff");
run(&mut s, "select.set", json!({"ids": [red.0, green.0, clip.0]}));
run(&mut s, "object.clippingMask.make", json!({}));
assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [30, 12, 55, 20]}]})), ["rgb 255 0 0"]);
}
/// An image in a clip group gives only the pixels inside its clipping path, by a click or a
/// marquee.
#[test]
fn theme_picker_reads_an_image_inside_its_clipping_path() {
let mut s = session();
// Red, with blue 6 × 3 px blocks in the corners, which an ellipse inscribed in the image leaves out.
let (w, h) = (64, 32);
let img = image::RgbaImage::from_fn(w, h, |x, y| {
let corner = (x < 6 || x >= w - 6) && (y < 3 || y >= h - 3);
image::Rgba(if corner { [0, 0, 255, 255] } else { [255, 0, 0, 255] })
});
let mut png = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let r = run(&mut s, "file.place", json!({"name": "corners.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
let id = NodeId(r["ids"][0].as_u64().unwrap());
let b = s.doc().unwrap().doc.node(id).unwrap().visual_bounds().unwrap();
let all = json!({"picks": [{"rect": [b.x0, b.y0, b.x1, b.y1]}]});
assert_eq!(pick_theme(&mut s, all.clone()).len(), 2, "unclipped: red and blue");
let e = NodeId(run(&mut s, "shape.ellipse", json!({"x": b.x0, "y": b.y0, "width": b.width(), "height": b.height()}))["id"].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [id.0, e.0]}));
run(&mut s, "object.clippingMask.make", json!({}));
assert_eq!(pick_theme(&mut s, all), ["rgb 255 0 0"], "a marquee");
let center = json!({"picks": [{"at": [(b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]}]});
assert_eq!(pick_theme(&mut s, center), ["rgb 255 0 0"], "a click");
}
/// An object in a clip group that its clipping path hides gives no color, even inside the
/// clipping path's box.
#[test]
fn theme_picker_leaves_out_art_a_curved_clipping_path_hides() {
let mut s = session();
let shape = |s: &mut Session, x: f64, y: f64, w: f64, h: f64, fill: &str| {
let id = NodeId(run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].as_u64().unwrap());
run(s, "paint.setFill", json!({"ids": [id.0], "color": fill}));
run(s, "paint.setStroke", json!({"ids": [id.0], "none": true}));
id
};
// A red square in the middle of a 100 × 100 ellipse, and a green one in its top left corner.
let red = shape(&mut s, 40.0, 40.0, 20.0, 20.0, "#ff0000");
let green = shape(&mut s, 0.0, 0.0, 8.0, 8.0, "#00ff00");
let e = NodeId(run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 100, "height": 100}))["id"].as_u64().unwrap());
let all = json!({"picks": [{"rect": [-5, -5, 105, 105]}]});
let mut both = pick_theme(&mut s, all.clone());
both.retain(|k| k == "rgb 255 0 0" || k == "rgb 0 255 0");
assert_eq!(both.len(), 2, "unclipped: both squares");
run(&mut s, "select.set", json!({"ids": [red.0, green.0, e.0]}));
run(&mut s, "object.clippingMask.make", json!({}));
assert_eq!(pick_theme(&mut s, all), ["rgb 255 0 0"], "the corner square is hidden");
}
/// In isolation mode a click and a marquee read only the isolated art.
#[test]
fn theme_picker_reads_only_the_isolated_art() {
let mut s = session();
let a = rect(&mut s, json!("#ff0000"));
let b = rect(&mut s, json!("#0000ff"));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
// Green on top of the blue square (x 30 to 45).
let green = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 10, "width": 15, "height": 15}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"ids": [green.0], "color": "#00ff00"}));
run(&mut s, "paint.setStroke", json!({"ids": [green.0], "none": true}));
assert_eq!(pick_theme(&mut s, json!({"picks": [{"at": [37, 17]}]})), ["rgb 0 255 0"], "outside isolation: the top object");
run(&mut s, "object.isolate", json!({"id": g.0}));
let got = pick_theme(&mut s, json!({"picks": [{"at": [37, 17]}]}));
assert_eq!(got, ["rgb 0 0 255"], "a click reaches the isolated blue square under the green one");
let mut got = pick_theme(&mut s, json!({"picks": [{"rect": [5, 5, 60, 30]}]}));
got.sort();
assert_eq!(got, ["rgb 0 0 255", "rgb 255 0 0"], "a marquee leaves out the green square");
}
/// Bad parameters are refused with an error naming them.
#[test]
fn theme_picker_refuses_bad_params() {
let mut s = session();
rect(&mut s, json!("#ff0000"));
let many: Vec<Value> = (0..257).map(|_| json!({"at": [0, 0]})).collect();
for (p, msg) in [
(json!({}), "missing `picks`"),
(json!({"picks": {"at": [0, 0]}}), "`picks` must be an array"),
(json!({"picks": []}), "`picks` must hold 1 to 256 picks (got 0)"),
(json!({"picks": many}), "`picks` must hold 1 to 256 picks (got 257)"),
(json!({"picks": [{"at": [0]}]}), "`at` must be [x, y]"),
(json!({"picks": [{"at": ["1", 2]}]}), "`at` must be [x, y]"),
(json!({"picks": [{"rect": [0, 0, 10]}]}), "`rect` must be [x0, y0, x1, y1]"),
(json!({"picks": [{"at": [0, 0], "rect": [0, 0, 1, 1]}]}), "each pick is"),
(json!({"picks": [{"point": [0, 0]}]}), "each pick is"),
(json!({"picks": [{"at": [0, 0]}], "colors": 0}), "`colors` must be between 1 and 64 (got 0)"),
(json!({"picks": [{"at": [0, 0]}], "colors": 65}), "`colors` must be between 1 and 64 (got 65)"),
(json!({"picks": [{"at": [0, 0]}], "colors": 2.5}), "`colors` must be a whole number"),
] {
let e = s.execute("recolor.pickTheme", &p).unwrap_err().to_string();
assert!(e.contains(msg), "{p}: {e}");
}
}
+10
View File
@@ -170,6 +170,16 @@ fn an_error_names_the_script_its_place_and_kind() {
assert_eq!(s.script_report().unwrap()["line"], 1);
}
/// An error raised where the run has no place for it, such as in code `eval` compiled, is named
/// with the script and its kind alone, with one colon after the script's name.
#[test]
fn an_error_without_a_place_names_the_script_and_kind() {
let mut s = two_docs();
let e = run(&mut s, "eval(\"throw new TypeError('no')\");").unwrap_err().to_string();
assert_eq!(s.script_report().unwrap()["line"], 0);
assert_eq!(e, "t.js: TypeError: no (thrown)");
}
#[test]
fn bad_parameters_are_refused_before_anything_runs() {
let mut s = two_docs();
+1 -1
View File
@@ -644,7 +644,7 @@ impl<'a> Writer<'a> {
}
NodeKind::Compound { rule, .. } => self.shape(n, &compound_path(n), *rule, xy),
NodeKind::Text(_) => self.text(n, xy),
NodeKind::Image(im) => self.image(im, xy),
NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im), xy),
NodeKind::SymbolInstance { symbol, xf } if self.live_instance_in_room(n, symbol, *xf) => self.symbol_instance(symbol, *xf, xy),
NodeKind::SymbolInstance { symbol, xf } => {
if !self.open_group("u") {
+313 -13
View File
@@ -189,6 +189,111 @@ fn with_strokes(kind: &NodeKind) -> Option<NodeKind> {
Some(kind)
}
/// How far, in points, the sides of two boxes may lie apart and still count as the same side: the
/// glyphs' box (from type's ink) and the box of what type paints (from its outlines) measure one
/// outline two ways, and where they meet they differ by rounding only ([`painted_margin`],
/// [`same_box`]).
const PAINTED_SLACK: f64 = 1e-4;
/// The box of what the pieces of type's outlines `outlines` ([`vectorcraft_effects::outline_text`])
/// paint as an envelope with Distort Appearance bends them: each piece baked as the envelope bakes
/// it ([`vectorcraft_effects::bake_type_appearance`]: geometry effects on its fills and strokes
/// applied, so a stroke a Transform effect moves counts where it is moved to), measured by its
/// visual bounds. Those are exact for miter joins (a tip counts where the miter limit keeps it) and
/// round joins, and an upper bound for bevel joins, miters the limit cuts, width profiles and
/// square-capped dashes; a contour of zero length, which paints nothing, doesn't count. Effects on
/// the type object itself are left out: VectorCraft applies them after the envelope bends the type.
/// `None` when nothing in it has bounds.
fn painted_outlines(outlines: &Node) -> Option<Rect> {
outlines.children().into_iter().flatten().fold(None, |acc, piece| {
let baked = vectorcraft_effects::bake_type_appearance(None, piece);
vectorcraft_geom::union_opt(acc, baked.as_ref().unwrap_or(piece).visual_bounds())
})
}
/// The box of `content` an envelope of type with Distort Appearance may map from in a file besides
/// [`half_stroked_box`]: what it paints, type by its outlines ([`painted_outlines`]), groups by
/// their members grown by as far as their own strokes paint along a side, other objects by their
/// bounds with strokes. `None` when nothing in it has bounds.
fn painted_box(content: &[Arc<Node>]) -> Option<Rect> {
fn walk(n: &Arc<Node>, acc: Option<Rect>) -> Option<Rect> {
match &n.kind {
NodeKind::Text(_) => vectorcraft_geom::union_opt(acc, vectorcraft_effects::outline_text(n).as_ref().and_then(painted_outlines)),
NodeKind::Group { children, clip: false } => {
let along = n.appearance.painted_strokes().map(|s| s.side_reach(true)).fold(0.0, f64::max);
let members = children.iter().fold(None, |acc, c| walk(c, acc));
let grown = |r: Rect| if along.is_finite() && along > 0.0 { r.inflate(along, along) } else { r };
vectorcraft_geom::union_opt(acc, members.map(grown))
}
_ => vectorcraft_geom::union_opt(acc, envelope_content_boxes(std::slice::from_ref(n), Affine::IDENTITY).map(|(stroked, _)| stroked)),
}
}
content.iter().fold(None, |acc, c| walk(c, acc))
}
/// The bounds margin of `painted`, the box of what contents with geometric box `plain` paint, a side
/// within [`PAINTED_SLACK`] of the geometric box's counting as that side. `None` where it lies
/// inside the geometric box on a side, where it is that box, and for margins that don't fit.
fn painted_margin(painted: Rect, plain: Rect) -> Option<[f32; 4]> {
let side = |p: f64, g: f64| if (p - g).abs() <= PAINTED_SLACK { g } else { p };
let painted = Rect::new(side(painted.x0, plain.x0), side(painted.y0, plain.y0), side(painted.x1, plain.x1), side(painted.y1, plain.y1));
let margin = envelope_stroke_margin(painted, plain)?;
(margin.iter().all(|m| *m >= 0.0) && margin.iter().any(|m| *m > 0.0)).then_some(margin)
}
/// Do bounds margins `a` and `b` give contents with geometric box `plain` the same box, each side
/// within [`PAINTED_SLACK`]?
fn same_box(a: [f32; 4], b: [f32; 4], plain: Rect) -> bool {
let sizes = [plain.height(), plain.height(), plain.width(), plain.width()];
a.iter().zip(b).zip(sizes).all(|((a, b), size)| (f64::from(*a) - f64::from(b)).abs() * size <= PAINTED_SLACK)
}
/// What the contents of an envelope of type paint ([`painted_box`]): their geometric box and the
/// bounds margin of what they paint from it.
#[derive(Clone, Copy)]
struct Painted {
plain: Rect,
margin: [f32; 4],
}
/// [`Painted`] for envelope `kind` with Distort Appearance; `None` without it, and where
/// [`painted_margin`] gives none.
fn painted_of(kind: &NodeKind) -> Option<Painted> {
let NodeKind::Envelope { content, options, .. } = kind else { return None };
if !options.distort_appearance {
return None;
}
let (_, plain) = envelope_content_boxes(content, Affine::IDENTITY)?;
Some(Painted { plain, margin: painted_margin(painted_box(content)?, plain)? })
}
/// Envelope `kind` mapping from what its contents paint (`painted`, [`painted_of`]), for an
/// envelope with Distort Appearance where that box is neither the one it maps from already nor its
/// contents' glyphs grown by half their strokes' weight ([`with_strokes`]); `None` otherwise.
fn as_painted(kind: &NodeKind, painted: &Painted) -> Option<NodeKind> {
let NodeKind::Envelope { options, .. } = kind else { return None };
let half = match with_strokes(kind) {
Some(NodeKind::Envelope { options, .. }) => Some(options.bounds_margin),
_ => None,
};
let Painted { plain, margin } = *painted;
if !options.distort_appearance || same_box(margin, options.bounds_margin, plain) || half.is_some_and(|h| same_box(margin, h, plain)) {
return None;
}
let mut kind = kind.clone();
if let NodeKind::Envelope { options, .. } = &mut kind {
options.bounds_margin = margin;
}
Some(kind)
}
/// A way an envelope of type is tried: a kind, or a kind mapping from what its type paints
/// ([`as_painted`]), worked out when its turn comes.
enum Way {
As(NodeKind),
Painted(NodeKind),
}
/// The kind of `envelope`, a mesh or a top object in Edit Contents, with its grid moved onto
/// `drawn`, the drawn art the file saves for it, where what it draws is as large as that art (within
/// [`MOVED_SLACK`]) but lies elsewhere (further than that): moved by as far as the drawn art's box
@@ -593,7 +698,8 @@ impl WarpedType {
/// for it ([`live_on_saved_grid`]), which opens in its place where it does: its type stays
/// editable in that shape, and the warp's style and bend are lost. With Distort Appearance, each
/// is also checked mapping from its type's glyphs grown by half their strokes' weight
/// ([`with_strokes`]). In Edit Contents, a mesh or top object whose grid draws the type
/// ([`with_strokes`]) and, after all of those, from what its type paints where that is another
/// box ([`as_painted`]). In Edit Contents, a mesh or top object whose grid draws the type
/// elsewhere than its drawn art is checked last moved onto that art ([`moved_onto`]). Each
/// check uses one of the import's checks and, for an envelope that shows, adds to what the page
/// check allows ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't
@@ -660,17 +766,16 @@ impl WarpedType {
// With Distort Appearance, a file's envelope may map its type from its glyphs grown by half
// their strokes' weight or from the glyphs alone, and for type the size the file saves for
// that box is often out of date (not the size of the type there now): each is checked.
let kinds: Vec<NodeKind> = live(&obj, before, inner)
.into_iter()
.chain(on_grid)
.flat_map(|k| {
let stroked = with_strokes(&k);
std::iter::once(k).chain(stroked)
})
.collect();
// After all of those, each is checked mapping from what its type paints, where that box is
// another: it is measured only when such a check comes and one is left.
let kinds: Vec<NodeKind> = live(&obj, before, inner).into_iter().chain(on_grid).collect();
if kinds.is_empty() {
return Err(TypeKept::Read);
}
let mut ways: Vec<Way> = kinds.iter().flat_map(|k| std::iter::once(Way::As(k.clone())).chain(with_strokes(k).map(Way::As))).collect();
ways.extend(kinds.into_iter().map(Way::Painted));
// What the type paints, measured once: the kinds share their contents.
let mut painted: Option<Option<Painted>> = None;
let (id, layer) = (doc.alloc_id(), doc.alloc_id());
let mut plain = art.clone();
(plain.visible, plain.opacity) = (true, 1.0);
@@ -678,9 +783,9 @@ impl WarpedType {
let mut alike = None;
// In Edit Contents, a grid that draws the type elsewhere than its drawn art is tried again
// moved onto that art ([`moved_onto`]), after every other way.
let (mut tries, mut moved, mut again, mut i) = (kinds.into_iter(), vec![], false, 0);
let (mut tries, mut moved, mut again, mut i) = (ways.into_iter(), vec![], false, 0);
loop {
let Some(kind) = tries.next() else {
let Some(way) = tries.next() else {
if again || moved.is_empty() {
break;
}
@@ -693,6 +798,13 @@ impl WarpedType {
if self.checks == 0 || (i > 0 && self.checks <= waiting + self.looks.len()) {
return Err(TypeKept::Budget);
}
let kind = match way {
Way::As(kind) => kind,
Way::Painted(base) => match painted.get_or_insert_with(|| painted_of(&base)).as_ref().and_then(|p| as_painted(&base, p)) {
Some(kind) => kind,
None => continue,
},
};
self.checks -= 1;
i += 1;
let mut envelope = art.clone();
@@ -705,7 +817,7 @@ impl WarpedType {
break;
}
if !again && let Some(kind) = moved_onto(&live_one, &plain) {
moved.push(kind);
moved.push(Way::As(kind));
}
}
let envelope = alike.ok_or(TypeKept::Differs)?;
@@ -867,7 +979,7 @@ fn alike_within(live: &Node, drawn: &Node, reach: Option<Rect>, layer: NodeId, s
mod tests {
use super::*;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{AppearanceItem, CharStyle, LineJoin, StrokeLayer, TextObject};
use vectorcraft_doc::{AppearanceItem, CharStyle, LineCap, LineJoin, StrokeLayer, TextObject};
/// An envelope of `content` with Distort Appearance, on a flat one-patch mesh.
fn envelope_of(content: Vec<Arc<Node>>) -> NodeKind {
@@ -949,4 +1061,192 @@ mod tests {
let (_, glyphs) = envelope_content_boxes(&content, Affine::IDENTITY).unwrap();
assert_eq!(stroked_margin(content), envelope_stroke_margin(glyphs.inflate(2.0, 2.0), glyphs));
}
/// Is the font type takes by default installed? Type that must draw as itself is tested only
/// where it is: the tests below measure its glyphs.
fn default_font() -> bool {
vectorcraft_text::FontDb::global().has_family(&CharStyle::default().font_family)
}
/// The bounds margin of the candidate mapping from what `content` paints, for an envelope of it,
/// type measured by its glyphs as the import measures it; `None` where there is none.
fn painted_candidate(content: Vec<Arc<Node>>) -> Option<[f32; 4]> {
vectorcraft_text::register_envelope_ink();
let kind = envelope_of(content);
match as_painted(&kind, &painted_of(&kind)?) {
Some(NodeKind::Envelope { options, .. }) => Some(options.bounds_margin),
_ => None,
}
}
/// The box contents with geometric box `plain` map from with bounds margin `m`.
fn box_of(m: [f32; 4], plain: Rect) -> Rect {
let [top, bottom, left, right] = m.map(f64::from);
Rect::new(
plain.x0 - left * plain.width(),
plain.y0 - top * plain.height(),
plain.x1 + right * plain.width(),
plain.y1 + bottom * plain.height(),
)
}
/// Are the sides of `a` and `b` within `tol` of each other?
fn close(a: Rect, b: Rect, tol: f64) -> bool {
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() <= tol)
}
/// The geometric box of `content`, type measured by its glyphs as the import measures it.
fn glyphs_of(content: &[Arc<Node>]) -> (Rect, Rect) {
vectorcraft_text::register_envelope_ink();
envelope_content_boxes(content, Affine::IDENTITY).unwrap()
}
/// What the type in `content` paints, measured apart from the import's own measure: each piece
/// of its outlines filled, and outlined by kurbo's stroker with each of its strokes' weight,
/// join and miter limit.
fn stroked_by_kurbo(content: &[Arc<Node>]) -> Rect {
use kurbo::Shape;
let mut out: Option<Rect> = None;
for n in content {
let outlines = vectorcraft_effects::outline_text(n).unwrap();
for piece in outlines.children().unwrap() {
let bp = piece.stroke_path().unwrap();
out = vectorcraft_geom::union_opt(out, Some(bp.bounding_box()));
for s in piece.appearance.painted_strokes() {
let join = match s.join {
LineJoin::Miter => kurbo::Join::Miter,
LineJoin::Round => kurbo::Join::Round,
LineJoin::Bevel => kurbo::Join::Bevel,
};
let stroke = kurbo::Stroke::new(s.width).with_join(join).with_miter_limit(s.miter_limit);
let outline = kurbo::stroke(bp.iter(), &stroke, &kurbo::StrokeOpts::default(), 1e-4);
out = vectorcraft_geom::union_opt(out, Some(outline.bounding_box()));
}
}
}
out.unwrap()
}
/// Type with Distort Appearance and a stroke with miter joins on its appearance is also tried
/// mapped from what that stroke paints: past half its weight where a miter tip pokes out at a
/// sharp corner (the feet of the A's), though not as far as its bounds with strokes, which allow
/// for a miter as long as the limit lets one be at every corner.
#[test]
fn mitred_type_is_also_tried_mapped_from_what_its_stroke_paints_miter_tips_included() {
if !default_font() {
return;
}
let mut text = type_node(1, CharStyle::default());
let mut appearance = (*text.appearance).clone();
appearance.items.push(AppearanceItem::Stroke(mitred()));
text.appearance = appearance.into();
let content = vec![Arc::new(text)];
let (with, glyphs) = glyphs_of(&content);
let (half, painted) = (glyphs.inflate(2.0, 2.0), stroked_by_kurbo(&content));
assert!(painted.x0 < half.x0 - 0.5 && painted.x1 > half.x1 + 0.5, "{painted:?} {half:?}");
assert!(painted.width() < with.width() - 0.5, "{painted:?} {with:?}");
let from = box_of(painted_candidate(content).unwrap(), glyphs);
assert!(close(from, painted, 0.01), "{from:?} {painted:?}");
}
/// Type stroked by its characters with miter joins is also tried mapped from what those strokes
/// paint, turned and stretched as well as upright.
#[test]
fn type_with_a_mitred_character_stroke_is_also_tried_mapped_from_what_it_paints() {
if !default_font() {
return;
}
let style = CharStyle { stroke: Paint::solid(Color::BLACK), stroke_width: 4.0, stroke_join: LineJoin::Miter, ..CharStyle::default() };
for xf in [
Affine::IDENTITY,
Affine::rotate(std::f64::consts::FRAC_PI_4),
Affine::scale_non_uniform(std::f64::consts::SQRT_2, std::f64::consts::FRAC_1_SQRT_2),
] {
let mut text = type_node(1, style.clone());
if let NodeKind::Text(t) = &mut text.kind {
t.xf = xf * t.xf;
}
let content = vec![Arc::new(text)];
let (_, glyphs) = glyphs_of(&content);
let painted = stroked_by_kurbo(&content);
let from = box_of(painted_candidate(content).unwrap(), glyphs);
assert!(close(from, painted, 0.01), "{xf:?}: {from:?} {painted:?}");
}
}
/// A stroke that a Transform effect moves paints where it is moved to: type filled over its
/// glyphs with a round 4 point stroke moved 10 points down is also tried mapped from its glyphs
/// grown by 2 points on the left and right and 12 at the bottom, and not at the top.
#[test]
fn a_stroke_moved_by_a_transform_effect_counts_where_it_paints() {
if !default_font() {
return;
}
let mut text = type_node(1, CharStyle::default());
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0);
(stroke.join, stroke.cap) = (LineJoin::Round, LineCap::Round);
stroke.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({ "moveV": 10.0 }), visible: true });
let mut appearance = (*text.appearance).clone();
appearance.items.push(AppearanceItem::Stroke(stroke));
text.appearance = appearance.into();
let content = vec![Arc::new(text)];
let (_, glyphs) = glyphs_of(&content);
let painted = Rect::new(glyphs.x0 - 2.0, glyphs.y0, glyphs.x1 + 2.0, glyphs.y1 + 12.0);
let from = box_of(painted_candidate(content).unwrap(), glyphs);
assert!(close(from, painted, 0.01), "{from:?} {painted:?}");
}
/// Type whose round-joined stroke paints half its weight past its glyphs everywhere is not tried
/// a second time mapped from what it paints: that is the box of its glyphs grown by half the
/// weight, already tried.
#[test]
fn round_joined_type_is_not_tried_twice_for_the_same_box() {
if !default_font() {
return;
}
let style = CharStyle { stroke: Paint::solid(Color::BLACK), stroke_width: 4.0, stroke_join: LineJoin::Round, ..CharStyle::default() };
let content = vec![Arc::new(type_node(1, style))];
vectorcraft_text::register_envelope_ink();
assert!(with_strokes(&envelope_of(content.clone())).is_some());
assert_eq!(painted_candidate(content), None);
}
/// A contour of zero length paints nothing, so it isn't part of what type's outlines paint: a
/// filled square with a round 2 point stroke and such a contour 5 points above it paints the
/// square grown by 1 point.
#[test]
fn a_contour_of_zero_length_paints_nothing() {
let mut bp = BezPath::new();
bp.move_to((10.0, 10.0));
bp.line_to((20.0, 10.0));
bp.line_to((20.0, 20.0));
bp.line_to((10.0, 20.0));
bp.close_path();
bp.move_to((15.0, 5.0));
bp.line_to((15.0, 5.0));
bp.close_path();
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
(stroke.join, stroke.cap) = (LineJoin::Round, LineCap::Round);
let mut appearance = Appearance::default();
appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))));
appearance.items.push(AppearanceItem::Stroke(stroke));
let piece = Node::path(NodeId(1), PathData::from_bezpath(&bp), appearance);
let outlines = Node::group(NodeId(2), vec![Arc::new(piece)]);
assert_eq!(painted_outlines(&outlines), Some(Rect::new(9.0, 9.0, 21.0, 21.0)));
}
/// A side of what contents paint within a ten-thousandth of a point of their geometric box's is
/// that side, inside it or out: the two boxes measure the same outline two ways. Further inside,
/// there is no box; further out, it counts.
#[test]
fn a_side_within_the_slack_of_the_geometric_box_is_that_side() {
let plain = Rect::new(10.0, 20.0, 110.0, 70.0);
let painted = Rect::new(8.0, 20.0 + 1e-9, 112.0, 72.0);
assert_eq!(painted_margin(painted, plain), Some([0.0, 0.04, 0.02, 0.02]));
assert_eq!(painted_margin(Rect::new(8.0, 20.001, 112.0, 72.0), plain), None);
assert_eq!(painted_margin(plain, plain), None);
let half = [0.04_f32, 0.04, 0.02, 0.02];
assert!(same_box(half, [0.04 + 1e-7, 0.04, 0.02, 0.02], plain));
assert!(!same_box(half, [0.041, 0.04, 0.02, 0.02], plain));
}
}

Some files were not shown because too many files have changed in this diff Show More